-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
filtering with isinstance doesn't narrow down types #6847
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
Comments
I think this would be another example if useful: from pathlib import Path
from typing import Union
def maybe_lowercase(obj: Union[str, Path]) -> Union[str, Path]:
if isinstance(obj, str):
return obj.lower()
return obj
def foo(obj: Union[str, Path]) -> str:
if isinstance(obj, Path):
return str(obj)
return maybe_lowercase(obj) In error: Incompatible return value type (got "Union[str, Path]", expected "str") |
@WillAyd your example should use a TypeVar with value restriction to str and Path for |
Yes, this is too tricky. There is a plan to support custom type guards, you can probably use that instead. I am leaving this open as a remainder about the use case. |
from typing import List, Union, TypeGuard
class TypeA: pass
class TypeB: pass
def is_TypeA(x: object) -> TypeGuard[TypeA]:
return isinstance(x, TypeA)
Types = Union[TypeA, TypeB]
t: List[Types] = [TypeA(), TypeB()]
a: List[TypeA] = list(filter(is_TypeA, t)) and then (inside my local clone of typeshed) run mypy's vendored copy of typeshed has yet to include the update to the stub for |
I had about this code (this is a small example):
And I got the following message (both with my distribution's mypy 0.560 and with the current master):
When I remove the type after
a
, it treatsa
asList[Types]
.I get that this might be difficult, but it would be nice if it worked.
This could be related to #476, I'm not sure.
The text was updated successfully, but these errors were encountered: