python / python/mypy

Unpacking a NamedTuple subclass uses superclass' types

Open
#8,663 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-inheritance topic-named-tuple
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the minimal Python reproduction with mypy 0.770 and compare named-field access with tuple unpacking. Trace how NamedTuple subclass type information is used during unpacking; done when the unpacked number is inferred as int and the final modulo line no longer reports an error, with regression coverage for this reproduction.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.