Python 3.5+typingfunction
typing.cast
casting and debugging
Tell the type checker a value has a given type; at runtime returns the value unchanged.
Syntax
typing.cast(typ, value)
The main trap: cast converts and checks nothing — unlike int(x), it never touches the value, it only silences the type checker. Overusing it hides real bugs, since the checker blindly trusts whatever you assert. Note the argument order is type first, then value — the reverse of assert_type.
Examples
# Python 3.9+
from typing import cast
print(cast(int, 42)) # → 42
print(type(cast(str, 42)).__name__) # → int
print(cast('list[int]', [1, 2])) # → [1, 2]
data = {'x': 1}; print(cast(dict[str, int], data) is data) # → True
print(cast(int, '42') + 1) # → TypeError
See also
Open in the full glossarydocs.python.orgReport an inaccuracy