On this page
typing.NewType
Prev: typing.IO | Up: typing | Next: typing.ParamSpec
Rel: typing.AbstractSet, typing.Annotated, typing.Any, typing.assert_never
Ref: docs.python.org — typing.NewType
Tags: #public #python3 #stdlib #typing
Import
import typing
from typing import NewType
Signature & Overview
typing.NewType(name, tp)
NewType creates simple unique types with almost zero runtime overhead.
Usage
from typing import NewType
UserId = NewType("UserId", int)
uid = UserId(42)
assert uid == 42 and type(uid) is int
Gotchas
- Zero runtime overhead: At runtime
UserId(42)simply returns42(int), soisinstance(uid, UserId)raisesTypeError—NewTypeexists purely for static type safety.
REPL Inspect
from typing import NewType
help(NewType)
Linked from
Related notes
- tuts/python3/stdlib_module/typing/IO Linked here; links to this page; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/ParamSpec Linked here; links to this page; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/typing/AbstractSet Linked here; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/Annotated Linked here; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/Any Linked here; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/assert_never Linked here; shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/assert_type shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/AsyncContextManager shared tags: #stdlib, #typing
- tuts/python3/stdlib_module/typing/AsyncGenerator shared tags: #stdlib, #typing