Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从外部模块执行全局变量_Python_String_Exec_Global_Python Module - Fatal编程技术网

Python 从外部模块执行全局变量

Python 从外部模块执行全局变量,python,string,exec,global,python-module,Python,String,Exec,Global,Python Module,我有一个extern模块,我想在其中将“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 d

我有一个extern模块,我想在其中将“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
而如果我这样做(在主脚本中)

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

谢谢

globals()。因此,您选择的编码方式不会影响任何其他模块的全局dict

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

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
更快、更干净。

globals()
始终返回调用它的模块的
\uu dict\uuu
。这真的是唯一合理的选择。。。考虑:

# 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.py
foo.py
baz.py
中设置全局变量?从这个角度来看,
baz
是最明显的选择,也是python使用的选择

现在我们要问的问题是,为什么首先要使用exec?通常,将所需的值返回给调用者是一个更好的主意。然后他们可以用它做他们想做的事:

def fn_in_extern_module():
    return 42
然后:

import extern
A = extern.fn_in_extern_module()

您是否尝试了外部模块A
?对此不确定,但这可能是个问题。
import extern
A = extern.fn_in_extern_module()