繁体   English   中英

如何通过键入从另一个模块导入的函数来修改python3 globals()?

[英]How to modify python3 globals() by key in function imported from another module?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM