Skip to content

Commit 914506b

Browse files
JelleZijlstraJukkaL
authored andcommitted
Fix type context for assert_type() (#12612)
Noticed in python/typeshed#7655 that it was incorrectly inferring list[Any] in all cases. This is because I incorrectly put Any as the type context in the assert_type implementation. Use the current context instead, like for reveal_type().
1 parent 851e89a commit 914506b

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

Diff for: mypy/checkexpr.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3145,7 +3145,7 @@ def visit_cast_expr(self, expr: CastExpr) -> Type:
31453145
return target_type
31463146

31473147
def visit_assert_type_expr(self, expr: AssertTypeExpr) -> Type:
3148-
source_type = self.accept(expr.expr, type_context=AnyType(TypeOfAny.special_form),
3148+
source_type = self.accept(expr.expr, type_context=self.type_context[-1],
31493149
allow_none_return=True, always_allow_any=True)
31503150
target_type = expr.type
31513151
if not is_same_type(source_type, target_type):

Diff for: test-data/unit/check-expressions.test

+14
Original file line numberDiff line numberDiff line change
@@ -1049,6 +1049,20 @@ assert_type(a, Any) # E: Expression is of type "int", not "Any"
10491049
assert_type(a, Literal[1]) # E: Expression is of type "int", not "Literal[1]"
10501050
[builtins fixtures/tuple.pyi]
10511051

1052+
[case testAssertTypeGeneric]
1053+
from typing import assert_type, TypeVar, Generic
1054+
from typing_extensions import Literal
1055+
T = TypeVar("T")
1056+
def f(x: T) -> T: return x
1057+
assert_type(f(1), int)
1058+
class Gen(Generic[T]):
1059+
def __new__(cls, obj: T) -> Gen[T]: ...
1060+
assert_type(Gen(1), Gen[int])
1061+
# With type context, it infers Gen[Literal[1]] instead.
1062+
y: Gen[Literal[1]] = assert_type(Gen(1), Gen[Literal[1]])
1063+
1064+
[builtins fixtures/tuple.pyi]
1065+
10521066
-- None return type
10531067
-- ----------------
10541068

0 commit comments

Comments
 (0)