Skip to content

isinstance(x, (T1, T2)) won't narrow the type of x when NamedTuple is involved. #1914

Closed
@kennytm

Description

@kennytm

Test case:

from typing import NamedTuple, Union

A = NamedTuple('A', [('y', int)])
B = NamedTuple('B', [('x', int)])
C = NamedTuple('C', [('x', int)])

def foo(a: Union[A, B, C]):
    if isinstance(a, (B, C)):
        a.x
        b = a # type: Union[B, C]

This fails with:

1.py: note: In function "foo":
1.py:9: error: Some element of union has no attribute "x"
1.py:10: error: Incompatible types in assignment (expression has type "Union[A, B, C]", variable has type "Union[B, C]")

The error happens only when NamedTuple is involved. Otherwise the type of a is correctly narrowed to Union[B, C] inside the branch.

cc #1328

$ mypy -V
mypy 0.4.3
$ python3 -V
Python 3.5.2

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions