寻找此代码为什么会提高的良好解释SyntaxError
。exec的行为的任何解释?
def echo(x):
return x
def foo(s):
d = {}
exec(s, {}, d)
return dict((x,y) for x,y in d.items())
def bar(s):
d = {}
exec(s, {}, d)
return dict((x, echo(y)) for x,y in d.items()) # comment this to compile
s = 'a=1'
foo(s)
File "test.py", line 11
exec(s, {}, d)
SyntaxError: unqualified exec is not allowed in function 'bar' it contains a
nested function with free variables
这究竟应该怎么办? – 2012-02-08 14:35:34
@DanielRoseman:实际的问题似乎是:为什么'foo()'是有效的Python而bar()不是?在我看来,这是一个非常有效的问题,尽管应该说清楚一点。 – 2012-02-08 14:40:49
@DanielRoseman:D此代码仅供解释。真正的代码是更可接受的版本。我只是在寻找高管的解释。 – Shekhar 2012-02-08 14:42:14