← Back to index

directives_cast.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 3
FP: 0
FN: 0
Optional: 0 / 0
1"""
2Tests the typing.cast call.
3"""
4
5# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#cast
6
7from typing import cast
8
9def find_first_str(a: list[object]) -> str:
10 index = next(i for i, x in enumerate(a) if isinstance(x, str))
11 return cast(str, a[index])
13x: int = cast(int, "not an int") # No type error
15bad1 = cast() # E: Too few arguments
[missing-argument] No arguments provided for required parameters `typ`, `val` of function `cast`
16bad2 = cast(1, "") # E: Bad first argument type
[invalid-type-form] Int literals are not allowed in this context in a type expression
17bad3 = cast(int, "", "") # E: Too many arguments
[too-many-positional-arguments] Too many positional arguments to function `cast`: expected 2, got 3