蓝色天空.知识 · 实践 · 创造
我的收藏
Python 教程目录 82章
课程介绍
Python / LEARN BY DOING

Python3 命名空间与作用域

跟踪同名绑定如何被读取、遮蔽和重新绑定,并区分模块、类体和闭包。

学完这一章,你能够

  • 跟踪同名绑定如何被读取、遮蔽和重新绑定,并区分模块、类体和闭包。

名字、对象和可见范围

命名空间把名称绑定到对象。不同模块可以各自拥有 status,读取时用模块名限定。可以把这件事想成在不同文件夹中寻找同名文件。Python 的映射还允许不同名称引用同一个对象,重新绑定其中一个名称不会自动改动另一个。

作用域描述无前缀名称在哪段代码中可直接查找。模块的全局命名空间通常由其字典体现,类体建立自己的类命名空间,函数调用有本次调用的局部绑定。函数参数也是局部名。要查看内置名称,可 import builtins 后执行 dir(builtins)。abs、chr、Exception 都在其中,char 不是 Python 3 的内置函数,if 等语法关键字也不通过内置名称查找。

名称是否可直接访问与对象能存活多久是两件事。普通局部名称不会自动出现在模块中,但函数可返回局部对象。闭包还能在外层调用结束后保留需要的绑定。两次调用闭包工厂可得到彼此独立的状态。

沿普通函数的 LEGB 查找

从当前函数查找无前缀名字时,可以按 L 局部、E 外层函数、G 函数定义所在模块、B 内置理解。嵌套多层函数时先检查最近的外层函数绑定。若各处都没有可用绑定,会出现 NameError。图中的四个结果来自四个独立的本站运行场景。

局部、外层函数、定义模块和内置四个场景的实际结果
本站四次独立运行的名称查找结果。前三行找到各自的绑定,第四行调用内置 abs 得到 9。

同名的局部绑定会遮蔽外层名称。函数体中只要有某个名称的绑定操作,且未用 global 或 nonlocal 改写规则,通常整段函数都把它视为局部名。即使赋值位于未运行的分支,赋值前读取该局部名也会触发 UnboundLocalError。它是 NameError 的子类。

类体、普通语句与推导式的边界

类体可定义属性,也可用前面已绑定的类体名称继续计算。方法中的普通无前缀查找不会把类命名空间当作外层函数。要读类属性,可用 self.name 或 ClassName.name。Python 3.12 中的类型别名注解作用域另有规则,可访问所属类命名空间。

if、for、while 和 try 不建立普通局部作用域。如果分支确实执行了赋值,同一作用域的后续语句可以读取该名称。未执行的分支没有建立绑定。except ... as error 的异常目标会在处理器退出时清除。Python 3 的推导式循环目标也不会泄漏到外围,即使 CPython 3.12 对列表、集合和字典推导式做了内联优化。

选择重绑定方式

函数读取自己定义模块里的全局名称。普通局部赋值只建立或更新局部名称。用 global 声明后,赋值更新函数定义模块的绑定,即使函数从别处调用。本站让库存模块的 count 从 12 变为 18。订单模块中的 stock.count 随之变为 18,而先前用 from 导入的整数 count 仍为 12。把这个整数传给函数计算会返回 13,原绑定依旧为 12。删除订单模块里的导入名会使当地再次读取时报 NameError,库存模块仍保留 18。

在嵌套函数中,用 nonlocal 重新绑定最近的、已经存在的外层函数变量。它不会退到模块作用域。没有符合条件的外层绑定时,编译会报 SyntaxError。两个独立计数器可以据此各自累计。

修改已找到的对象与重绑名称应分开看。读取外层列表再调用 append 会修改该列表,无须 global 或 nonlocal。若要让同一外层名称指向另一个列表,则必须选择对应的声明或返回新值。

四种查找位置与重绑定

位置或写法普通函数中的含义本地可观察结果
L当前调用的局部绑定同名局部参数或变量优先
E最近的匹配外层函数绑定外层调用返回后闭包仍可读取
G函数定义所在的模块换一个调用者不会改变查找模块
B模块使用的内置命名空间其余位置无 abs 绑定时找到内置函数
global把声明的名称指向模块绑定读原值后可在本模块重绑定
nonlocal把声明的名称指向已有外层函数绑定独立闭包保留各自的累积值
显式传参和返回局部参数绑定到调用时传入的对象算出新整数后原名称仍保持旧值

本章自编源码与运行范围

含完整源码 · 206 行
展开查看收起
Python
"""蓝色天空网 mbsky.com | Test namespace behavior in isolated owned modules."""
import builtins
import keyword
from pathlib import Path
import sys
from types import ModuleType

