PEP 322: Reverse Iteration (second revision, please comment)

Peter Otten __peter__ at web.de
Sat Nov 1 03:51:25 EST 2003


Paul Moore wrote:

>> * the sample implementation now clearly shows a check for a custom
>>   reverse method and a guard against being applied to a mapping.
> 
> I stumbled over this, as using the existence of has_key to reject
> mappings seemed odd. Surely even without this check, the sample
> implementation would fail on a mapping, with a KeyError at the yield?

But not reliably so. Assuming the following implementation,

def reversed(x):
    i = len(x)
    while i > 0:
        i -= 1
        yield x[i]

where the check for a custom reverse iterator is also removed because it's a
syntax error in current Python, consider

>>> sample = dict.fromkeys(range(3))
>>> [i for i in reversed(sample)]
[None, None, None]

But this fails:

>>> del sample[1]
>>> [i for i in reversed(sample)]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "reversed.py", line 12, in reversed
    yield x[i]
KeyError: 1
>>>

That is, you could reverse-iterate dictionaries if and only if the
dictionary d has entries for key in range(len(d)), if it were not for the
has_key attribute check, or - with the notorious 

def sorted(l): 
    l.sort()
    return l

sorted(d.keys()) == range(len(d))

Peter





More information about the Python-list mailing list