[Python-ideas] Introduce collections.Reiterable
Stephen J. Turnbull
stephen at xemacs.org
Sat Sep 21 09:02:35 CEST 2013
Neil Girdhar writes:
> I can humbly suggest why Python would deprecate the sequence
> protocol: there "should be one obvious way" to answer iter(), and
> in my opinion that's the __iter__() method. I considered
> infinite iterators, and if you happen to have __getitem__ written,
> you can trivially write an __iter__ function
Better yet, Python can do it for me. That's *why* it makes sense for
iter() to accept an object with a __getitem__ method.
I wonder if it would be possible for Iterable to provide an __iter__
method at instantiation if and only if __iter__ is not defined in the
derived class and __getitem__ is. Then
>>> class GoodIterable1(Iterable):
... def __iter__(self):
... return iter([])
...
>>> gi1 = GoodIterable1(Iterable)
>>> dir(gi1)
[..., __iter__, ...]
>>> class GoodIterable2(Iterable)
... def __getitem__(self, i):
... return [][0]
...
>>> dir(gi2)
[..., __getitem__, __iter__, ...] # it's magic!
>>> class BadIterable(Iterable):
... pass
...
>>> bi = BadIterable() # ordinary mixin __iter__ wouldn't raise
# but magic one does
TypeError: can't instantiate abstract class BadIterable with abstract methods __iter__
>>>
Although I guess the ordinary mixin will raise anyway when it tries to
call __getitem__.
More information about the Python-ideas
mailing list