Types
NewType
NewType helps type checkers distinguish values that share a runtime representation.
Source
from typing import NewType
UserId = NewType("UserId", int)
OrderId = NewType("OrderId", int)
def load_user(user_id: UserId) -> str:
return f"user {user_id}"
uid = UserId(42)
print(load_user(uid))Output
user 42At runtime, a NewType value is the underlying value. It compares like that value and has the same runtime type.
Source
oid = OrderId(42)
print(uid == oid)
print(type(uid).__name__)Output
True
intThe NewType constructor keeps a name for static tools and introspection.
Source
print(UserId.__name__)
print(OrderId.__name__)Output
UserId
OrderIdNotes
NewTypehelps type checkers distinguish values that share a runtime representation.- At runtime, the value is still the underlying type.
- Use aliases for readability; use
NewTypefor static separation.
See also
- related: Type Aliases
- related: Type Hints
- related: Runtime Type Checks
Run the complete example
Expected output
user 42
True
int
UserId
Execution time appears here after you run the example.