file1.py
:
def test_globals():
globals()['t']=5
在 python3 repl 中:
>>> from file1 import *
>>> test_globals()
>>> t
Traceback ....
NameError: name 't' is not defined
>>> def test_globals2(): #local context
globals()['t'] = 5
>>> test_globals2()
>>> t
5
如何修复 test_globals 函数以实际修改 globals()
?
最佳答案
您所做的问题是 from file1 import *
没有导入 t
因为它不存在。如果重复 import
行,它将起作用:
>>> from file1 import *
>>> test_globals()
>>> t
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 't' is not defined
>>> from file1 import *
>>> t
5
另一件事会起作用:
>>> import file1 as f1
>>> f1.t
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 't'
>>> f1.test_globals()
>>> f1.t
5
但是,如果您只是在重新加载模块后(如您在评论中所写),请考虑使用 importlib.reload
.
关于python - 如何在从另一个模块导入的函数中通过键修改python3 globals()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26835853/