Skip to content

Commit

Permalink
Output distinct types when type names are ambiguous (#15184)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
teresa0605 committed May 4, 2023
1 parent 13f35ad commit a8bd273
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
8 changes: 2 additions & 6 deletions mypy/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -1656,12 +1656,8 @@ def redundant_cast(self, typ: Type, context: Context) -> None:
)

def assert_type_fail(self, source_type: Type, target_type: Type, context: Context) -> None:
self.fail(
f"Expression is of type {format_type(source_type, self.options)}, "
f"not {format_type(target_type, self.options)}",
context,
code=codes.ASSERT_TYPE,
)
(source, target) = format_type_distinctly(source_type, target_type, options=self.options)
self.fail(f"Expression is of type {source}, not {target}", context, code=codes.ASSERT_TYPE)

def unimported_type_becomes_any(self, prefix: str, typ: Type, ctx: Context) -> None:
self.fail(
Expand Down
28 changes: 28 additions & 0 deletions test-data/unit/check-assert-type-fail.test
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
[case testAssertTypeFail1]
import typing
import array as arr
class array:
pass
def f(si: arr.array[int]):
typing.assert_type(si, array) # E: Expression is of type "array.array[int]", not "__main__.array"
[builtins fixtures/tuple.pyi]

[case testAssertTypeFail2]
import typing
import array as arr
class array:
class array:
i = 1
def f(si: arr.array[int]):
typing.assert_type(si, array.array) # E: Expression is of type "array.array[int]", not "__main__.array.array"
[builtins fixtures/tuple.pyi]

[case testAssertTypeFail3]
import typing
import array as arr
class array:
class array:
i = 1
def f(si: arr.array[int]):
typing.assert_type(si, int) # E: Expression is of type "array[int]", not "int"
[builtins fixtures/tuple.pyi]

0 comments on commit a8bd273

Please sign in to comment.