next up previous contents index
Next: NumPy basics Up: Python basics Previous: The __doc__ attribute   Contents   Index

Global/local variables and module name spaces

Python has the usual notion of global and local variables. A variable may be either visible in all the main code (it is global) or only in the function which defines it (it is local). When a variable is called in a function, Python searches it in the local name space and if not found, it searches it in the global name space.

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
Note that importing all module objects in the main name space does not give a solution:
>>> 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
execute() function still works in mymodule (and defines variables as members of it) although there is no 'mymodule' module visible in the main name space.

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
Note that the two objects a (imported from mymodule) and mymodule.a are the same object (not a copy):
>>> 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]


next up previous contents index
Next: NumPy basics Up: Python basics Previous: The __doc__ attribute   Contents   Index
Gildas manager 2014-07-01