这是一个相当有趣的情况:
>>> def func(): ... exec('print "hi from func"') ... def subfunction(): ... return True ... File "", line 2 SyntaxError: unqualified exec is not allowed in function 'func' because it contains a nested function with free variables
之所以这样做确实不起作用,是因为subfunction包含一个自由variables,而且由于在Python 2中, exec理论上可以修改包含范围中的局部variables,所以不可能决定variables是应该从全局variables还是从全局variables父函数范围。 Python的禅宗之一的诗句是“面对模棱两可,拒绝猜测的诱惑”。 这就是Python 2所做的。
现在的问题是:这个未绑定的variables是什么? 那么,这是True !
事实上它可以与None再现:
>>> def func(): ... exec('print "hi from func"') ... def subfunction(): ... return None ... File "", line 2 SyntaxError: unqualified exec is not allowed in function 'test2' because it contains a nested function with free variables
尽pipeNone不能被分配,并且在字节码中被认为是一个常量 ,但是这个buggyparsing器认为这是一个未绑定的variables。
但是,如果你用1代替它,它没有问题的工作:
>>> def test2(): ... exec('print "hi from func"') ... def subfunction(): ... return 1 ... >>>
为了避免这个错误,请明确指定要被exec使用的全局variables和可能的局部variables,例如:
>>> def test2(): ... exec 'print "hi from test2"' in {} ... def subfunction(): ... return None ... >>>
在Python 3中, exec只是一个简单的函数,并不是由parsing器或字节码编译器专门处理的。 在Python 3中exec不能重新绑定函数本地名,因此这个SyntaxError和模糊不存在。
Python 2 vs 3兼容性的一个奇怪的例子是Python 2.7的文档说明了这一点
表单exec(expr, globals)相当于exec expr in globals exec(expr, globals, locals)forms相当于exec expr in globals, locals 。 exec的元组forms提供了与Python 3的兼容性,其中exec是一个函数而不是语句。
元组表单并不总是100%兼容,因为在嵌套函数的函数中处理exec有一个错误(issue 21591) ; 直到Python 2.7.8以下代码可能会引发exception:
def func(): exec('print "hi from test2"', {}) def subfunction(): return None
这已经在Python 2.7.9中解决了,不再抛出。