Skip to content

Commit 6b326d5

Browse files
CarlFKhauntsaninja
andauthored
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 <[email protected]>
1 parent bd2a641 commit 6b326d5

File tree

2 files changed

+8
-0
lines changed

2 files changed

+8
-0
lines changed

mypy/checkexpr.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3918,6 +3918,12 @@ def visit_assert_type_expr(self, expr: AssertTypeExpr) -> Type:
39183918
always_allow_any=True,
39193919
)
39203920
target_type = expr.type
3921+
proper_source_type = get_proper_type(source_type)
3922+
if (
3923+
isinstance(proper_source_type, mypy.types.Instance)
3924+
and proper_source_type.last_known_value is not None
3925+
):
3926+
source_type = proper_source_type.last_known_value
39213927
if not is_same_type(source_type, target_type):
39223928
if not self.chk.in_checked_function():
39233929
self.msg.note(

test-data/unit/check-expressions.test

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -937,6 +937,8 @@ reveal_type(returned) # N: Revealed type is "builtins.int"
937937
assert_type(a, str) # E: Expression is of type "int", not "str"
938938
assert_type(a, Any) # E: Expression is of type "int", not "Any"
939939
assert_type(a, Literal[1]) # E: Expression is of type "int", not "Literal[1]"
940+
assert_type(42, Literal[42])
941+
assert_type(42, int) # E: Expression is of type "Literal[42]", not "int"
940942
[builtins fixtures/tuple.pyi]
941943

942944
[case testAssertTypeGeneric]

0 commit comments

Comments
 (0)