Python

NewType for Nominal IDs

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Python's type system is structural — `UserId` and `PostId` are both just `int` unless you ask otherwise. `NewType` creates a distinct type with zero runtime cost for static checking only.
Python
Raw
from typing import NewType

UserId = NewType("UserId", int)
PostId = NewType("PostId", int)

def delete_user(uid: UserId) -> None: ...
def delete_post(pid: PostId) -> None: ...

u: UserId = UserId(42)
p: PostId = PostId(99)

delete_user(u)        # ✓
# delete_user(p)      # mypy error: PostId is not assignable to UserId
# delete_user(42)     # mypy error: int is not assignable to UserId

# At runtime, UserId IS just int — no overhead.
assert UserId(1) == 1
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.