[英]How to change global variables using globals() in python method?
If I have the following Python script foo.py :如果我有以下 Python 脚本 foo.py :
def foo() :
my_dict = {'A': 1, 'B': 2, 'C': 3}
globals().update(my_dict)
print(A)
print(B)
print(C)
foo()
I can type this in ipython :我可以在 ipython 中输入:
run foo.py
=> 1
=> 2
=> 3
A
=> 1
However, If I remove the foo() at the bottom :但是,如果我删除底部的 foo() :
def foo() :
my_dict = {'A': 1, 'B': 2, 'C': 3}
globals().update(my_dict)
print(A)
print(B)
print(C)
# no foo
And I type this in ipython :我在 ipython 中输入:
run foo.py
foo()
=> 1
=> 2
=> 3
A
=> NameError: name 'A' is not defined
I get this error.我收到这个错误。 Why is this the case?
为什么会这样?
IPython's %run
defaults to running the file in a new namespace and then copying the results into your namespace. IPython 的
%run
默认在新的命名空间中运行文件,然后将结果复制到你的命名空间中。
When foo.py
contains a foo()
call, that creates A
, B
, and C
variables in the new namespace that IPython then copies to your namespace.当
foo.py
包含foo()
调用时,它会在新命名空间中创建A
、 B
和C
变量,然后 IPython 将其复制到您的命名空间。
When foo.py
doesn't contain a foo()
call, you can call foo()
yourself, but foo
is still using its original namespace for globals.当
foo.py
不包含foo()
调用时,您可以自己调用foo()
,但foo
仍然使用其原始命名空间作为全局变量。 Calling foo()
creates A
, B
, and C
variables in foo
's original namespace, too late for IPython to pick them up and copy them into your namespace.调用
foo()
在foo
的原始名称空间中创建A
、 B
和C
变量,IPython 来不及将它们提取并复制到您的名称空间中。
You can use %run
with the -i
flag to run the file in your namespace directly, avoiding these issues.您可以使用带有
-i
标志的%run
直接在您的命名空间中运行文件,从而避免这些问题。
You need to declare element_dict
a global variable before assigning it.在分配之前,您需要将
element_dict
声明为全局变量。 Once you have an assign statement anywhere within a function, the variable being assigned is declared on a local scope only, unless otherwise specified.一旦你在函数内的任何地方有赋值语句,被赋值的变量就只在局部范围内声明,除非另有说明。 In your case,
element_dict
is declared locally due to element_dict = read_mass_from_file()
.在您的情况下,
element_dict
由于element_dict = read_mass_from_file()
在本地声明。
See the documentation for more details. 有关更多详细信息,请参阅文档。
To actually reference the global variable:要实际引用全局变量:
def mass_mode() :
'''
Add element names and masses to the global variables.
'''
global element_dict
element_dict = read_mass_from_file()
will update the element_dict
from the global scope.将从全局范围更新
element_dict
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.