"""蓝色天空网 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")
本例需在 本地 Python 环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地 Python 环境
入口文件:projects/python-lab/python3-namespace-scope.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python3-namespace-scope.py,或下载右侧课程工程包。 - 确认本地已准备 本地 Python 环境。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip