【问题标题】:Why use exec to create function dynamically inside a class method doesn't work? [duplicate]为什么使用 exec 在类方法中动态创建函数不起作用? [复制]
【发布时间】:2021-05-19 09:43:28
【问题描述】:

我了解到exec 可以从这篇帖子Python: dynamically create function at runtime 动态创建函数。

我想在实例方法中动态创建一个函数,然后使用该函数。

但是下面的代码失败了,为什么?

class A:
    def method_a(self, input_function_str: str):
        exec('''def hello():
            print('123')
        ''')
        
        # hello() # call hello() here leads to NameError


b = A() 
b.method_a()
# hello() # call hello() here also leads to NameError

我的目标是根据从外部传递的input_function_str 动态创建一个函数,然后在method_a 的某个位置使用该函数。

【问题讨论】:

  • exec() 可以从当前作用域中获取东西,但不能将东西添加到作用域中,因此hello 函数之后会丢失。无论如何,我不建议这样做,似乎很不安全。这有什么用例?
  • 请注意,如果没有沙盒和其他预防措施,这会打开一个巨大的安全漏洞,因为输入字符串可能包含恶意代码。 另请参阅:stackoverflow.com/questions/1832940/…

标签: python python-3.x


【解决方案1】:

使用exec 在其他函数中动态定义的函数不会保存到该函数locals()。如果您将其保存到 globals() 范围内,您的代码将可以工作,但您也可以在函数范围之外调用 hello()

def method_a(input_function_str: str = None):
    exec('''def hello():  print('123') ''', globals())
    print('inside scope:')
    hello()

method_a()
print('outside scope:')
hello()

有关更多信息,请参阅此答案:Using a function defined in an exec'ed string in Python 3

【讨论】:

    猜你喜欢
    • 2014-01-11
    • 2021-02-11
    • 1970-01-01
    • 2013-07-11
    • 2020-07-13
    • 1970-01-01
    • 2012-09-12
    • 2018-04-06
    • 2019-01-28
    相关资源
    最近更新 更多