From a8bd2737f6c315c27809ed77b29e9573edf3cdff Mon Sep 17 00:00:00 2001 From: teresa0605 <92952705+teresa0605@users.noreply.github.com> Date: Thu, 4 May 2023 18:52:40 -0400 Subject: [PATCH] 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. --- mypy/messages.py | 8 ++----- test-data/unit/check-assert-type-fail.test | 28 ++++++++++++++++++++++ 2 files changed, 30 insertions(+), 6 deletions(-) create mode 100644 test-data/unit/check-assert-type-fail.test diff --git a/mypy/messages.py b/mypy/messages.py index eb0b5448efdfb..3274f05d8f944 100644 --- a/mypy/messages.py +++ b/mypy/messages.py @@ -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( diff --git a/test-data/unit/check-assert-type-fail.test b/test-data/unit/check-assert-type-fail.test new file mode 100644 index 0000000000000..2811e71978c8b --- /dev/null +++ b/test-data/unit/check-assert-type-fail.test @@ -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] \ No newline at end of file