Understanding global variable in Python
Question: I came across a strange issue in Python when using global variables.

I have two modules(files):`mod1.py` and `mod2.py`

`mod1` tries to modify the global variable `var` defined in `mod2`. But the
`var` in mod2 and `var` in `mod` seems to be two different things. Thus, the
result shows that such modification does not work.

Here is the code:

    
    
    #code for mod2.py
    global var  
    var = 1 
    def fun_of_mod2():
        print var
    
    #code for mod1.py
    from mod2 import var,fun_of_mod2    
    global var #commenting out this line yields the same result
    var = 2 #I want to modify the value of var defined in mod2
    fun_of_mod2() #but it prints: 1 instead of 2. Modification failed :-(
    

Any hint on why this happens? And how can I modify the value of `val` defined
in `mod2` in `mod1`?

Thanks


Answer: When you import `var` into `mod1`:

    
    
    from mod2 import var,fun_of_mod2
    

You are giving it the name `var` _in mod1's namespace._ It is as if you did
this:

    
    
    import mod2
    var = mod2.var
    fun_of_mod2 = mod2.fun_of_mod2
    del mod2
    

In other words, there are now two names for the value, `mod1.var` and
`mod2.var`. They are the same at first, but when you reassign `mod1.var`,
`mod2.var` still points to the same thing.

What you want to do is just:

    
    
    import mod2
    

Then access and assign the variable as `mod2.var`.

It's important to note that global variables in Python are not truly global.
They are global only to the module they're declared in. To access global
variables inside another module, you use the `module.variable` syntax. The
`global` statement can be used inside a function to allow a module-global name
to be assigned to (without it, assigning to a variable makes it a local
variable in that function). It has no other effect.

