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

Sven R. Kunze srkunze at mail.de
Sat Oct 15 17:38:08 EDT 2016


On 15.10.2016 16:47, Martti Kühne wrote:
> [var for expression in iterable for var in expression]
> you are right, though. List comprehensions are already stackable.
> TIL.

Good catch, Paul. Comprehensions appear to be a special case when it 
comes to unpacking as they provide an alternative path. So, nested 
comprehensions seem to unintuitive to those who actually favor the 
*-variant. ;) Anyway, I don't think that it's a strong argument against 
the proposal. ~10 other ways are available to do what * does and this 
kind of argument did not prevent PEP448.


What's more (and which I think is a more important response to the 
nested comprehension alternative) is that nested comprehensions are 
rarely used, and usually get long quite easily. To be practical here, 
let's look at an example I remembered this morning (taken from 
real-world code I needed to work with lately):

return [(language, text) for language, text in fulltext_tuples]

That's the minimum comprehension. So, you need to make it longer already 
to do **actual** work like filtering or mapping (otherwise, just return 
fulltext_tuples). So, we go even longer (and/or less readable):

return [t for t in tuple for tuple in fulltext_tuples if tuple[0] == 
'english']
return chain.from_iterable((language, text) for language, text in 
fulltext_tuples if language == 'english'])

I still think the * variant would have its benefits here:

return [*(language, text) for language, text in fulltext_tuples if 
language == 'english']

(Why it should be unpacked, you wonder? It's because of executemany of 
psycopg2.]

Cheers,
Sven


More information about the Python-ideas mailing list