在函数内运行exec

4 python function exec

如何在函数内部使用python exec关键字?

Ale*_*lli 14

它会破坏你的功能性能以及它的可维护性,但如果你真的想让你自己的代码变得更糟,那么Python会给你"足够的绳索来射击你自己"(;-):

>>> def horror():
...   exec "x=23"
...   return x
... 
>>> print horror()
23
Run Code Online (Sandbox Code Playgroud)

当然,一个不那么可怕的事情将是exec在一个特定的字典中:

>>> def better():
...   d = {}
...   exec "x=23" in d
...   return d['x']
... 
>>> print better()
23
Run Code Online (Sandbox Code Playgroud)

这至少避免了第一种方法的命名空间污染.

  • 有时我需要在进行一些符号计算时动态创建变量。您还建议如何在不使用 exec 的情况下执行此操作? (3认同)

H. *_*ena 8

Alex 的答案在 Python 3 中的工作方式略有不同。

由于 exec() 是 Python 3 中的函数,因此请使用以下模式 -

def better():
    d = {}
    exec("x=23", d)
    return d['x']

print better()
23
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅此问题 - Behaviour of exec function in Python 2 and Python 3

  • 使用 exec('x=23', globals())` 但请注意,这会将 exec 内生成的所有变量添加到全局范围中。它还会覆盖任何同名的变量。 (4认同)