Frozenset Guards Constant Tables

Freeze lookup tables with frozenset: mutation fails loudly at the source, hashing lets sets key dicts and appear inside other sets, and algebra still works.

PythonSecurity Boundaries

Code

pythonsnippet
22 lines
REQUIRED_FIELDS = frozenset({"email", "password", "csrf"})
DENIED_EXT = frozenset({".exe", ".bat", ".sh"})

# 可哈希:frozenset 能当 dict 键、能嵌进另一个 set,普通 set 不行
ROUTE_RULES = {REQUIRED_FIELDS: "strict", frozenset(): "open"}
print("route lookup:", ROUTE_RULES[REQUIRED_FIELDS])

# 不可变:篡改常量表在源头就报错,而不是等到下游
try:
    DENIED_EXT.add(".cmd")
except AttributeError as err:
    print("immutability:", type(err).__name__)

# 集合运算照常可用,返回值跟随左侧操作数的类型
upload = {"report.pdf", "run.bat", "notes.md", "setup.bat"}
blocked = upload & DENIED_EXT
print("blocked:", sorted(blocked))
print("allowed:", sorted(upload - blocked))

# 校验表组合:必填字段齐 + 扩展名放行,两条 frozenset 各管一边
payload = {"email", "password", "csrf"}
print("fields ok:", REQUIRED_FIELDS <= payload)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

route lookup: strict
immutability: AttributeError
blocked: []
allowed: ['notes.md', 'report.pdf', 'run.bat', 'setup.bat']
fields ok: True

Inside the snippet

Top-level bindings upload, blocked, payload hold the demo state — nothing sits inside a function scope.

The top-level object literal pins REQUIRED_FIELDS as plain values — no derivation, no imports behind them.

Putting it to use

The demo output is labeled (route lookup:, immutability:, blocked:), so every printed line maps back to its originating operation.

Core lines

except AttributeError as err:
    print("immutability:", type(err).__name__)

Interactive Tools for This Topic

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. Its state lives in module-level bindings: `upload`, `blocked`, `payload`.