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.
Code
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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.