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

标签 python global-variables metaprogramming python-3.4

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/

相关文章:

python - 加密不可用错误: No crypto library available (using oauth2client in google app engine)

javascript - 是否可以在 javascript 中创建一个在刷新页面时不会改变的变量?

c++ - 递归构造 unsigned int 的可变参数模板

Python 动态创建自定义命名函数

python - 切片命名元组

python - UDP 套接字 sendto() 函数

javascript - 如何创建javascript全局可访问的静态变量?

svn - 在svn-external中获取变量

python - 将函数 "inside"设为模块

Python Koan 131 引发异常