Skip to content

Commit

Permalink
Fix type context for assert_type() (#12612)
Browse files Browse the repository at this point in the history
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().
  • Loading branch information
JelleZijlstra authored Apr 18, 2022
1 parent 0df8cf5 commit f501cf6
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
2 changes: 1 addition & 1 deletion mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
14 changes: 14 additions & 0 deletions test-data/unit/check-expressions.test
Original file line number Diff line number Diff line change
Expand Up @@ -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
-- ----------------

Expand Down

0 comments on commit f501cf6

Please sign in to comment.