From 7af36b1be10c5015752ca802cc0d43acdc2a12cc Mon Sep 17 00:00:00 2001 From: Jelle Zijlstra Date: Sun, 17 Apr 2022 15:06:55 -0700 Subject: [PATCH] Fix type context for assert_type() 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(). --- mypy/checkexpr.py | 2 +- test-data/unit/check-expressions.test | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index 32fa391bb0e2..7383a2b69610 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -3145,7 +3145,7 @@ def visit_cast_expr(self, expr: CastExpr) -> Type: return target_type def visit_assert_type_expr(self, expr: AssertTypeExpr) -> Type: - source_type = self.accept(expr.expr, type_context=AnyType(TypeOfAny.special_form), + source_type = self.accept(expr.expr, type_context=self.type_context[-1], allow_none_return=True, always_allow_any=True) target_type = expr.type if not is_same_type(source_type, target_type): diff --git a/test-data/unit/check-expressions.test b/test-data/unit/check-expressions.test index 84b6105170bd..fd10b82cc558 100644 --- a/test-data/unit/check-expressions.test +++ b/test-data/unit/check-expressions.test @@ -1049,6 +1049,20 @@ 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]" [builtins fixtures/tuple.pyi] +[case testAssertTypeGeneric] +from typing import assert_type, TypeVar, Generic +from typing_extensions import Literal +T = TypeVar("T") +def f(x: T) -> T: return x +assert_type(f(1), int) +class Gen(Generic[T]): + def __new__(cls, obj: T) -> Gen[T]: ... +assert_type(Gen(1), Gen[int]) +# With type context, it infers Gen[Literal[1]] instead. +y: Gen[Literal[1]] = assert_type(Gen(1), Gen[Literal[1]]) + +[builtins fixtures/tuple.pyi] + -- None return type -- ----------------