Namespace and Scope Rules
This section discusses rules for name binding and lookup (see also the sections Name format and Name conventions). In all cases, names are created when first assigned but must already exist when referenced. Qualified and unqualified names are resolved differently.
Qualified Names: Object Namespaces
Qualified names (
object.X) are known as attributes and live in object namespaces. Assignments in some lexical scopes initialize object namespaces (modules, classes).
Assignment: object.X = value
Creates or alters the attribute name
Xin the namespace of the
Searches for the attribute name
object, then all accessible classes above it (for instances and classes). This is the definition of inheritance.
Unqualified Names: Lexical Scopes
Unqualified names (
X) involve lexical scope rules. Assignments bind such names
to the local scope unless they are declared global.
Assignment: X = value
Xlocal by default: creates or changes name
Xin the current local scope. If
global, this creates or changes name
Xin the enclosing module’s scope. If
nonlocalin Python 3.0, this changes name
Xin an enclosing function’s scope. Local variables are stored in the call stack at runtime for quick access.
Looks for name
Xin at most four scope categories: in the current local scope (function); then in the local scopes of all lexically enclosing functions (if any, from inner to outer); ...