← 中文资源

简体中文版本

MappingProxyType 提供只读字典视图

MappingProxyType 把共享字典包成动态只读视图:读操作实时生效,写操作抛 TypeError;内层配 frozenset 或 tuple 才能做到彻底只读。

阅读英文原文

实现说明

各个操作都建立在顶层绑定之上:editable。

使用要点

  • 直接运行文件,输出会带上标签,比如 editor can write:、blocked:、inner frozenset blocks mutation too——输出的每一行都能指回产生它的那次调用。

常见问题

除了语言工具链还要下载什么吗?

除了这个语言的工具链,什么都不用再下载。 全部导入都来自标准库:types。 跨调用保留的状态放在这些顶层绑定里:editable。

核心语句

except TypeError as exc:
    print("blocked:", exc)
except AttributeError:
    print("inner frozenset blocks mutation too")

代码示例

from types import MappingProxyType

ROLE_POLICY = MappingProxyType({
    "viewer": frozenset({"read"}),
    "editor": frozenset({"read", "write"}),
})

print("editor can write:", "write" in ROLE_POLICY["editor"])

# the proxy rejects top-level writes: the shared table callers receive cannot be tampered with
try:
    ROLE_POLICY["admin"] = {"read", "write", "admin"}
except TypeError as exc:
    print("blocked:", exc)

# the read-only view is shallow: inner layers need frozenset/tuple too, a plain set stays mutable
try:
    ROLE_POLICY["viewer"].add("write")
except AttributeError:
    print("inner frozenset blocks mutation too")

# dict() copies it out into a writable version, leaving the source table untouched
editable = dict(ROLE_POLICY)
editable["admin"] = frozenset({"read", "write", "admin"})
print("copy has admin:", "admin" in editable, "| proxy still read-only")