typing — type hints and runtime helpers

cast, NewType, TypedDict, get_type_hints, and the documented TypeGuard versus TypeIs difference on Python 3.13, without claiming static checker results.

模块页正文目前为英文。

The typing module holds standard-library typing helpers. At runtime, most of them are markers or thin wrappers: Python does not automatically type-check arguments or return values. This page measures runtime behavior on Python 3.13.12. It does not run mypy or any other static type checker, and it does not treat annotation strings as a runtime contract.

get_type_hints may evaluate annotation expressions, including function calls written in a hint, so you should only use it on code you trust. TypeIs was added in Python 3.13 (PEP 742). TypeGuard is older (PEP 647). Their difference is a documented static-checker contract, not a result measured with a type checker on this machine.

Examples were checked against Python 3.13. See the official documentation for the complete API.

Python reference overview →

cast, NewType, TypedDict, and overload at runtime

cast(int, "x") returns "x" unchanged; the runtime type is still str. NewType("UserId", int)(7) returns 7, and type(user_id) is int. TypedDict builds an ordinary dict: isinstance(point, dict) is True, and a constructor call with an extra key is accepted at runtime.

int | str has origin UnionType and args (int, str). Literal["a", "b"] keeps those two strings as get_args. @overload declarations are not called; the final implementation is the function that runs, so pick(1) returns 1.

cast, NewType, TypedDict, get_origin, get_args, overload

typing.cast(typ, val)
typing.NewType(name, tp)
class typing.TypedDict(dict)
typing.get_origin(tp)
typing.get_args(tp)
@typing.overload

Runtime helpers that do not validate types, plus origin and argument inspection for typing objects.

ParameterDescription
typ, valcast records an intended type for static checkers and returns val unchanged at runtime.
name, tpNewType creates a named alias. The value returned at runtime is still a plain tp instance in this measurement.

Returns: cast returns val. NewType(...) returns a callable that returns its argument. get_origin and get_args return the origin type and its type arguments.

  • These results are runtime facts on Python 3.13.12. A static checker might reject Point(..., z=9) or treat UserId as distinct from int; that was not measured here.
python
import typing

print(typing.cast(int, "x"), type(typing.cast(int, "x")).__name__)

UserId = typing.NewType("UserId", int)
user_id = UserId(7)
print(user_id, type(user_id).__name__, user_id == 7)

class Point(typing.TypedDict):
    x: int
    y: int

point: Point = {"x": 1, "y": 2}
print(point, type(point).__name__, isinstance(point, dict))
extra = Point(x=1, y=2, z=9)
print(extra)

print(typing.get_origin(int | str).__name__)
print(typing.get_args(int | str))
print(typing.get_args(typing.Literal["a", "b"]))

@typing.overload
def pick(value: int) -> str: ...
@typing.overload
def pick(value: str) -> int: ...
def pick(value):
    return value

print(pick(1), pick("a"))

Expected output

x str
7 int True
{'x': 1, 'y': 2} dict True
{'x': 1, 'y': 2, 'z': 9}
UnionType
(<class 'int'>, <class 'str'>)
('a', 'b')
1 a

Related: Built-in types

Official documentation →

get_type_hints, TypeGuard, and TypeIs

With from __future__ import annotations, the annotation marker() is stored as the string "marker()" and is not called at function definition. get_type_hints(lazy) evaluates that expression, so marker runs, and a second get_type_hints call runs it again. Only evaluate hints for code you trust. include_extras=True keeps Annotated[int, "id"] instead of stripping it to int. get_type_hints(1) raises TypeError.

TypeGuard[int] and TypeIs[int] exist at runtime as typing objects whose get_args are (int,). Functions annotated with them still just return a bool; Python does not narrow types at runtime. The documented static difference, not verified with mypy here, is that TypeIs[T] narrows both the true and false branches and requires a consistent input type, while TypeGuard[T] narrows only the true branch and can be used when the types are not compatible, such as list[object] to list[str]. TypeIs is new in 3.13.

get_type_hints, Annotated, TypeGuard, TypeIs

typing.get_type_hints(obj, globalns=None, localns=None, include_extras=False)
typing.Annotated[T, x]
typing.TypeGuard[C]
typing.TypeIs[C]

Resolve annotations, including executing deferred hint expressions, and inspect TypeGuard and TypeIs objects at runtime.

ParameterDescription
objA function, method, class, or module. Values that cannot carry annotations raise TypeError.
include_extrasIf True, Annotated metadata is kept. If False, get_type_hints returns the underlying type.

Returns: A dict of evaluated type hints for get_type_hints. TypeGuard and TypeIs objects can be inspected with get_origin and get_args.

Raises

  • TypeError — get_type_hints(1) raised TypeError on Python 3.13.12.
  • This page does not run mypy, pyright, or another static type checker, and it does not invent a static narrowing result. The TypeGuard versus TypeIs behavior described in the prose follows the Python 3.13 documentation (PEP 647 and PEP 742).
python
from __future__ import annotations

import typing

calls = []

def marker():
    calls.append("ran")
    return int

def lazy(value: marker()) -> None:
    pass

print("after-def", calls)
print(lazy.__annotations__)
print(typing.get_type_hints(lazy))
print("after-hints", calls)
print(typing.get_type_hints(lazy))
print("after-second", calls)

def tagged(value: typing.Annotated[int, "id"]) -> None:
    pass

print(typing.get_type_hints(tagged))
print(typing.get_type_hints(tagged, include_extras=True))

try:
    typing.get_type_hints(1)
except TypeError as exc:
    print(type(exc).__name__)

print(typing.get_origin(typing.TypeGuard[int]))
print(typing.get_args(typing.TypeGuard[int]))
print(typing.get_origin(typing.TypeIs[int]))
print(typing.get_args(typing.TypeIs[int]))

def is_int_guard(value: object) -> typing.TypeGuard[int]:
    return isinstance(value, int)

def is_int_is(value: object) -> typing.TypeIs[int]:
    return isinstance(value, int)

print(is_int_guard("x"), is_int_is(1))

Expected output

after-def []
{'value': 'marker()', 'return': 'None'}
{'value': <class 'int'>, 'return': <class 'NoneType'>}
after-hints ['ran']
{'value': <class 'int'>, 'return': <class 'NoneType'>}
after-second ['ran', 'ran']
{'value': <class 'int'>, 'return': <class 'NoneType'>}
{'value': typing.Annotated[int, 'id'], 'return': <class 'NoneType'>}
TypeError
typing.TypeGuard
(<class 'int'>,)
typing.TypeIs
(<class 'int'>,)
False True

Official documentation →