Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

python - Why are closures broken within exec?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you pass a string to exec or eval, it compiles that string to a code object before considering globals or locals. So when you say:

eval('lambda: a', ...)

it means:

eval(compile('lambda: a', '<stdin>', 'eval'), ...)

There's no way for compile to know that a is a freevar, so it compiles it to a global reference:

>>> c= compile('lambda: a', '<stdin>', 'eval')
>>> c.co_consts[0]
<code object <lambda> at 0x7f36577330a8, file "<stdin>", line 1>
>>> dis.dis(c.co_consts[0])
  1           0 LOAD_GLOBAL              0 (a)
              3 RETURN_VALUE        

Therefore to make it work you have to put a in the globals and not the locals.

Yeah, it's a bit dodgy. But then that's exec and eval for you I suppose... they're not supposed to be nice.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...