Namespace and Scope Rules

This section discusses rules for name binding and lookup. See also Section and Section earlier, in Section 1.7. 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: creates or changes name X in the current local scope by default. If X is declared global, creates or changes name X in the enclosing module’s scope. Local variables are stored in the call stack for quick access.

Reference: X

Prior to Release 2.2, looks for name X in at most three scopes: the current local scope (function), then the current global scope (module), then the built-in scope (module _ _builtin_ _). Local and global scope contexts are defined in Table 1-16.

In Release 2.2 and later, ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.