Skip to content

Honor NoReturn as __setitem__ return type to mark unreachable code. #12572

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

Merged
merged 3 commits into from
Feb 27, 2023
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -4047,14 +4047,17 @@ def check_indexed_assignment(
)

lvalue.method_type = method_type
self.expr_checker.check_method_call(
res_type, _ = self.expr_checker.check_method_call(
"__setitem__",
basetype,
method_type,
[lvalue.index, rvalue],
[nodes.ARG_POS, nodes.ARG_POS],
context,
)
res_type = get_proper_type(res_type)
if isinstance(res_type, UninhabitedType) and not res_type.ambiguous:
self.binder.unreachable()

def try_infer_partial_type_from_indexed_assignment(
self, lvalue: IndexExpr, rvalue: Expression
Expand Down
24 changes: 24 additions & 0 deletions test-data/unit/check-unreachable-code.test
Original file line number Diff line number Diff line change
Expand Up @@ -1423,3 +1423,27 @@ def f(value: None) -> None:

x = force_forward_ref()
[builtins fixtures/exception.pyi]

[case testSetitemNoReturn]
# flags: --warn-unreachable
from typing import NoReturn
class Foo:
def __setitem__(self, key: str, value: str) -> NoReturn:
raise Exception
Foo()['a'] = 'a'
x = 0 # E: Statement is unreachable
[builtins fixtures/exception.pyi]

[case TestNoImplicNoReturnFromError]
# flags: --warn-unreachable
from typing import TypeVar

T = TypeVar("T")
class Foo:
def __setitem__(self, key: str, value: str) -> T: # E: A function returning TypeVar should receive at least one argument containing the same TypeVar
raise Exception

def f() -> None:
Foo()['a'] = 'a'
x = 0 # This should not be reported as unreachable
[builtins fixtures/exception.pyi]