python / python/mypy

Cannot infer generic parameter types within `match` statements

Open
#18,432 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

Related to #13612.

#13618 fixed the error reported in #13612, so mypy correctly infers the type of the unpacked value.

However, mypy does not correctly infer the type parameter of the class containing the generic attribute within the scope of the match statement, despite correct inference outside the statement.

To Reproduce

Extending the reprex from #13612:

from typing import Generic, TypeVar

T = TypeVar("T")


class A(Generic[T]):
    x: T

    __match_args__ = ("x",)

    def __init__(self, x: T):
        self.x = x


a = A("foo")
reveal_type(a)    # A[builtins.str] (correct)
reveal_type(a.x)  # builtins.str (correct)

match a:
    case A(x) as a_match:
        reveal_type(x)          # builtins.str (correct)
        reveal_type(a_match)    # A[Any]  **(incorrect! should be A[str])**

Expected Behavior

Within the match statement, A(x) should be inferred to be of type A[str].

Revealed type is "test_generic.A[builtins.str]"
Revealed type is "builtins.str"
Revealed type is "builtins.str"
Revealed type is "test_generic.A[builtins.str]"

I have found that pyright, or at least the pylance VS code extension, infers this correctly. See below:

Screenshot 2025-01-09 at 4 25 24 PM

Actual Behavior

The final line does not reveal A[str].

Revealed type is "test_generic.A[builtins.str]"
Revealed type is "builtins.str"
Revealed type is "builtins.str"
Revealed type is "test_generic.A[Any]"

Your Environment

  • Mypy version used: 1.14.1
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.12.8

Motivation

This becomes relevant when trying to match on a union of generic types, as it creates an unreachable error.

e.g.

type Union_AB[T] = A[T] | B[T]

def func(val: Union_AB[int]) -> None:
    match val:
        case A(x):
            pass
        case B(x):  #  error: Subclass of "A[int]" and "B[Any]" cannot exist: would have incompatible method signatures  [unreachable]
            pass

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 provided generic match reproducer with mypy 1.14.1 and compare the revealed types with the expected output. Trace mypy's pattern-matching inference for the captured a_match value, then add regression coverage for generic class patterns and confirm the union example no longer reports the incorrect unreachable error.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.