Global Variables between different modules

我是研究僧i 提交于 2019-12-01 09:40:45

There is no such thing as a truly global variable in python. Objects are bound to variables in namespaces and the global keyword refers to the current module namespace. from somemodule import * creates new variables in the current module's namespace and refers them to somemodule's objects. You now have two different variables pointing to the same object. If you rebind one of the variables, the other ones continue to reference the original object. Further, a function.s "global" namespace is the module it is defined in, even if it is imported to a different module.

If you want a "global" variable, import the module and use its namespace qualified name instead of rebinding individual variables in the local namespace.

Here's an annotated example...

cfg.py

var = 10
somelist = []
var2 = 1

def show_var2():
    print var2

main.py

import cfg
from cfg import *   # bind objects referenced by variables in cfg to
                    # like-named variables in this module. These objects
                    # from 'cfg' now have an additional reference here

if __name__ == '__main__':
    print cfg.var, var
    var = 20        # rebind this module's 'var' to some other value.
                    # this does not affect cfg's 'var'
    print cfg.var, var

    print '----'
    print cfg.somelist, somelist
    somelist.append(1)    # update this module's 'somelist'
                          # since we updated the existing object, all see it
    print cfg.somelist, somelist

    print '----'
    var2 = 2
    print var2, cfg.var2, show_var2() # show_var2 is in cfg.py and uses its
                                      # namespace even if its been imported
                                      # elsewhere
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!