When a module is imported, it has its own global and locals name spaces, which it does not share with the main ones. Thus, if a variable is defined as global in a module, it can only be accessed as an element of the module. Let us assume we want to import a module named mymodule which provides an execute() function. This function executes command lines in the module global name space3.
>>> import mymodule
>>> mymodule.execute('a = 0')
>>> mymodule.a
0
|
>>> a # is not defined (or visible) in the main name space. Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'a' is not defined |
>>> from mymodule import execute
>>> # 'execute()' is now a member of the main name space
>>> execute('a = 0')
>>> a # is not defined...
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'a' is not defined
>>> execute('print a') # but seems defined 'somewhere'...
0
>>> print __name__ # Prints the current module name
__main__
>>> execute('print __name__') # Prints the module name the
... # 'execute()' function works in
mymodule
|
Finally you will have to import the brand new created variable if you want to make it visible in the main name space:
>>> from mymodule import a >>> a 0 |
>>> execute('b = [0, 0, 0]')
>>> from mymodule import b
>>> b
[0, 0, 0]
>>> b[0] = 1
>>> b # the one imported into 'main' from 'mymodule'
[1, 0, 0]
>>> execute('print b') # the one in 'mymodule'
[1, 0, 0]
|