[Python-ideas] Fwd: Fwd: Fwd: unpacking generalisations for list comprehension

David Mertz mertz at gnosis.cx
Mon Oct 17 14:32:24 EDT 2016


On Sun, Oct 16, 2016 at 9:06 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:

> Remember that what we're arguing about is that existing instances of:
>
>   [x for subiterable in iterable for x in subiterable]
>
> [...] would be easier to read and maintain if they were instead written as:
>
>   [*subiter for subiter in iterable]
>
> That's the bar people have to reach - if we're going to add a 3rd
> spelling for something that already has two spellings
>


> The only proposal in this thread that has come close to reaching that
> bar is David Mertz's proposal to reify single level flattening as a
> flatten() builtin:
>
>     [x for x in flatten(iterable)]
>
> or, equivalently:
>
>     list(flatten(iterable))
>

I don't think I'd actually propose a builtin for this.  For me, including
the recipe that is in the itertools documentation into a function in the
module would be plenty.  Writing "from itertools import flatten" is not
hard.


> Then the only thing that folks need to learn is that Python's builtin
> "flatten()" is a *non-recursive* operation that consistently flattens
> one layer of iterables with no special casing (not even of strings or
> bytes-like objects).
>

Actually, I think that if we added `flatten()` to itertools, I'd like a
more complex implementation that had a signature like:

    def flatten(it, levels=1):
        # Not sure the best implementation for clever use of other itertools
        ...

I'm not quite sure how one would specify "flatten all the way down."  In
practice, `sys.maxsize` is surely large enough; but semantically it feels
weird to use an arbitrary large number to mean "infinitely if necessary."

-- 
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons.  Intellectual property is
to the 21st century what the slave trade was to the 16th.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20161017/9466390a/attachment.html>


More information about the Python-ideas mailing list