Files
ruff/crates/ty_python_semantic/resources/lint_docs/invalid-match-pattern.md
Felix ScherzandCharlie Marsh 1d2041ca19 [ty] Validate positional class patterns against __match_args__ (#26195)
## Summary

Positional class patterns use `__match_args__` to map each subpattern to
an attribute. We previously only diagnosed positional subpatterns for
`collections.abc.Callable`; ordinary classes could supply too many
positional subpatterns, omit `__match_args__`, or expose a definitely
non-tuple value without an `invalid-match-pattern` diagnostic.

This PR derives positional limits from the semantic `__match_args__`
member type. Exact fixed-length tuples provide their length, absent
source-class members accept zero positional subpatterns, and Python's
match-self builtins accept one. Definitely non-tuple member types
produce a dedicated diagnostic instead of being interpreted as an arity.
Fixed tuple information is preserved through variables, typed function
calls, explicit annotations, PEP 695 aliases, inheritance, descriptors,
dataclasses, and named tuples.

```python
class Point:
    __match_args__ = ("x", "y")

class Missing: ...

class Invalid:
    __match_args__ = ["x"]

def describe(point: Point, missing: Missing, invalid: Invalid) -> None:
    match point:
        case Point(_, _, _):  # error: expected 2, got 3
            pass

    match missing:
        case Missing(_):  # error: expected 0, got 1
            pass

    match invalid:
        case Invalid(_):  # error: __match_args__ must be an exact tuple
            pass
```

Closes https://github.com/astral-sh/ty/issues/3738.

---------

Co-authored-by: Charlie Marsh <charlie.r.marsh@gmail.com>
2026-06-26 16:09:38 -04:00

919 B

What it does

Checks for invalid match patterns.

Why is this bad?

Invalid match patterns can cause a TypeError at runtime. This includes:

  • Using a non-type object in a class pattern.
  • Providing positional subpatterns when __match_args__ is missing or has an invalid static type.
  • Matching against collections.abc.Callable with positional subpatterns.
  • Matching against a non-runtime-checkable protocol.
  • Matching against a TypedDict.

Examples

class Point:
    __match_args__ = ("x", "y")


def describe(p: Point) -> None:
    match p:
        # TypeError at runtime: Point() accepts 2 positional sub-patterns (3 given)
        case Point(x, y, z):  # error: [invalid-match-pattern]
            ...
NotAClass = 42

match object():
    # TypeError at runtime: called match pattern must be a class
    case NotAClass():  # error: [invalid-match-pattern]
        ...