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.overloadRuntime helpers that do not validate types, plus origin and argument inspection for typing objects.
| Parameter | Description |
|---|---|
typ, val | cast records an intended type for static checkers and returns val unchanged at runtime. |
name, tp | NewType 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.
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