Skip to content

Fix generic NamedTuple class pattern matching#21140

Open
paulorochaoliveira wants to merge 4 commits intopython:masterfrom
paulorochaoliveira:bug/generic-namedtuple-match-pattern
Open

Fix generic NamedTuple class pattern matching#21140
paulorochaoliveira wants to merge 4 commits intopython:masterfrom
paulorochaoliveira:bug/generic-namedtuple-match-pattern

Conversation

@paulorochaoliveira
Copy link
Copy Markdown

Fixes #21050

Description

Preserve named tuple field information when matching against generic class-based NamedTuples.

This updates class-pattern narrowing so a generic named tuple type object is normalized to its named tuple instance fallback before pattern analysis. That keeps keyword field lookup on the named tuple instance type instead of the tuple alias form, so field names and concrete type arguments are preserved.

Tests

Added regressions for:

  • generic NamedTuple with Generic[T] syntax in match class patterns
  • PEP 695 generic NamedTuple syntax in match class patterns

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 2, 2026

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

@paulorochaoliveira paulorochaoliveira marked this pull request as ready for review April 2, 2026 17:00
proper_narrowed_type_for_members.partial_fallback.type.is_named_tuple
):
narrowed_type_for_members = proper_narrowed_type_for_members.partial_fallback

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This keeps the tuple form for class-pattern narrowing, but switches to the namedtuple fallback for keyword field lookup. Without that conversion, generic NamedTuple fields are effectively erased during member access inside the pattern.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

1 participant