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.

PythonData Integrity

Code

pythonsnippet
18 lines
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 intent

How 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

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.