You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In the following code I was expecting the type of item to be narrowed inside the conditional. Instead I get an error message about an incompatible return type. The code following the conditional shows that two separated checks do narrow the type.
from typing import TypeVar
VariantResult = dict | None
MISSING: VariantResult = {}
T = TypeVar("T")
def get_something(key: int, default: T) -> int | T:
""" Trying to mimic the type of the "dict.get" method """
return default
def check() -> VariantResult:
item = get_something(123, MISSING)
if item in [None, MISSING]:
return item # Error here*
if item == None:
return None
if item == MISSING:
return MISSING
return {}
*Error: mypy :return-value Incompatible return value type (got "Union[int, Dict[Any, Any], None]", expected "Optional[Dict[Any, Any]]")
The error is unexpected since item can only be one of None or INVALID_SPEC, which are both valid for the result of VariantResult. If they weren't, then the following returns would also fail, but they do not.
The text was updated successfully, but these errors were encountered:
Additionally, the code following the if ... in does not narrow the type either. While there is no way to exlclude the MISSING type, the None type should be excluded. But the item is still marked as | None after the if statement, this fails:
...
def require_int(value: int) -> None:
pass
require_int(item) # Type error, may not be None
In the following code I was expecting the type of
item
to be narrowed inside the conditional. Instead I get an error message about an incompatible return type. The code following the conditional shows that two separated checks do narrow the type.*Error:
mypy :return-value Incompatible return value type (got "Union[int, Dict[Any, Any], None]", expected "Optional[Dict[Any, Any]]")
The error is unexpected since
item
can only be one ofNone
orINVALID_SPEC
, which are both valid for the result ofVariantResult
. If they weren't, then the following returns would also fail, but they do not.The text was updated successfully, but these errors were encountered: