Skip to content

Commit

Permalink
Output a note about use of assert_type in untyped functions (#13626)
Browse files Browse the repository at this point in the history
`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
  • Loading branch information
rsokl authored Sep 8, 2022
1 parent b265daa commit d8652b4
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
5 changes: 5 additions & 0 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
22 changes: 22 additions & 0 deletions test-data/unit/check-expressions.test
Original file line number Diff line number Diff line change
Expand Up @@ -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
-- ----------------

Expand Down

0 comments on commit d8652b4

Please sign in to comment.