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.
Code
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: TrueInside 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
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.