Python Glossary Русский

Python 3.11+typingfunction

typing.assert_type

casting and debugging

Assert to the type checker that a value has a given type; a runtime no-op returning the value (3.11+).

Syntax

typing.assert_type(value, typ)

This isn't a runtime tool but rather a test for your annotations themselves: it forces the type checker to confirm the value was inferred as exactly the type you expected, and fails statically on any mismatch. At runtime it does nothing — it just returns the value — so it has no place in ordinary code. Don't confuse it with cast: cast imposes a type, assert_type only checks the one already inferred.

Examples

from typing import assert_type
print(assert_type(5, int))   # → 5
print(assert_type([1, 2], list[int]))   # → [1, 2]
print(repr(assert_type('42', int)))   # → '42'
nums = [1, 2]; print(assert_type(nums, list[int]) is nums)   # → True
print(assert_type(5))   # → TypeError

See also

Open in the full glossarydocs.python.orgReport an inaccuracy