Skip to content

Commit d8652b4

Browse files
authored
Output a note about use of assert_type in untyped functions (#13626)
`reveal_type` provides a useful note to users that it will always reveal `Any` within an unchecked function. Similarly, `assert_type` always checks against `Any`, but does not notify the user about its behavior. This PR adds said note, which is displayed when `assert_type` raises an error in an unchecked function
1 parent b265daa commit d8652b4

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

mypy/checkexpr.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3724,6 +3724,11 @@ def visit_assert_type_expr(self, expr: AssertTypeExpr) -> Type:
37243724
)
37253725
target_type = expr.type
37263726
if not is_same_type(source_type, target_type):
3727+
if not self.chk.in_checked_function():
3728+
self.msg.note(
3729+
'"assert_type" expects everything to be "Any" in unchecked functions',
3730+
expr.expr,
3731+
)
37273732
self.msg.assert_type_fail(source_type, target_type, expr)
37283733
return source_type
37293734

test-data/unit/check-expressions.test

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -952,6 +952,28 @@ y: Gen[Literal[1]] = assert_type(Gen(1), Gen[Literal[1]])
952952

953953
[builtins fixtures/tuple.pyi]
954954

955+
[case testAssertTypeUncheckedFunction]
956+
from typing import assert_type
957+
from typing_extensions import Literal
958+
def f():
959+
x = 42
960+
assert_type(x, Literal[42])
961+
[out]
962+
main:5: error: Expression is of type "Any", not "Literal[42]"
963+
main:5: note: "assert_type" expects everything to be "Any" in unchecked functions
964+
[builtins fixtures/tuple.pyi]
965+
966+
[case testAssertTypeUncheckedFunctionWithUntypedCheck]
967+
# flags: --check-untyped-defs
968+
from typing import assert_type
969+
from typing_extensions import Literal
970+
def f():
971+
x = 42
972+
assert_type(x, Literal[42])
973+
[out]
974+
main:6: error: Expression is of type "int", not "Literal[42]"
975+
[builtins fixtures/tuple.pyi]
976+
955977
-- None return type
956978
-- ----------------
957979

0 commit comments

Comments
 (0)