Explain the visibility of global variables in imported modules in Python?



Globals in Python are global to a module, not across all modules. (Unlike C, where a global is the same across all implementation files unless you explicitly make it static.). If you need truly global variables from imported modules, you can set those at an attribute of the module where you're importing it.

import module1
module1.a=3

On the other hand, if a is shared by a whole lot of modules, put it somewhere else, and have everyone import it:

global_module.py
module1.py:
import global_module
def fun():
    print global_module.var
Other files:
import global_module
import module1
global_module.var = 3
module1.fun()

Advertisements