[issue6021] itertools.grouper

Raymond Hettinger report at bugs.python.org
Thu May 14 21:09:49 CEST 2009


Raymond Hettinger <rhettinger at users.sourceforge.net> added the comment:

> All implementations relying on zip or zip_longest breaks 
> with infinite iterable (e.g. itertools.count()).

How is it broken?  
Infinite in, infinite out.

>>> def grouper(n, iterable, fillvalue=None):
...    args = [iter(iterable)] * n
...    return zip_longest(*args, fillvalue=fillvalue)

>>> g = grouper(3, count())
>>> next(g)
(0, 1, 2)
>>> next(g)
(3, 4, 5)
>>> next(g)
(6, 7, 8)
>>> next(g)

> And it is not impossible to define a clean, flexible, 
> and familiar API which will be similar to open()'s mode
> or unicode error mode. The modes would be 'error' 
> (default), 'pad', 'truncate', and 'partial'

Of course, it's possible.  I find that to be bad design.  Generally, we
follow Guido's advice and create separate functions rather than overload
a single function with flags -- that is why we have filterfalse()
instead of a flag on filter().  When people suggest an API with multiple
flags, it can be a symptom of hyper-generalization where api complexity
gets substituted for writing a simple function that does what you want
in the first place.  IMO, it is easier to learn the zip(g, g, g) idiom
and customize it to your own needs than to learn a new tool with four
flag options that control its output signature.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue6021>
_______________________________________


More information about the Python-bugs-list mailing list