[Python-Dev] Tricky way of of creating a generator via a comprehension expression (original) (raw)
Nick Coghlan ncoghlan at gmail.com
Thu Nov 23 01:00:58 EST 2017
- Previous message (by thread): [Python-Dev] Tricky way of of creating a generator via a comprehension expression
- Next message (by thread): [Python-Dev] Tricky way of of creating a generator via a comprehension expression
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On 23 November 2017 at 15:33, Stephen J. Turnbull < turnbull.stephen.fw at u.tsukuba.ac.jp> wrote:
However, my model of comprehensions is exactly a for loop that appends to an empty list repeatedly, but doesn't leak iteration variables.
Not since Python 3.0. Instead, they create a nested function, the same way generator expressions do (which is why the name resolution semantics are now identical between the two cases).
The differences in structure between the four cases (genexp, list/set/dict comprehensions) then relate mainly to what the innermost loop does:
result.append(expr) # list comp
result.add(expr) # set comp
result[k] = v # dict comp
yield expr # genexp
Thus, when the expression itself is a yield expression, you get:
result.append(yield expr) # list comp
result.add(yield expr) # set comp
result[k] = (yield v) # dict comp
yield (yield expr) # genexp
Cheers, Nick.
-- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20171123/df975b75/attachment.html>
- Previous message (by thread): [Python-Dev] Tricky way of of creating a generator via a comprehension expression
- Next message (by thread): [Python-Dev] Tricky way of of creating a generator via a comprehension expression
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]