Missing __length_hint__ in __getitem__ iterator

Giovanni Bajo noway at ask.me
Fri Dec 15 06:38:36 EST 2006


Hello,

given the following object:

 >>> class A(object):
...     def __getitem__(self, idx):
...             if idx >= 10: raise IndexError
...             return idx
...     def __len__(self):
...             return 10
...

I noticed that the iterator that Python constructs:

 >>> a = A()
 >>> i = iter(a)
 >>> dir(i)
['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', 
'__init__', '__iter__', '__len__', '__new__', '__reduce__', '__reduce_ex__', 
'__repr__', '__setattr__', '__str__', 'next']

does not have a __length_hint__ method.

Is this just a missing optimization, or there is a deep semantic reason for 
which a __length_hint__ could not be constructed out of the __len__ result?
-- 
Giovanni Bajo



More information about the Python-list mailing list