blhsing
(Ben Hsing)
November 20, 2025, 5:44am
22
Jean-Pierre Messager:
You’re right. This is the way it is. For implementation reasons (no “sub-cells” in comprehensions). BUT (again IMHO), it it not “crucial”, it is a (unexpected) side effect of implementation. not a feature. It is (IMHO) bad, error prone and may be fixable by a quite fix patch on cells handling in comprehensions.
That would break a lot of existing codes that rely on the current behavior.
And there’s already a widely accepted workaround of storing the iterating value as a default value to a parameter of the lambda function:
>>> l = [ (lambda i=i: i) for i in (1, 2, 3) ]
>>> [ f() for f in l ]
[1, 2, 3]
3 Likes
YBM
(Jean-Pierre Messager)
November 20, 2025, 6:04am
23
Let me think about this, not conviced yet, but thanks!
“widely accepted” ? Any reference ? Just asking.
YBM
(Jean-Pierre Messager)
November 20, 2025, 6:09am
24
I buy your fix Ben !
But I still think that the original (without i=i) should behave the same.
YBM
(Jean-Pierre Messager)
November 20, 2025, 6:14am
25
It makes perfect sense (event if weird) thanks Ben. To be added in the doc ?
“Comprehension leakages: how to avoid them”.
Going back to LISP
YBM
(Jean-Pierre Messager)
November 20, 2025, 6:29am
26
To put this into perspective: I’m teaching Python. I insist on the fact that there are no scopes in Python, but namespaces and LEGB. It appears as it is equivalent to lexical scoping, but it is NOT.
I ended up with bugs when coding while it was as if Python had lexical scope.
I ended up with bugs.
I missed block-level scope (there is no spoon, right ?)
My 2ç
YBM
(Jean-Pierre Messager)
November 20, 2025, 6:53am
27
Python is NOT a lexical language. Face it or leave it. Ok
YBM
(Jean-Pierre Messager)
November 20, 2025, 7:22am
28
No cigar: my lambdas are not awaiting arguments, your are;
blhsing
(Ben Hsing)
November 20, 2025, 8:10am
29
You can search for “python lambda list comprehension same value” to find tons of Q&As on this topic, all of which point to this very solution.
Here’s one of the them:
python, lambda, closures
Jean-Pierre Messager:
To be added in the doc ?
It already is:
Contents: Programming FAQ- General Questions- Is there a source code level debugger with breakpoints, single-stepping, etc.?, Are there tools to help find bugs or perform static analysis?, How can ...
3 Likes
blhsing
(Ben Hsing)
November 20, 2025, 9:29am
30
Lexical scoping just means that a variable’s scope is statically bound by where it is defined. It does not mean that a snapshot of a variable’s value has to be taken when the variable is defined. So Python does use lexical scoping, with values resolved by the LEGB rule.
2 Likes