NewType Brands IDs Without Runtime Cost
typing.NewType stamps distinct types onto primitives for static checkers while the runtime value stays a plain int with zero overhead.
Code
from typing import NewType
# NewType creates distinct types for static checkers with zero runtime cost
UserId = NewType("UserId", int)
OrderId = NewType("OrderId", int)
def risk_score(user: UserId, order: OrderId) -> str:
return f"user {user} order {order}"
# At runtime a NewType value is just the underlying int
uid = UserId(42)
oid = OrderId(7)
print(risk_score(uid, oid))
print("uid is int:", isinstance(uid, int), "value:", uid)
# Construction is explicit: a bare int does not silently become a UserId
raw = 42
print("same runtime value:", uid == raw, "different types by intent")Output
Captured from a sandboxed run of this snippet in the build pipeline.
user 42 order 7
uid is int: True value: 42
same runtime value: True different types by intentHow it works
The part worth importing is the function risk_score — everything else is wiring.
Points of care
- Only built-in APIs, which leaves no supply chain to vet.
Using it
The signature doing the primary work is def risk_score(user: UserId, order: OrderId) -> str
The run emits 2 labeled sections — uid is int:, same runtime value: — one per step.
risk_score is what another module would consume; nothing else here is load-bearing for callers.
Key statements worth quoting
def risk_score(user: UserId, order: OrderId) -> str:
return f"user {user} order {order}"
Interactive Tools for This Topic
bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.LLM Token & Cost EstimatorEstimate BPE-approximate LLM token counts across English, CJK text, and source code and compare request and batch costs across pricing tiers.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. The file defines `risk_score` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.