From 6b326d556e3a34949c363ef1f728abda164a9f24 Mon Sep 17 00:00:00 2001 From: Carl Karsten Date: Tue, 25 Apr 2023 21:30:37 -0500 Subject: [PATCH] Fix assert_type behaviour with Instance last_known_value (#15123) Fixes #12923 assert_type(42, int) ... had issues. #12923 was a bit of a mess as the OP was or wasn't currently accurate. Added two tests to repo the current problem, which now pass. Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com> --- mypy/checkexpr.py | 6 ++++++ test-data/unit/check-expressions.test | 2 ++ 2 files changed, 8 insertions(+) diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index e7428f58ec85..d4b38c9d409c 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -3918,6 +3918,12 @@ def visit_assert_type_expr(self, expr: AssertTypeExpr) -> Type: always_allow_any=True, ) target_type = expr.type + proper_source_type = get_proper_type(source_type) + if ( + isinstance(proper_source_type, mypy.types.Instance) + and proper_source_type.last_known_value is not None + ): + source_type = proper_source_type.last_known_value if not is_same_type(source_type, target_type): if not self.chk.in_checked_function(): self.msg.note( diff --git a/test-data/unit/check-expressions.test b/test-data/unit/check-expressions.test index e2fdaa1b07b8..43bf28e519c6 100644 --- a/test-data/unit/check-expressions.test +++ b/test-data/unit/check-expressions.test @@ -937,6 +937,8 @@ reveal_type(returned) # N: Revealed type is "builtins.int" assert_type(a, str) # E: Expression is of type "int", not "str" assert_type(a, Any) # E: Expression is of type "int", not "Any" assert_type(a, Literal[1]) # E: Expression is of type "int", not "Literal[1]" +assert_type(42, Literal[42]) +assert_type(42, int) # E: Expression is of type "Literal[42]", not "int" [builtins fixtures/tuple.pyi] [case testAssertTypeGeneric]