Охранные условия в match

Поток управления / Условные операторы / Оператор match

class Tiger:
    def __init__(self, age):
        self.age = age


def describe(obj):
    match obj:
        case int(i) if i > 1_000_000:
            return "Big number"
        case str(s) if len(s) < 256:
            return "Short string"
        case Tiger(age=age) if age > 12:
            return "Old tiger"
        case _:
            return "Unknown type"


result = describe(Tiger(15))
# result is 'Old tiger'

# The guard fails: the next case is tried
young = describe(Tiger(5))
# young is 'Unknown type'

print(f"{result = }")
print(f"{young = }")