Namespace and Scope Rules
Names are created when assigned, but must exist when referenced.
Unqualified names (“X”) deal with scopes.
Qualified names (“object.X”) deal with object namespaces.
Assignments in some scopes initialize object attribute namespaces (modules, classes).
Unqualified Names: Global Unless Assigned
- Assignment: X = value
Makes name X local: creates or changes name X in the current local scope, unless declared global.
- Reference: X
Looks for name X in the current local scope, then the current global scope, then the built-in scope.
Qualified Names: Object Namespaces
- 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, classes).
Table 1-13. Unqualified Name Scopes
Context | Global Scope | Local Scope |
---|---|---|
Module | Same as local | The module itself |
Function, method | Enclosing module | Function call |
Class | Enclosing module | Class statement |
Script, interactive mode | Same as local | module __main__ |
exec, eval | Caller’s global (or passed in) | Caller’s local (or passed in) |
Get Python Pocket Reference 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.