【问题标题】:exec a global variable from an extern module从外部模块执行全局变量
【发布时间】:2015-10-31 11:38:14
【问题描述】:

我有一个外部模块,我想将“exec”表达式设置为全局(因为我需要将字符串作为变量名传递)

所以,我有一个类似的功能

def fct_in_extern_module():
    exec 'A = 42' in globals()
    return None

在我的主脚本中,我有

import extern_module
extern_module.fct_in_extern_module()

那么,我为什么会有

NameError: name 'A' is not defined

如果我这样做(在主脚本中)

def fct_in_main():
    exec 'B = 42' in globals()

fct_in_main()

>>> B
42

知道如何在外部模块中将字符串“A”设置为变量名吗?

谢谢!

【问题讨论】:

  • 你试过extern_module.A 吗?不确定,但这可能是问题所在。

标签: python string exec global python-module


【解决方案1】:

globals() 总是返回调用它的模块的__dict__。这确实是唯一合理的选择……考虑一下:

# qux.py
import foo
foo.bar()

# foo.py
import baz
def bar():
    return baz.exec_stuff()

# baz.py
def exec_stuff():
    exec 'A = 1' in globals()

应该在qux.pyfoo.pybaz.py 中设置全局吗?这样看来,baz显而易见的选择,也是 python 使用的选择。

现在这给我们带来了你为什么首先使用 exec 的问题?一般来说,返回你需要的值给调用者是一个更好的主意。然后他们可以用它做他们想做的事:

def fn_in_extern_module():
    return 42

然后:

import extern
A = extern.fn_in_extern_module()

【讨论】:

    【解决方案2】:

    globals() 表示“this 模块的全局字典”。因此,您选择编码extern_module.py 的方式将不会影响任何其他模块的全局字典。

    一种解决方法:将其定义为:

    def fct_in_extern_module(where):
        exec 'A = 42' in where
    

    并将其称为:

    extern_module.fct_in_extern_module(globals())
    

    当然,像往常一样,exec 并不是解决问题的最佳方式。更好:

    def fct_in_extern_module(where):
        where['A'] = 42
    

    更快更干净。

    【讨论】:

      猜你喜欢
      • 2016-02-10
      • 2013-07-19
      • 2016-05-19
      • 2015-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      相关资源
      最近更新 更多