-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
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
Overloads not resolved correctly when argument is Any
and return types use TypeGuard
or TypeIs
#17579
Comments
The same happens with from typing import Any, overload
from typing_extensions import TypeGuard
@overload
def func1(x: str) -> TypeGuard[str]:
...
@overload
def func1(x: int) -> TypeGuard[int]:
...
def func1(x: Any) -> Any:
return True
def func2(val: Any):
if func1(val):
reveal_type(val) # Should be `Any`, but is `str` |
Any
and return types use TypeIs
Any
and return types use TypeGuard
or TypeIs
The problem is that we don't check for overloads here: Lines 5873 to 5890 in db9837f
|
The same happens if from typing import Any, overload
from typing_extensions import TypeGuard, TypeIs
@overload
def func1(x: int | str) -> TypeIs[int]:
...
@overload
def func1(x: list) -> TypeGuard[int]:
...
def func1(x: Any) -> Any:
return True
def func2(val: Any):
if func1(val):
reveal_type(val) # Should be `Any`, but is `int` |
I have a prototype implementation, will create a PR tomorrow 🎉 |
When overload matching is ambiguous due to an
Any
argument, mypy typically looks at the return types of the potential matches. If the return types differ, it evaluates the return type asAny
to preserve the "gradual type guarantee". It apparently doesn't do this when the return types of the potential overload matches useTypeIs
. See the example below, where mypy matches the first overload rather than detecting the ambiguity and evaluatingAny
.I discovered this problem because pyright has the same issue. I'm guessing that the underlying cause of the bug in mypy is similar. Pyright's logic was treating
TypeIs[T]
as equivalent tobool
in this case, butTypeIs[T]
should be treated as a subtype ofbool
. Also,TypeIs[X]
is not equivalent toTypeIs[Y]
unlessX
is equivalent toY
.This bug affects a recent change in typeshed to the
dataclasses.isdataclass
function, as discussed here.The text was updated successfully, but these errors were encountered: