Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix type context for assert_type() #12612

Merged
merged 1 commit into from Apr 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion mypy/checkexpr.py
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
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