Skip to content

isinstance erases type info #12949

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
gsakkis opened this issue Jun 7, 2022 · 3 comments · Fixed by #18972
Closed

isinstance erases type info #12949

gsakkis opened this issue Jun 7, 2022 · 3 comments · Fixed by #18972
Labels
bug mypy got something wrong topic-type-narrowing Conditional type narrowing / binder topic-type-variables

Comments

@gsakkis
Copy link

gsakkis commented Jun 7, 2022

Bug Report

Accessing a variable of a generic type after an if isinstance() against a (non-generic) subclass of said type changes the variable's type to <nothing> within the isinstance clause scope:

from typing import List, TypeVar

class IntList(List[int]):
    pass

T = TypeVar("T")

def f(s: List[T]) -> T:
    reveal_type(s)
    if isinstance(s, IntList):
        reveal_type(s)
        s.pop()
    reveal_type(s)
    return s.pop()

Expected Behavior

No error.

Actual Behavior

note: Revealed type is "builtins.list[T`-1]"
note: Revealed type is "<nothing>"
error: <nothing> has no attribute "pop"  [attr-defined]
note: Revealed type is "builtins.list[T`-1]"

Your Environment

  • Mypy version used: 0.960
@gsakkis gsakkis added the bug mypy got something wrong label Jun 7, 2022
@AlexWaygood AlexWaygood added topic-type-variables topic-type-narrowing Conditional type narrowing / binder labels Jun 7, 2022
@erictraut
Copy link

This is a duplicate of #8252.

This bug report is a simpler demonstration of the bug, so it might be worth keeping this one open and closing the other.

@ichard26
Copy link
Collaborator

#8252, which I just closed, contains some more examples of this issue.

@erictraut
Copy link

I think this might also be the same as #15793.

jhance pushed a commit that referenced this issue May 8, 2025
Fixes #18967
Fixes #16494
Fixes #15793
Fixes #12949

As you can see from updated test cases, it is kind of gray area, so
whether we go this way will depend on the `mypy_primer` results (and
also potentially on Dropbox internal code bases, where the above issue
may cause problems).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-type-narrowing Conditional type narrowing / binder topic-type-variables
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants