Skip to content

Commit

Permalink
Fix assert_type behaviour with Instance last_known_value (#15123)
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
CarlFK and hauntsaninja authored Apr 26, 2023
1 parent bd2a641 commit 6b326d5
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 0 deletions.
6 changes: 6 additions & 0 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
2 changes: 2 additions & 0 deletions test-data/unit/check-expressions.test
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down

0 comments on commit 6b326d5

Please sign in to comment.