[Python-ideas] Fwd: Fwd: Fwd: unpacking generalisations for list comprehension
Greg Ewing
greg.ewing at canterbury.ac.nz
Tue Oct 18 02:23:38 EDT 2016
Steven D'Aprano wrote:
> Your example shows the proposed:
>
> [*(language, text) for language, text in fulltext_tuples if language == 'english']
>
> which can be written as:
>
> [x for language, text in fulltext_tuples for x in (language, text) if language == 'english']
>
> which is only ten characters longer. To me, though, there's simply no
> nice way of writing this: the repetition of "language, text" reads
> poorly regardless of whether there is a star or no star.
I think the ugliness of this particular example has roots in
the fact that a tuple rather than an object with named fields
is being used, which is going to make *any* piece of code
that touches it a bit awkward.
If it were a namedtuple, for example, you could write
[*t for t in fulltext_tuples if t.language == 'english']
or
[x for t in fulltext_tuples if t.language == 'english' for x in t]
The latter is a bit unsatisfying, because we are having to
make up an arbitrary name 'x' to stand for an element of t.
Even though the two elements of t have quite different roles,
we can't use names that reflect those roles.
Because of that, to my eyes the version with * makes it easier
to see what is going on.
--
Greg
More information about the Python-ideas
mailing list