Types

NewType

NewType creates distinct static identities for runtime-compatible values.

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 42
RUNTIME: INT42STATIC: USERIDUserId(42)
NewType creates a distinct static identity backed by the same runtime type — UserId is int with a name.

At 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
int

The NewType constructor keeps a name for static tools and introspection.

Source

print(UserId.__name__)
print(OrderId.__name__)

Output

UserId
OrderId

Notes

See also

Run the complete example

Example code

Expected output

user 42
True
int
UserId

Execution time appears here after you run the example.