Skip to content

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

Closed

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

Activity

  1. ddfisher commented on Jul 21, 2016

    @ddfisher
    Collaborator

    This might be related to #1691.

  2. added this to the milestone on Jul 21, 2016
  3. self-assigned this
    on Mar 14, 2017
  4. added 2 commits that reference this issue on Mar 19, 2017
    50d3823
    07d64f5
  5. added 2 commits that reference this issue on Mar 29, 2017
    67cda6e
    bf20f49
  6. added a commit that references this issue on Apr 4, 2017
    4141d20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions