-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
isinstance
with generic type
#949
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
IsInstance
with generic typeisinstance
with generic type
Hmm this looks like a mypy bug. It should work like this:
|
And if you try to use |
That seems kind of limited but I guess its the best we can do given we can't modify the behavior of I don't like it because it could be both an |
We are stuck with |
The issue is there logically isn't anything we can infer here, as far as I can tell. Since The use-case I can think of for |
Related #3037 |
On current master it behaves like this: class A(Generic[T]):
pass
class B(A[T]):
pass
x: A[int]
if isinstance(x, B):
reveal_type(x) # Revealed type is '__main__.B[Any]'
isinstance(x, B[int]) # Parameterized generics cannot be used with class or instance checks It looks like the issue is fixed only partially. I think the revealed type should be |
isinstance
with generic typeisinstance
with generic type
Are there any known work-arounds? I mean: are there any reliable ways to ensure that Things I have tried:
Is there anything I am missing? |
For the record, typechecking of generics does work in pytypes (Python 3.7+ support is almost done but not released as of this writing). The issue linked above rather required type inference which is beyond the scope of pytypes. See the specific example that was requested and the answers for clarification. |
In 2022, the way to achieve "slightly unsafe" type-narrowing of generics in this fashion is to use |
For example
is apparently illegal and I'm not sure what replacement I'm supposed to use. It tells me to use a
# type
comment which isn't really applicable here.Removing the
[T]
causes mypy to be unable to infer thatx
is in fact aB[T]
.The text was updated successfully, but these errors were encountered: