Skip to content

Unpacking a NamedTuple subclass uses superclass' types #8663

Open
@brettcs

Description

@brettcs

If you subclass an existing NamedTuple to provide more specific type declarations for some of the fields, and then unpack an instance of that NamedTuple, mypy 0.770 gets its type information from the superclass, not the subclass. Minimal reproduction:

from typing import NamedTuple, Optional

class BaseInventory(NamedTuple):
    number: Optional[int]
    name: str


class Inventory(BaseInventory):
    number: int


item = Inventory(42, 'parrot')
item.number % 10  # mypy allows this
number, _ = item
number % 10  # mypy does not allow this

The last line reports:

error: Unsupported operand types for % ("None" and "int")  [operator]
note: Left operand is of type "Optional[int]"

I expected no error, since accessing the field by name works fine.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions