We changed order for a list, now we need a mechanism for accessing elements by index with matching behaviour
<p>There is a class BaseFormSet. </p>

<pre><code>class BaseFormSet(object):
    def __iter__(self):
        return iter(self.forms)

    def __getitem__(self, index):
        return self.forms[index]
</code></pre>

<p>Where self.forms is a list. In the documentation they tell us that this class represents a set of forms, the order being in the order they were created. And we can change order: we have to override __iter__() method of BaseFormSet. But if we override __iter__(), we will need to also override __getitem__() to have matching behavior.</p>

<p>Well, this __getitem__() astonishes me a bit.</p>

<p>Well, we are talking about lists, as a matter of fact. So, in the example I'll use a list.</p>

<p>This is what I can think of to the best of my ability:</p>

<pre><code>l = [0, 1, 2, 3, 4, 5] // Imitating a formset.

def get_reversed_index(length, index):
    return -(index+1) % length


def print_result(i):
    reversed_index = get_reversed_index(len(l), i)
    return "Index {}, reversed {}, reversed value {}".format(i, reversed_index, l[reversed_index])
</code></pre>

<p>This seems to reverse the index. But is it a matching behavior which documentation implies?</p>

<p>What troubles me: myMy code seems unable to raise IndexError exception.</p>

<pre><code>IndexError: list index out of range
In case of ordinary 
print(l[10])
</code></pre>

<p>Could you help me: what matching behavour is necessary? And whether my example is garbage?</p>

<p>P.S. The class is from Django.</p>

<p>I'm having trouble understanding your question, but if you mean that you <em>want</em> to raise an exception from your "reversed" indices, then you need to change your <code>get_reversed_index</code> function.</p>

<p>Currently, the output of this function is guaranteed to be in the range <code>[0, length)</code> due to the <code>%</code> or mod operator. So if you want to generate indices that can be out of bounds, try removing the <code>% length</code> ...</p>

python