Skip to content

Class typevars lose information from isinstance checks #5720

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

Closed
msullivan opened this issue Oct 3, 2018 · 1 comment · Fixed by #19183
Closed

Class typevars lose information from isinstance checks #5720

msullivan opened this issue Oct 3, 2018 · 1 comment · Fixed by #19183
Labels
bug mypy got something wrong false-positive mypy gave an error on correct code priority-1-normal

Comments

@msullivan
Copy link
Collaborator

from typing import Generic, TypeVar

T = TypeVar('T')

class C(Generic[T]):
    def foo(self, x: T) -> None:
        if isinstance(x, int):
            self.bar(x)

    def bar(self, x: T) -> None:
        pass

fails with Argument 1 to "bar" of "C" has incompatible type "int"; expected "T", even though x is obviously a T (that was its annotated type!)

Arguably this is just the Dreaded Intersection Bug (#3603) in a different manifestation?

@msullivan msullivan added bug mypy got something wrong false-positive mypy gave an error on correct code labels Oct 3, 2018
@ilevkivskyi
Copy link
Member

Yes, and this is probably a hardest aspect of the problem, because I don't see an easy way to work around this using some fake TypeInfos for intersections.

ilevkivskyi added a commit that referenced this issue Jun 3, 2025
Fixes #5720
Fixes #8556
Fixes #9778
Fixes #10003
Fixes #10817
Fixes #11163
Fixes #11664
Fixes #12882
Fixes #13426
Fixes #13462
Fixes #14941
Fixes #15151
Fixes #19166

This handles a (surprisingly) common edge case. The charges in
`bind_self()` and `bind_self_fast()` are tricky. I got a few "Redundant
cast" errors there, which seemed good, but then I realized that
attribute access etc. on a type variable go through slow `PyObject`
paths, so I am actually forcing `CallableType` instead of
`F(bound=CallableType)` there, since these are performance-critical
functions.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong false-positive mypy gave an error on correct code priority-1-normal
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants