python / python/mypy

Generic `NamedTuple` does appear attribute-less in `match` statements, and member type information is erased

Open
#21,050 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

If a NamedTuple is generic over T, then for some reason, inside a match statement over this NamedTuple, all information about member variables and their types are erased. Even if they are explicitly stated.

To Reproduce

from typing import NamedTuple

class Wrapper[T](NamedTuple):
    wrap: T


foo: Wrapper[int] = Wrapper(123)

def bar() -> int:
    match foo:
        case Wrapper(wrap=w):
            return w
        case _:  # this is only to make this error-less with `pyrefly`
            raise RuntimeError("Unreachable")

Expected Behavior

This function clearly matches a Wrapper[int] in its first case. It should detect it can match the internal wrap variable, and it also has to be int.

$ pyrefly check tst.py
 INFO 0 errors
$ pyright tst.py
0 errors, 0 warnings, 0 informations

Actual Behavior

mypy for some reason seems to say that Wrapper does not even have a wrap attribute, and also, it's saying that this is Any, even though the matched Wrapper here is Wrapper[int].

$ mypy --strict tst.py
tst.py:12: error: Class "tst.Wrapper[Any]" has no attribute "wrap"  [misc]
tst.py:13: error: Returning Any from function declared to return "int"  [no-any-return]

Your Environment

  • Mypy version used: 1.19.1
  • Mypy command-line flags: --strict
  • Python version used: 3.12.9

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

Reproduce the report in tst.py using Python 3.12.9 and mypy --strict, then compare the result with pyrefly and pyright as shown. Trace how the generic NamedTuple pattern in the match statement is analyzed; done means w is recognized as the wrap attribute with type int and the example reports no errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.