diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index 20b11fe1c0d7..567d64fa05fa 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -3724,6 +3724,11 @@ def visit_assert_type_expr(self, expr: AssertTypeExpr) -> Type: ) target_type = expr.type if not is_same_type(source_type, target_type): + if not self.chk.in_checked_function(): + self.msg.note( + '"assert_type" expects everything to be "Any" in unchecked functions', + expr.expr, + ) self.msg.assert_type_fail(source_type, target_type, expr) return source_type diff --git a/test-data/unit/check-expressions.test b/test-data/unit/check-expressions.test index bcd466616551..1a1272002562 100644 --- a/test-data/unit/check-expressions.test +++ b/test-data/unit/check-expressions.test @@ -952,6 +952,28 @@ y: Gen[Literal[1]] = assert_type(Gen(1), Gen[Literal[1]]) [builtins fixtures/tuple.pyi] +[case testAssertTypeUncheckedFunction] +from typing import assert_type +from typing_extensions import Literal +def f(): + x = 42 + assert_type(x, Literal[42]) +[out] +main:5: error: Expression is of type "Any", not "Literal[42]" +main:5: note: "assert_type" expects everything to be "Any" in unchecked functions +[builtins fixtures/tuple.pyi] + +[case testAssertTypeUncheckedFunctionWithUntypedCheck] +# flags: --check-untyped-defs +from typing import assert_type +from typing_extensions import Literal +def f(): + x = 42 + assert_type(x, Literal[42]) +[out] +main:6: error: Expression is of type "int", not "Literal[42]" +[builtins fixtures/tuple.pyi] + -- None return type -- ----------------