Python Programming/Scoping

Variables
Variables in Python are automatically declared by assignment. Variables are always references to objects, and are never typed. Variables exist only in the current scope or global scope. When they go out of scope, the variables are destroyed, but the objects to which they refer are not (unless the number of references to the object drops to zero).

Scope is delineated by function and class blocks. Both functions and their scopes can be nested. So therefore

Now when this code is tested,

The name 'bar' is not found because a higher scope does not have access to the names lower in the hierarchy.

It is a common pitfall to fail to assign an object to a variable before use. In its most common form:

Here, to correct this problem, one must add y = [] before the for loop executes.

A loop does not create its own scope:

Keyword global
Global variables of a Python module are read-accessible from functions in that module. In fact, if they are mutable, they can be also modified via method call. However, they cannot be modified by a plain assignment unless they are declared global in the function.

An example to clarify:

Links:
 * 6.13. The global statement, docs.python.org
 * What are the rules for local and global variables in Python? in Programming FAQ, docs.python.org

Keyword nonlocal
Keyword nonlocal, available since Python 3.0, is an analogue of global for nested scopes. It enables a nested function to assign-modify even an immutable variable that is local to the outer function.

An example:

Simulation of nonlocal in Python 2 via a mutable object:

Links:
 * 7.13. The nonlocal statement, docs.python.org

globals and locals
To find out which variables exist in the global and local scopes, you can use locals and globals functions, which return dictionaries:

Write access to locals dictionary is discouraged by the Python documentation.

Links:
 * 2. Built-in Functions # globals, docs.python.org
 * 2. Built-in Functions # locals, docs.python.org