Tuesday, September 21, 2021

Brett Cannon: Unravelling comprehensions

After failing to unravel generator expressions, in this post as part as my Python syntactic sugar post series I want to tackle comprehensions. Thanks to a change made in Python 3.0, recreating comprehensions using generator expressions is straightforward since comprehensions do not leak their loop variant.

List comprehensions

Unravelling [c for b in a] is list(c for b in a): take the body of the list comprehension and pass it to list() as a generator expression.

Set comprehensions

Unravelling {c for b in a} is set(c for b in a). I suspect you&aposre starting to see a pattern...

Dict comprehensions

There&aposs a slight trick to dict comprehensions in that the generator expression needs to return key/value pairs, otherwise it&aposs the same "pass a generator to the type&aposs constructor" trick. That means {c: d for b in a} becomes dict((c, d) for b in a).

Aside: why isn&apost there a tuple comprehension?

There are two reasons why there is no such thing as a "tuple comprehension".

One is how would you represent that syntactically? The obvious syntax of parentheses around a comprehension-like syntax, but that&aposs taken by generator expressions.

The second reason is a "tuple comprehension" is a misuse of tuples. The data structure is meant to provide an index-based struct instead of an immutable sequence. Consider a pair of key and value like we did for  dict comprehensions: (key, value). What&aposs represented by index 0 means something different than what is in index 1.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...