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); then in the current global scope (module); then in the built-in scope (which corresponds to module builtins in Python 3.0, and module __builtin__ in Python 2.X). Local and global scope contexts are defined in Table 1-17. global declarations make the search begin in the global scope instead, and nonlocal declarations restrict the search to enclosing functions.

Table 1-17. Unqualified name scopes

Code 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)

Statically Nested Scopes

The enclosing functions search of the last rule in the previous section (Reference: X) is called a statically nested scope, and was made standard in version 2.2. For example, the following function now works because the reference to x within f2 has access to the scope of f1:

def f1():
    x = 42
    def f2():
        print(x)
    f2()

In Python versions prior to 2.2, this function fails because name x is not local (in f2’s scope), global (in the module enclosing f1), or built-in. To make such cases work prior to version 2.2, default arguments retain values from the immediately enclosing scope (defaults are evaluated before entering a def):

def f1():
    x = 42
    def f2(x=x):
        print(x)
    f2()

This rule also applies to lambda expressions, which imply a nested scope just like def and are more commonly nested in practice:

def func(x):
    action = (lambda n: x ** n)        # works as of 2.2
    return action

def func(x):
    action = (lambda n, x=x: x ** n)   # use before 2.2
    return action

Defaults are still sometimes needed to reference loop variables when creating functions inside loops (they reflect their final loop value). Scopes nest arbitrarily, but only enclosing functions (not classes) are searched:

def f1():
    x = 42
    def f2():
        def f3():
            print(x)   # found in f1's scope
        f3()
    f2()


[4] Lexical scopes refer to physically (syntactically) nested code structures in a program’s source code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset