Python3 命名空间/作用域

命名空间的种类、作用域查找规则 LEGB、global 与 nonlocal 的使用。

Beginner
Key Points变量查找顺序是 LEGB:局部 → 外层函数 → 全局 → 内置;函数内赋值即视为局部变量,改全局要 global、改外层要 nonlocal。

命名空间

A namespace maps names to objects. Python has three: built-in (builtins, alive from interpreter start), global (module level), and local (created per function call, destroyed on return).

Python
import builtins

g = "global"

def f():
    l = "local"
    print(l, g)
    print('len' in dir(builtins))

f()

print('g' in globals(), 'l' in globals())
print(hasattr(builtins, 'len'), hasattr(builtins, 'g'))
Output
local global
True
True False
True False

作用域

Scope is the region where a namespace is visible; lookup is LEGB: Local → Enclosing → Global → Built-in. The key rule: any assignment inside a function makes that name local for the whole function.

Python
x = "global"

def outer():
    x = "enclosing"

    def inner():
        print("inner sees:", x)
    inner()

outer()

def shadow():
    print(x)
    x = "local"

try:
    shadow()
except UnboundLocalError as e:
    print("UnboundLocalError:", e)

def use_global():
    global x
    x = "changed"

use_global()
print(x)
Output
inner sees: enclosing
UnboundLocalError: cannot access local variable 'x' where it is not associated with a value
changed
UnboundLocalError is the classic scope trap: once you assign to x anywhere in the function, Python treats it as local — so the earlier print(x) hits an unbound name.

global 与 nonlocal

global declares a module-level name; nonlocal declares one from an enclosing function (not global). Both must appear inside the function and before the name is used.

Python
count = 0

def inc():
    global count
    count += 1

inc(); inc()
print(count)

def make_counter():
    n = 0
    def step():
        nonlocal n
        n += 1
        return n
    return step

c = make_counter()
print(c(), c(), c())
Output
2
1 2 3
Use global sparingly — it creates hidden coupling and hurts testability. Prefer keeping state in a class or a mutable container, or pass values through returns.

Friends & Partners