MappingProxyType Exposes Read-Only Dicts

types.MappingProxyType wraps a dict in a dynamic read-only view: reads stay live, writes raise TypeError, and frozenset values freeze the inner levels too.

PythonConfig Management

Code

pythonsnippet
25 lines
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")

How it works

Module-level bindings hold the data — editable — with no function scope in between.

Putting it to use

Running the file prints labeled results such as editor can write:, blocked:, inner frozenset blocks mutation too — each operation’s effect is visible in the output.

Core lines

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

Interactive Tools for This Topic

FAQ

Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. Every import resolves inside the standard library — `types`. Its state lives in module-level bindings: `editable`.