Glyph on Nostr: This is possibly my least (most?) favorite #PythonOddity : ``` def loop(): for number ...
This is possibly my least (most?) favorite #PythonOddity :
```
def loop():
for number in range(10):
def closure():
return number
yield closure
eagerly = [each() for each in loop()]
lazily = [each() for each in list(loop())]
```
Understanding why `eagerly` and `lazily` differ is *crucial* to understanding how scopes work in Python, and illustrates a weakness in the otherwise pretty great “you don’t have to declare variables” structure of the language.
Published at
2024-06-16 20:05:10Event JSON
{
"id": "d89817fc6636cc535c301742fd0ffc41406a51acab5955d398cd2107b1c18f2d",
"pubkey": "bd385aa0b579765c6883c5b0eb17e8ae350c988c659510be1e8453557ee38784",
"created_at": 1718568310,
"kind": 1,
"tags": [
[
"t",
"pythonoddity"
],
[
"proxy",
"https://mastodon.social/users/glyph/statuses/112628092787725236",
"activitypub"
]
],
"content": "This is possibly my least (most?) favorite #PythonOddity :\n\n```\ndef loop():\n for number in range(10):\n def closure():\n return number\n yield closure\n\neagerly = [each() for each in loop()]\nlazily = [each() for each in list(loop())]\n```\n\nUnderstanding why `eagerly` and `lazily` differ is *crucial* to understanding how scopes work in Python, and illustrates a weakness in the otherwise pretty great “you don’t have to declare variables” structure of the language.",
"sig": "bdaec533ee75eb0d566a2089be140632b28d030597247534d5091019c5dbac45b1650ba51d6ee6bbbff8a273b7b8da6d33b7043e25b57cd6237f05796cfa8c56"
}