如何直接引用Python3中的exec编译函数?

2024-09-26 22:13:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我曾经创建过一个exec语句来生成一个在Python2中使用的函数。然而,当我转到Python3时,同样的方法停止了工作

Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def a():
...   exec(compile("def printt(): print(2)","printt","exec"))
...   printt()
... 
>>> a()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in a
NameError: name 'printt' is not defined
>>>

Python 2.7.15+ (default, Nov 27 2018, 23:36:35) 
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def a():
...   exec(compile("def printt(): print(2)","printt","exec"))
...   printt()
... 
>>> a()
2
>>> 

Tags: ordefaultforinformationlicenseondefmore
1条回答
网友
1楼 · 发布于 2024-09-26 22:13:49

在Python3中,exec函数不再能够直接修改本地范围

这在^{}中有记录,请参见注释,其中说明:

Note: The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.

还要注意,Python2代码使用的是^{} statement,尽管您编写它看起来像一个函数,但它是一种完全不同的形式。另请参见this answer以获得更深入的讨论,甚至this answer从Python代码反汇编的角度讨论了这个问题

因此,如果您想访问在exec()范围内定义的符号,应该向它传递一个dict(可能是空的,或者预先填充了要在exec()块中使用的任何变量赋值或函数定义),然后再访问它

Python 3中的代码works

def a():
   namespace = {}
   exec(compile("def printt(): print(2)","printt","exec"),
        globals(), namespace)
   printt = namespace['printt']
   printt()

希望这对于您的目的来说足够好

相关问题 更多 >

    热门问题