sys.path.insert(0, str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks


def owned_module(name, source):
    module = ModuleType(name)
    exec(compile(source, f"<{name}>", "exec"), vars(module))
    return module


def lookup_and_closure(checks):
    local = owned_module("scope_local", """
abs = "module"
def enclosing():
    abs = "outer"
    def read():
        abs = "local"
        return abs
    return read
""")
    enclosing = owned_module("scope_enclosing", """
abs = "module"
def enclosing():
    abs = "outer"
    def read():
        return abs
    return read
""")
    global_scope = owned_module("scope_global", """
abs = "module"
def enclosing():
    def read():
        return abs
    return read
""")
    builtin_scope = owned_module("scope_builtin", """
def enclosing():
    def read():
        return abs(-9)
    return read
""")
    for label, module, expected in (
        ("L local", local, "local"),
        ("E enclosing", enclosing, "outer"),
        ("G defining module", global_scope, "module"),
        ("B builtin abs", builtin_scope, 9),
    ):
        reader = module.enclosing()
        checks.eq(label, reader(), expected)

    def other_caller(reader):
        abs = "caller"
        return abs, reader()

    checks.eq("caller locals do not alter defining module",
              other_caller(global_scope.enclosing()), ("caller", "module"))
    checks.eq("same name distinct modules", (global_scope.abs, local.abs), ("module", "module"))
    local.abs = "only local module"
    checks.eq("module names remain isolated", (global_scope.abs, local.abs), ("module", "only local module"))
    checks.eq("inner function name not exported", hasattr(enclosing, "read"), False)
    checks.eq("closure keeps captured value", enclosing.enclosing()(), "outer")
    local_object = object()
    alias = local_object
    local_object = object()
    checks.eq("rebind leaves alias on earlier object", alias is local_object, False)
    missing = owned_module("scope_missing", "def read():\n    return missing_dispatch")
    checks.raises("completely missing name", NameError, missing.read)
    checks.eq("dir builtins includes modern spellings",
              all(name in dir(builtins) for name in ("abs", "chr", "BaseException", "Exception")), True)
    checks.eq("char is absent", hasattr(builtins, "char"), False)
    checks.eq("keyword is not an ordinary builtin binding",
              (keyword.iskeyword("if"), hasattr(builtins, "if")), (True, False))


def scope_boundaries(checks):
    module = owned_module("scope_class", """
prefix = "module"
class Dispatch:
    prefix = "class"
    label = prefix + "-body"
    Item = int
    type ItemList = list[Item]
    def unqualified(self):
        return prefix
    def qualified(self):
        return self.prefix
""")
    checks.eq("class body can see earlier class binding", module.Dispatch.label, "class-body")
    checks.eq("method bypasses class lexical names", module.Dispatch().unqualified(), "module")
    checks.eq("explicit instance lookup sees class attribute", module.Dispatch().qualified(), "class")
    checks.eq("3.12 annotation scope sees enclosing class", repr(module.Dispatch.ItemList.__value__),
              "list[int]")

    if True:
        destination = "dock"
    for stop in ("quay",):
        last_stop = stop
    remaining = 1
    while remaining:
        remaining -= 1
        cleared = remaining == 0
    try:
        parcel = "B7"
        int("dock")
    except ValueError as error:
        recovery = type(error).__name__
    checks.eq("executed blocks reuse current scope", (destination, last_stop, cleared, parcel, recovery),
              ("dock", "quay", True, "B7", "ValueError"))

    def read_cleared_target():
        try:
            raise ValueError("owned")
        except ValueError as caught:
            observed = type(caught).__name__
        return observed, caught

    checks.raises("except target cleared on exit", UnboundLocalError, read_cleared_target)
    branch = owned_module("scope_branch", "if False:\n    absent = 1\n")
    checks.eq("unexecuted branch establishes no binding", hasattr(branch, "absent"), False)
    marker = "outer"
    squares = [marker * marker for marker in (2, 3)]
    checks.eq("comprehension target stays isolated", (squares, marker), ([4, 9], "outer"))
    checks.raises("class comprehension skips class-local lookup", NameError,
                  lambda: owned_module("scope_comp", "class C:\n    rate = 3\n    values = [rate for _ in [0]]"))

    def internal():
        hidden = "packet"
        return hidden

    checks.eq("function returns local object", internal(), "packet")
    checks.eq("function local absent from module", "hidden" in globals(), False)


def rebinding(checks):
    module = owned_module("scope_rebinding", """
rate = 12
def read():
    return rate
def shadow():
    rate = 30
    return rate
def update():
    global rate
    before = rate
    rate = 18
    return before, rate
def broken():
    if False:
        rate = 30
    return rate
def broken_augmented():
    rate = rate + 1
    return rate
def parameter(rate):
    rate = rate + 1
    return rate
def counter(start):
    count = start
    def step(amount):
        nonlocal count
        count += amount
        return count
    def read():
        return count
    return step, read
def use_outer_list():
    notes = []
    def add():
        notes.append("delivered")
    add()
    return notes
""")
    checks.eq("read global without declaration", module.read(), 12)
    checks.eq("local assignment does not rebind global", (module.shadow(), module.rate), (30, 12))
    checks.raises("compile-time local even in dead branch", UnboundLocalError, module.broken)
    checks.raises("same-name read before assignment", UnboundLocalError, module.broken_augmented)
    checks.eq("local error is NameError subclass", issubclass(UnboundLocalError, NameError), True)
    checks.eq("global read and rebind", (module.update(), module.rate), ((12, 18), 18))
    passed = module.rate
    checks.eq("explicit parameter and return", (module.parameter(passed), passed, module.rate), (19, 18, 18))
    first, read_first = module.counter(4)
    second, read_second = module.counter(50)
    checks.eq("nonlocal retained and independent", (first(3), read_first(), second(2), first(1), read_second()),
              (7, 7, 52, 8, 52))
    checks.eq("mutate found object without rebinding", module.use_outer_list(), ["delivered"])
    checks.raises("nonlocal without outer binding", SyntaxError,
                  lambda: compile("rate = 1\ndef outer():\n    nonlocal rate", "<own>", "exec"))
    checks.raises("global declared after use", SyntaxError,
                  lambda: compile("def outer():\n    print(rate)\n    global rate", "<own>", "exec"))


if __name__ == "__main__":
    checks = Checks()
    lookup_and_closure(checks)
    scope_boundaries(checks)
    rebinding(checks)
    checks.finish("python3-namespace-scope", runtime=sys.version, implementation=sys.implementation.name,
                  invocation="fixed site-authored fixtures in distinct ModuleType namespaces, no external source executed")

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。

本章附件与实例包

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip

常见错误与边界检查

  • 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。

技术规范与官方资料

练习与参考解答

查看参考解答

比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习