Skip to main content
A class pattern is a structural pattern matching construct in Python (introduced in Python 3.10) used within match/case statements to verify an object’s type and deconstruct its attributes. It evaluates to True if the subject is an instance of the specified class and all nested sub-patterns successfully match or bind to the object’s attributes.

Technical Mechanics

The matching engine processes a class pattern in three distinct phases:
  1. Type Verification: The engine performs an implicit isinstance(subject, ClassName) check. If this evaluates to False, the pattern fails immediately.
  2. Positional Argument Matching: If positional sub-patterns are provided, the engine maps them to the subject’s attributes using the __match_args__ class attribute.
  3. Keyword Argument Matching: If keyword sub-patterns are provided, the engine extracts the attribute by name using getattr(subject, "keyword_attribute") and matches it against the provided sub-pattern.

Keyword Matching

Keyword patterns extract attributes by name. The pattern succeeds only if the attribute exists and matches the specified sub-pattern (which can be a literal, a variable binding, or another nested pattern).

Positional Matching and __match_args__

To use positional arguments in a class pattern, the target class must define the __match_args__ special attribute. This attribute is a tuple of strings dictating the order in which positional patterns map to class attributes. If __match_args__ is not defined, attempting to use positional patterns will raise a TypeError.
Note: Python’s @dataclass and collections.namedtuple automatically generate the __match_args__ attribute based on their field definitions.

Built-in Type Exceptions

Eleven built-in types exhibit specialized behavior in class patterns: bool, bytearray, bytes, dict, float, frozenset, int, list, set, str, and tuple. When matching against these types, a single positional argument does not look for an attribute via __match_args__. Instead, it matches the sub-pattern against the entire subject itself.

Nested Deconstruction

Class patterns can be arbitrarily nested, allowing the matching engine to traverse deep object graphs in a single declarative statement.
Tired of Poor Python Skills? Fix That With Deep Grasping!Learn More