Types
Casts and Any
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
100cast() 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
dictA 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
98Notes
Anydisables most static checking for a value.cast()tells the type checker to trust you without changing the runtime object.- Prefer narrowing with checks when possible.
See also
- related: Type Hints
- related: Runtime Type Checks
- related: TypedDict
Run the complete example
Expected output
100
True
dict
Execution time appears here after you run the example.