[Python-ideas] __iter__ implies __contains__?

Arnaud Delobelle arnodel at gmail.com
Tue Oct 4 00:20:51 CEST 2011


On 3 October 2011 23:00, Nick Coghlan <ncoghlan at gmail.com> wrote:

>> Maybe we should be thinking about a "reiterator algebra"
>> to sit on top of the iterator algebra.
>>
>> For example, given two reiterables x and y, zip(x, y)
>> would return a reiterable that, when iterated over, would
>> extract iterators from x and y and return a corresponding
>> iterator.
>
> Can't be done in general, since one of the main points of iterator
> algebra is that it works with *infinite* iterators.

But an iterable doesn't have to be finite to be reiterable:

>>> class A:
...     def __iter__(self):
...         return itertools.count()
...
>>> a = A()
>>> list(zip(a, range(10)))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]
>>> list(zip(a, range(10)))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]

This makes me think that you could have a process of "lifting" an
iterator-making function like zip back to iterable-making:

>>> class deiter:
...    def __init__(self, f, *args, **kwargs):
...       self.f = f
...       self.args = args
...       self.kwargs = kwargs
...    def __iter__(self):
...       return iter(self.f(*self.args, **self.kwargs))

>>> z = deiter(zip, a, range(10))
>>> list(z)
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]
>>> list(z)
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]

-- 
Arnaud



More information about the Python-ideas mailing list