Skip to content

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

@bersbersbers

Description

@bersbersbers

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions