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 = valueCreates or alters the attribute name
Xin the namespace of theobjectbeing qualified.Reference: object.XSearches for the attribute name
Xin theobject, 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 = valueMakes name
Xlocal by default: creates or changes nameXin the current local scope. IfXis declaredglobal, this creates or changes nameXin the enclosing module’s scope. IfXis declarednonlocalin Python 3.0, this changes nameXin an enclosing function’s scope. Local variables are stored in the call stack at runtime for quick access.Reference: XLooks 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); ...
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