Skip to content

Commit a8bd273

Browse files
authored
Output distinct types when type names are ambiguous (#15184)
Fixes #12677 When assert_type fails, when the type of value examined and the specified type have the same name, mypy returns an error with more descriptive and distinct names.
1 parent 13f35ad commit a8bd273

File tree

2 files changed

+30
-6
lines changed

2 files changed

+30
-6
lines changed

mypy/messages.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1656,12 +1656,8 @@ def redundant_cast(self, typ: Type, context: Context) -> None:
16561656
)
16571657

16581658
def assert_type_fail(self, source_type: Type, target_type: Type, context: Context) -> None:
1659-
self.fail(
1660-
f"Expression is of type {format_type(source_type, self.options)}, "
1661-
f"not {format_type(target_type, self.options)}",
1662-
context,
1663-
code=codes.ASSERT_TYPE,
1664-
)
1659+
(source, target) = format_type_distinctly(source_type, target_type, options=self.options)
1660+
self.fail(f"Expression is of type {source}, not {target}", context, code=codes.ASSERT_TYPE)
16651661

16661662
def unimported_type_becomes_any(self, prefix: str, typ: Type, ctx: Context) -> None:
16671663
self.fail(
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
[case testAssertTypeFail1]
2+
import typing
3+
import array as arr
4+
class array:
5+
pass
6+
def f(si: arr.array[int]):
7+
typing.assert_type(si, array) # E: Expression is of type "array.array[int]", not "__main__.array"
8+
[builtins fixtures/tuple.pyi]
9+
10+
[case testAssertTypeFail2]
11+
import typing
12+
import array as arr
13+
class array:
14+
class array:
15+
i = 1
16+
def f(si: arr.array[int]):
17+
typing.assert_type(si, array.array) # E: Expression is of type "array.array[int]", not "__main__.array.array"
18+
[builtins fixtures/tuple.pyi]
19+
20+
[case testAssertTypeFail3]
21+
import typing
22+
import array as arr
23+
class array:
24+
class array:
25+
i = 1
26+
def f(si: arr.array[int]):
27+
typing.assert_type(si, int) # E: Expression is of type "array[int]", not "int"
28+
[builtins fixtures/tuple.pyi]

0 commit comments

Comments
 (0)