0Pricing
Python Academy · Lesson

Class Patterns

Match against object attributes.

Matching Objects

Class patterns let match check the type of an object and pull out its attributes in one step. They look like a constructor call inside a case.

Type-Only Check

A class pattern with empty parentheses matches any instance of that class.

def kind(value):
    match value:
        case int():
            return 'an integer'
        case str():
            return 'a string'
        case _:
            return 'something else'

print(kind(5))
print(kind('hi'))
print(kind([1]))

All lessons in this course

  1. match and case Basics
  2. Matching Sequences and Mappings
  3. Class Patterns
  4. Guards and Wildcards
← Back to Python Academy