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 (X, in object.X) are known as attributes and live in object namespaces. Assignments in some lexical scopes[4] initialize object namespaces (modules, classes).

Assignment: object.X = value

Creates or alters the attribute name X in the namespace of the object being qualified.

Reference: object.X

Searches for the attribute name X in the 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

Makes name X local by default: creates or changes name X in the current local scope. If X is declared global, this creates or changes name X in the enclosing module’s scope. If X is declared nonlocal in Python 3.0, this changes name X in an enclosing function’s scope. Local variables are stored in the call stack at runtime for quick access.

Reference: X

Looks for name X in 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); ...

Get Python Pocket Reference, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.