尋找此代碼爲什麼會提高的良好解釋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