You're absolutely right to question this! In an ideal world, you should always annotate your variables properly instead of relying on cast. However, there are a few rare cases where cast might be the most practical solution—though they’re often signs of poor type hygiene. Let’s clarify when (if ever) cast is truly necessary.
When cast Might Be Justified (But Still Questionable)
1. Working with Any from Untyped Libraries
If a function returns Any (e.g., from json.loads() or a legacy library), you could annotate the variable directly:
import json
from typing import Any, List
raw_data = '{"numbers": [1, 2, 3]}'
parsed: dict[str, Any] = json.loads(raw_data) # ✅ Better: Annotate `parsed`
numbers: List[int] = parsed["numbers"] # Type checker may complain here
2. Overriding Incorrect Union Inference
Sometimes type checkers struggle with Union narrowing:
from typing import Union, cast
def get_value() -> Union[int, str]:
return 42 # Suppose this sometimes returns str
value = get_value()
if isinstance(value, int):
# Without `cast`, some type checkers may still see `value` as `Union[int, str]` here
int_value: int = cast(int, value) # 😕 Sometimes needed for older type checkers
- Modern Fix: Use
assert isinstance(value, int) or typing.TypeGuard (Python 3.10+).
3. Interop with Protocols or Dynamic Code
If you’re using structural typing (Protocol) or @property with type overrides, cast can force a type: