Back to Intellij Community

Too many positional patterns

python/python-psi-impl/resources/inspectionDescriptions/PyPatternInspection.html

2025.3-rc-21.3 KB
Original Source

Reports incorrect or ambiguous use of structural pattern matching in Python class patterns and __match_args__ definitions.

This inspection helps you catch issues such as:

  • Using positional patterns for a class that does not define __match_args__.
  • Providing more positional patterns than the class exposes via __match_args__.
  • Specifying the same attribute both positionally and by keyword in a single class pattern.
  • Defining __match_args__ with invalid type (must be tuple[str, ...]).

For certain simple as-patterns with built-in classes, it also suggests a quick fix to simplify the pattern.

# Too many positional patterns
match p:
    case Point(x, y, z): # expected only 2 according to __match_args__
        ...

# Positional + keyword conflict
match p:
    case Point(x, y, x=0): # 'x' is already specified positionally
        ...

# Class without __match_args__ but used with positional patterns
class C:
    def __init__ (self, a, b):
        self.a = a; self.b = b

match obj:
    case C(1, 2): # C does not support positional patterns
        ...

# Invalid __match_args__ declaration
class D:
    __match_args__ = ["a", 42] # must be tuple[str, ...]

The inspection provides quick fixes where possible, for example to add __match_args__, remove redundant patterns, or simplify certain as-patterns involving built-in classes.