Skip to content

Match statement parameter binding fails for subclass of generic class #19442

@xeniarose

Description

@xeniarose

Bug Report

When type checking the binding parameters of a match case expression, the binding completely fails if the class has a generic superclass and the match is located in a generic function, though the binding succeeds if the enclosing function is not generic.

To Reproduce

from typing import Any


class MyBase[T]:
    pass

class MyData(MyBase[int]):
    __match_args__ = ("a", "b")
    def __init__(self, a: str, b: bool) -> None:
        self.a = a
        self.b = b

def handle_mydata_ok(val: MyBase[Any]) -> None:
    match val:
        case MyData(_a, _b):
            pass

def handle_mydata_not_ok[T](val: MyBase[T]) -> None:
    match val:
        case MyData(_a, _b):
            pass

https://mypy-play.net/?mypy=latest&python=3.12&gist=d8b1f6586d82fab7ead1a3d76a9962cf

Expected Behavior

mypy should report no type errors for both handle_mydata_ok and handle_mydata_not_ok

Actual Behavior

main.py:20: error: Class "__main__.MyData" has no attribute "a"  [misc]
main.py:20: error: Class "__main__.MyData" has no attribute "b"  [misc]
Found 2 errors in 1 file (checked 1 source file)

Your Environment

Check the mypy-play link for the reproduction.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-match-statementPython 3.10's match statementtopic-runtime-semanticsmypy doesn't model runtime semantics correctlytopic-type-narrowingConditional type narrowing / binder

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions