Files
Morgan Bartholomew 467785be0e [python] PY-79178/PY-80252 report invalid and unrequired casts
Merge-request: IJ-MR-171620
Merged-by: Morgan Bartholomew <morgan.bartholomew@jetbrains.com>

(cherry picked from commit d9b13a99bad56a112f04febfc939823397b55ddd)

GitOrigin-RevId: a03b56b8c3ea58455af5100e59eab310776e063d
2025-08-31 12:26:25 +00:00

29 lines
1.1 KiB
HTML

<html>
<body>
<p>Reports calls to `typing.cast` where no possible value of the source type can be assignable to the target type. We can refer to this as "non overlapping" types</p>
<p>This usually indicates a mistake. If the conversion is intentional, first convert the expression to the common parent type to make the intent explicit.</p>
<p><b>Example:</b></p>
<pre><code>
from typing import cast
# Non-overlapping types — likely a mistake
<b>cast(int, "a")</b> # 'str' -> 'int'
<b>cast(list[int], ["a"])</b> # 'list[str]' -> 'list[int]'
# Recommended explicit escape hatch is to use a "double cast"
cast(int, <b>cast(object, "a")</b>) # ok
# Legitimate overlapping cases
cast(int, object()) # a valid down cast
cast(object, 1) # a valid up cast
# While the following is an invalid cast, as <code>list</code> is invariant. It's not currently supported by this inspection
int_list = [1, 2, 3]
cast(list[object], int_list)
</code></pre>
<!-- tooltip end -->
<p>The inspection relies on static type information; when a type is unknown, no warning is reported.
Variance of generic types is not yet considered.</p>
</body>
</html>