Skip to content

typing.cast used

Detects usage of typing.cast() function calls, which can lead to runtime errors by bypassing type checking without any runtime validation.

typing.cast() tells the type checker to treat a value as a specific type without performing any runtime checks. Type checkers trust casts completely, so incorrect casts bypass all type safety guarantees.

What gets flagged

Python
1
2
3
4
from typing import cast

def foo() -> int:
    return cast(int, "hello")
Unsoundness Checker Output
Text Only
1
2
3
4
5
6
7
8
9
warning[typing-cast-used]: Using `typing.cast()` bypasses type checking and can lead to runtime type errors.
 --> main.py:4:12
  |
3 | def foo() -> int:
4 |     return cast(int, "hello")
  |            ^^^^
  |
info: Consider using `isinstance` checks to ensure types at runtime.
info: rule `typing-cast-used` was selected in the configuration file

Mypy: No Diagnostic Emitted

Pyright: No Diagnostic Emitted

Ty: No Diagnostic Emitted

Better alternative

Instead of using cast(), use assert isinstance() to validate types at runtime:

Python
1
2
3
4
5
6
def get_value() -> int | str:
    return "hello"

result = get_value()
assert isinstance(result, int)
# Now we know it's safe - the assertion will catch incorrect types

Unsoundness Checker: No Diagnostic Emitted

Mypy: No Diagnostic Emitted

Pyright: No Diagnostic Emitted

Ty: No Diagnostic Emitted

This provides actual runtime safety instead of just lying to the type checker.

What is okay

If the type of the value you are casting is assignable to the target type, it is okay to use typing.cast().

Python
1
2
3
4
from typing import cast

def foo() -> int:
    return cast(int, 1)

Unsoundness Checker: No Diagnostic Emitted

Mypy: No Diagnostic Emitted

Pyright: No Diagnostic Emitted

Ty: No Diagnostic Emitted