Skip to content

Mypy infers types of NamedTuple subclass as 'nothing' when using isinstance. #5640

@toshihikoyanase

Description

@toshihikoyanase

I encountered an issue that mypy failed to infer a type of a variable. This issue occurs when isinstance() is applied to a subclass of NamedTuple.

Environment:

  • Python 3.6.5
  • mypy: 0.630

Code

from typing import NamedTuple


class Base:
    pass


class BaseTuple(NamedTuple):
    value: float


class MyTuple(BaseTuple, Base):
    pass


def f(o: Base) -> float:
    if isinstance(o, MyTuple):
        return o.value + 10
    return 0


t = MyTuple(1)
print(f(t))

Python 3.6.5 successfully executes this code and returns 11 as expected. But mypy 0.630 fails to infer the type of o after checking its type using isinstance as follows:

sample.py:18: error: <nothing> has no attribute "value"

Observations:

  • Current master head (commit 5751f42) also has this issue.
  • mypy 0.620 successfully infer the type and does not show this error message.
  • This issue seems to occur from 3fb16a2.
  • mypy 0.630 successfully infer the type if BaseTuple is not a subclass of NamedTuple as follows:
class BaseTuple:

    def __init__(self, value: float) -> None:
        self.value = value

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions