13.4. Functions and namespaces

There are three different namespaces in Python: a local namespace, a module namespace (see Chapter 14) and a global namespace. A local environment is created at function calls. It includes all the parameters and local variables of the function. Function definitions can be nested, and nested functions have their own local namespace.

Example 13.2. Function execution namespaces

>>> enz = []

>>> def add_enz(*new):
...     def verif():
...             print "enz: ", enz
...             print "new: ", new
...     verif()
...     enz.extend(list(new))

>>> add_enz('EcoRI')
enz:  []
new:  ('EcoRI',)

>>> enz
[ 'EcoRI' ]
	  

By default, variables are defined in the local namespace. In order to access a global variable, there is nothing to do (see Example 13.2 above). In order to define a global variable within a function (i.e to assign a value to it), it has to be declared explicitly as global variable, using the global statement.

Example 13.3. Global statement

>>> def change_global():
...     global a
...     a = 10
... 
>>> a = 20
>>> change_global()
>>> a
10
	

Example 13.4. Global statement (2)

In this example, the global variable is both accessed and changed.
>>> def add_enz(*new):
...     global enz
...     enz = enz + list(new)
... 
>>> add_enz('BamHI', 'HindIII')
>>> enz
[ 'EcoRI', 'BamHI', 'HindIII']