Skip to content
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

False-positive due to missing type narrowing in isinstance of TypeVar #15235

Closed
bersbersbers opened this issue May 13, 2023 · 1 comment · Fixed by #17850
Closed

False-positive due to missing type narrowing in isinstance of TypeVar #15235

bersbersbers opened this issue May 13, 2023 · 1 comment · Fixed by #17850
Labels
bug mypy got something wrong topic-type-narrowing Conditional type narrowing / binder topic-type-variables

Comments

@bersbersbers
Copy link

isnistance on a TypeVared variabled does not correctly narrow the type.

To Reproduce

from typing import TypeVar, Union

T = TypeVar("T", bound=Union["A", "B"])


# Imagine fun being used in a class templated on T
def fun(t: T) -> None:
    if isinstance(t, A):
        print("t is an A: do not print(foo)")
    else:
        print("t must be a B: it is safe to print(foo)")
        # > bug.py:13: error: Item "A" of the upper bound "Union[A, B]" of type variable "T" has no attribute "foo"  [union-attr]
        print(t.foo)


class A:
    ...


class B:
    foo = 0


fun(A())
fun(B())

Expected Behavior

No error

Actual Behavior

bug.py:13: error: Item "A" of the upper bound "Union[A, B]" of type variable "T" has no attribute "foo"  [union-attr]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 1.3.0 (compiled: yes)
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.11.2

python bug,py:

t is an A: do not print(foo)
t must be a B: it is safe to print(foo)
0
@bersbersbers bersbersbers added the bug mypy got something wrong label May 13, 2023
@Bibo-Joshi
Copy link

The issue is still reproducable wtih mypy 1.11.2 (compiled: yes). Interestingly, the problem vanishes if you change the definition of T to T = TypeVar("T", "A", "B").
Note also that pyright sees no problem with either version.

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.

3 participants