简体   繁体   English

从其他模块获取 globals() dict

[英]Get globals() dict from other module

I have follow this method to create a settings file with globals.我已经按照这个方法创建了一个带有全局变量的设置文件。

settings.py I have: settings.py 我有:

def init()
    global test
    test = True

in main.py:在 main.py 中:

import settings
settings.init()
print(globals())

I cannot see "test" in globals?我在全局变量中看不到“测试”? Any idea please ?请问有什么想法吗?

In Python, global variables are only global in the module where they were defined.在 Python 中,全局变量仅在定义它们的模块中是全局的。

If you want to access the global variables of an imported module, you can use:如果要访问导入模块的全局变量,可以使用:

settings_globals = vars(settings)

Or if you only want the public ones (not starting with a leading underscore):或者,如果您只想要公共的(不以前导下划线开头):

settings_publics = {k: v for k,v in vars(settings).items if not k.startswith('_')}

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

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