[Python-ideas] Generators' and iterators' __add__ method
tjreedy at udel.edu
Wed Feb 15 23:39:31 CET 2012
On 2/15/2012 11:20 AM, Yuval Greenfield wrote:
> Wouldn't it be nice to add generators and iterators like we can do with
That is simply not possible. list1+list2 is a list; tuple1+tuple2 is a
tuple; list1+tuple2 is an error! What type would iterable1 + iterable 2
be? Answer: a chain object!
> def f():
> yield 1
> yield 2
> yield 3
> def g():
> yield 4
> yield 5
> # today
> for item in itertools.chain(f(), g()):
The itertools module is the proper place for generic operations on
iterables (and not just iterators!).
>>> import itertools as it
>>> list(it.chain([1,2,3], (4,5.6), range(7,10)))
[1, 2, 3, 4, 5.6, 7, 8, 9]
Chain 'adds' mixed types and is not limited to binary scope.
If we were starting fresh today, we *might* consider making the
functions that went into itertools into methods of an iterable ABC. But
making every function a method is not Python's style. Indeed, exposing
generic methods like __len__ as functions is more common.
Terry Jan Reedy
More information about the Python-ideas