[Python-ideas] Fwd: Fwd: Fwd: unpacking generalisations for list comprehension
Steven D'Aprano
steve at pearwood.info
Mon Oct 17 20:49:47 EDT 2016
On Mon, Oct 17, 2016 at 10:33:32PM +0200, Sven R. Kunze wrote:
> Sorry? You know, I am all for real-world code and I also delivered:
> https://mail.python.org/pipermail/python-ideas/2016-October/043030.html
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.
If I were doing this more than once, I'd be strongly inclined to invest
in a simple helper function to make this more readable:
def filter_and_flatten(language, fulltext):
for lang, text in fulltext:
if lang == language:
yield lang
yield text
filter_and_flatten('english', fulltext_tuples)
In some ways, list comprehensions are a trap: their convenience and ease
of use for the easy cases lure us into using them when we ought to be
using a generator. But that's just my opinion.
--
Steve
More information about the Python-ideas
mailing list