Content · Programming · Python

Python Class Patterns and Attribute Matching

Use class patterns to match an object type and selected attributes.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Use class patterns to match an object type and selected attributes.

What You Will Learn


Class patterns like Point(x=0, y=value) test whether the subject is an instance of Point and whether named attributes match. Positional class patterns depend on __match_args__, which dataclasses generate for ordinary init fields; keyword patterns are often clearer. Matching an attribute does not guarantee any application-level validation.

Step-by-Step Example


The example below makes the behavior visible with small input values that you can change safely.

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

def describe(point):
    match point:
        case Point(x=0, y=value):
            return f"On the vertical axis at {value}"
        case Point(x=x, y=y):
            return f"Point at {x}, {y}"

print(describe(Point(0, 7)))
print(describe(Point(2, 3)))

How the Example Works


  • The imports provide the standard-library tools used in the demonstration: dataclasses.
  • The definitions Point, describe separate the main steps into named components; calls to those components drive the example.
  • The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.

Expected output from the example:

On the vertical axis at 7
Point at 2, 3

When You Would Use This


Pattern matching can simplify dispatching application commands or decoding structured messages from a trusted parser. It chooses a branch based on shape and selected values, but application-level validation is still necessary. Compare it with an if/elif chain if the problem only involves simple Boolean expressions.

Practice: Modify the Code


Add a case for points on the horizontal axis and compare pattern order.

Verify the changed output against the behavior described above, including the relevant invalid or boundary case.

For complete parameters and version details, consult the official Python documentation.

Common Beginner Mistakes


  • Writing case Point() as if it automatically tests all field values.
  • Assuming positional class patterns are supported without considering __match_args__.

Key Takeaways


  • Use class patterns to match an object type and selected attributes.
  • Class patterns like Point(x=0, y=value) test whether the subject is an instance of Point and whether named attributes match.
  • Apply this operation only after checking the assumptions and input conditions shown in the example.
Share this resourceSend this page to someone who may find it useful.