Missing __length_hint__ in __getitem__ iterator
Peter Otten
__peter__ at web.de
Fri Dec 15 06:46:46 EST 2006
Giovanni Bajo wrote:
> 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?
It's there, just not doctored into the dir() output:
>>> class A(object):
... def __getitem__(self, index): return index
... def __len__(self): return 42
...
>>> iter(A()).__length_hint__
<built-in method __length_hint__ of iterator object at 0x401d558c>
>>> iter(A()).__length_hint__()
42
Peter
More information about the Python-list
mailing list