exec为什么不能在具有子功能的功能中工作? [英] Why doesn't exec work in a function with a subfunction?
问题描述
您似乎无法在具有子功能的函数中使用exec ...
It looks like you can't use exec in a function that has a subfunction...
任何人都知道为什么此Python代码不起作用吗?我在test2中的exec处遇到错误.另外,我知道exec的风格不好,但是请相信我,出于适当的原因,我正在使用exec.否则我不会使用它.
Anyone know why this Python code doesn't work? I get an error at the exec in test2. Also, I know exec's aren't good style, but trust me, I'm using exec for an appropriate reason. I wouldn't use it otherwise.
#!/usr/bin/env python
#
def test1():
exec('print "hi from test1"')
test1()
def test2():
"""Test with a subfunction."""
exec('print "hi from test2"')
def subfunction():
return True
test2()
我将错误缩小为在子功能中具有功能.它与raise关键字无关.
I narrowed down the bug to having a function in a subfunction. It has nothing to do with the raise keyword.
推荐答案
正确.除非指定上下文,否则不能在具有子功能的函数中使用exec.从文档中:
Correct. You can't use exec in a function that has a subfunction, unless you specify a context. From the docs:
如果在函数中使用了exec并且 函数包含一个嵌套块 免费变量,编译器将 引发SyntaxError除非执行 明确指定本地 exec的名称空间. (其他 的话,"exec obj"将是非法的, 但"ns中的exec obj"是合法的.)
If exec is used in a function and the function contains a nested block with free variables, the compiler will raise a SyntaxError unless the exec explicitly specifies the local namespace for the exec. (In other words, "exec obj" would be illegal, but "exec obj in ns" would be legal.)
有一个很好的理由,如果不是星期天晚上,我可能会明白. 现在,下一个问题:为什么要使用exec?很少需要它.你说你有充分的理由.我对此表示怀疑. ;)如果您有充分的理由,我会告诉您解决方法. :-P
There is good reason for this which I would probably understand if it wasn't Sunday night. Now, next question: Why are you using exec? It's very rarely needed. You say you have a good reason. I'm feeling sceptical about that. ;) If you have a good reason I'll tell you the workaround. :-P
哦,还是这样:
def test2():
"""Test with a subfunction."""
exec 'print "hi from test2"' in globals(), locals()
def subfunction():
return True
这篇关于exec为什么不能在具有子功能的功能中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!