如何在运行时更新Python中的全局包变量

时间:2017-06-15 08:42:23

标签: python

我正在努力定义一个全局包变量,供包中的所有模块使用。 我有这段代码:

# my_module.py
from .__main__ import GLOBAL_VAR

def print_global():
    print(GLOBAL_VAR)


# __main__.py
from my_package import my_module
GLOBAL_VAR = ''

def main():
    global GLOBAL_VAR
    GLOBAL_VAR = 'myvalue'
    my_module.print_global()

if __name__ == '__main__':
    main()

我希望my_module.print_global()打印myvalue,而是打印一个空字符串(初始值)。 我也尝试在GLOBAL_VAR main()声明之后导入模块,但它没有帮助。

您能否告诉我如何从GOBAL_VAR重新定义main()并使其可用于包中的所有子模块?我也接受任何其他选项,而不是使用global关键字。

编辑:建议的类似问题仅部分回答了这一问题。重新定义全局变量没有任何意义。

1 个答案:

答案 0 :(得分:0)

I'm not sure this is the right way to do it, but this is how I made it work:

  1. Moved GLOBAL_VAR to a separate file settings.py to eliminate circular import, as advised by @Nearoo.

  2. In main() redefined settings.GLOBAL_VAR the way I want.

  3. And only then imported my_module.

Again, the problem here was that I didn't know the variable value initially and needed to define it at run time to be used by all modules.

That's how the code looks now:

# settings.py
GLOBAL_VAR = ''


# my_module.py
from .settings import GLOBAL_VAR

def print_global():
    print(GLOBAL_VAR)


# __main__.py
from my_package import settings

def main():
    settings.GLOBAL_VAR = 'myvalue'

    from my_package import my_module
    my_module.print_global()

if __name__ == '__main__':
    main()