Python for Developers

First edition

Chapter 9: Scope of names


The scope of names in Python are maintained by Namespaces, which are dictionaries that list the names of the objects (references) and the objects themselves.

Normally, the names are defined in two dictionaries, which can be accessed through the functions locals() and globals(). These dictionaries are updated dynamically at runtime.

Namespaces

Global variables can be overshadowed by local variables (because the local scope is consulted before the global scope). To avoid this, you must declare the variable as global in the local scope.

example:

In [1]:
def addlist(list):
    """
    Add lists of lists, recursively
    the result is global
    """
    global add
    
    for item in list:
        if type(item) is list: # If item type is list
            addlist(item)
        else:
            add += item

add = 0
addlist([[1, 2], [3, 4, 5], 6])

print add # 21
21

Using global variables is not considered a good development practice, as they make the system harder to understand, so it is better to avoid their use. The same applies to overshadowing variables.

In [1]:
 
Out[1]: