More types
This section introduces a few additional kinds of types, including NoReturn
,NewType
, TypedDict
, and types for async code. It also discusseshow to give functions more precise types using overloads. All of these are onlysituationally useful, so feel free to skip this section and come back when youhave a need for some of them.
Here’s a quick summary of what’s covered here:
NoReturn
lets you tell mypy that a function never returns normally.NewType
lets you define a variant of a type that is treated as aseparate type by mypy but is identical to the original type at runtime.For example, you can haveUserId
as a variant ofint
that isjust anint
at runtime.@overload
lets you define a function that can accept multiple distinctsignatures. This is useful if you need to encode a relationship between thearguments and the return type that would be difficult to express normally.TypedDict
lets you give precise types for dictionaries that representobjects with a fixed schema, such as{'id': 1, 'items': ['x']}
.- Async types let you type check programs using
async
andawait
.