-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Open
Description
mypy can use NoReturn
to narrow types of variables, thus enabling us to express some kinds of guards, in the sense of #1203 / #2357, without using any dedicated mechanism. For example
from typing import Union, NoReturn, overload
@overload
def assert_int(x: int) -> None: ...
@overload
def assert_int(x: str) -> NoReturn: ...
def assert_int(x):
assert isinstance(x, int)
y: Union[int, str]
assert_int(y)
reveal_type(y) # should be: int; currently Union[int, str]
The same technique could be used to narrow types in conditionals, using only "always true" / "always false" types (do we already have such things? maybe it requires singleton True
False
literal-types).
Note that unlike simple isinstance
, this can also be used to correlate two different arguments, test for generic compatibility, etc; it is the responsibility of the programmer to have an actual implementation.
kkozmic, antonagestam, jkhsjdhjs, lbel, captainGeech42 and 2 more