Skip to content

Commit 002e309

Browse files
authored
Fix handling of NoReturn in Union return types (#11996)
There are several discussions and comments describing the following problem (references can be found at the end of the PR summary): ```python def func() -> str | NoReturn: ... func().lower() ``` At the moment the code results in: `"NoReturn" of "Union[str, NoReturn]" has no attribute "lower"` Make `Union[int, NoReturn]` equivalent to `int` in a return type, because in case the function returns it must be `int`.
1 parent 9b31477 commit 002e309

File tree

2 files changed

+7
-0
lines changed

2 files changed

+7
-0
lines changed

mypy/checkexpr.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,8 @@ def visit_call_expr_inner(self, e: CallExpr, allow_none_return: bool = False) ->
378378
if isinstance(e.callee, MemberExpr) and e.callee.name == 'format':
379379
self.check_str_format_call(e)
380380
ret_type = get_proper_type(ret_type)
381+
if isinstance(ret_type, UnionType):
382+
ret_type = make_simplified_union(ret_type.items)
381383
if isinstance(ret_type, UninhabitedType) and not ret_type.ambiguous:
382384
self.chk.binder.unreachable()
383385
# Warn on calls to functions that always return None. The check

test-data/unit/check-unions.test

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,11 @@ f(1)
144144
f(None)
145145
f('') # E: Argument 1 to "f" has incompatible type "str"; expected "Optional[int]"
146146

147+
[case testUnionWithNoReturn]
148+
from typing import Union, NoReturn
149+
def f() -> Union[int, NoReturn]: ...
150+
reveal_type(f()) # N: Revealed type is "builtins.int"
151+
147152
[case testUnionSimplificationGenericFunction]
148153
from typing import TypeVar, Union, List
149154
T = TypeVar('T')

0 commit comments

Comments
 (0)