Why are closures broken within exec?

Posted by Devin Jeanpierre on Stack Overflow See other posts from Stack Overflow or by Devin Jeanpierre
Published on 2010-05-01T10:59:11Z Indexed on 2010/05/01 12:07 UTC
Read the original article Hit count: 249

Filed under:
|
|

In Python 2.6,

>>> exec "print (lambda: a)()" in dict(a=2), {}
2
>>> exec "print (lambda: a)()" in globals(), {'a': 2}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
  File "<string>", line 1, in <lambda>
NameError: global name 'a' is not defined
>>> exec "print (lambda: a).__closure__" in globals(), {'a': 2}
None

I expected it to print 2 twice, and then print a tuple with a single cell. It is the same situation in 3.1. What's going on?

© Stack Overflow or respective owner

Related posts about python

Related posts about closures