Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

typing.cast

Tell the type checker to treat an expression as the target type.

Version: Python 3.14; repository image, production runtime not attested

Syntax

cast(T, value)

Tell the type checker to treat an expression as the target type.

At runtime cast returns the identical object without conversion or validation. An incorrect cast leaves all operations subject to the actual type.

The string in the example still concatenates and cannot be added to an integer.

Examples

from typing import cast
raw: object = "12"
number = cast(int, raw)
print(number is raw, type(number).__name__, number + "3")
try:
    number + 1
except TypeError:
    print("incompatible")

Result

True str 123
incompatible

The string in the example still concatenates and cannot be added to an integer.

Sources