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) |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access