Types

Casts and Any

Any and cast are escape hatches for places static analysis cannot prove.

Any disables most static checking for a value. The runtime object is still whatever value was actually assigned.

Source

from typing import Any, cast

raw: Any = {"score": "98"}
score_text = cast(dict[str, str], raw)["score"]
score = int(score_text)
print(score + 2)

Output

100
Anycast(T, x)T
cast(T, x) tells the type checker to treat x as T; the runtime is unaffected.

cast() does not convert or validate the value. It returns the same object at runtime.

Source

print(cast(list[int], raw) is raw)
print(type(raw).__name__)

Output

True
dict

A real runtime check narrows by inspecting the value. This is safer when the input is untrusted.

Source

value: object = {"score": "98"}
if isinstance(value, dict):
    print(value["score"])

Output

98

Notes

See also

Run the complete example

Example code

Expected output

100
True
dict

Execution time appears here after you run the example.