Is there a way to match inequalities in Python ≥ 3.10?

Question:

The new structural pattern matching feature in Python 3.10 is a very welcome feature. Is there a way to match inequalities using this statement? Prototype example:

match a:
    case < 42:
        print('Less')
    case == 42:
        print('The answer')
    case > 42:
        print('Greater')
Asked By: gustafbstrom

||

Answers:

You can use guards:

match a:
    case _ if a < 42:
        print('Less')
    case _ if a == 42:
        print('The answer')
    case _ if a > 42:
        print('Greater')

Another option, without guards, using pure pattern matching:

match [a < 42, a == 42]:
    case [True, False]:
        print('Less')
    case [_, True]:
        print('The answer')
    case [False, False]:
        print('Greater')
Answered By: Ajax1234

A match-case statement inherently is designed for matching equalities (hence the word "match"). In your prototype example you could achieve this by matching with an if statement (as proposed by other answers), however now you are in essence simply matching True and False, which seems redundant.

One way other languages solve this is via comparisons using Enums:

from enum import Enum


class Ordering(Enum):
    LESS = 1
    EQUAL = 2
    GREATER = 3


def compare(a, b):
    if a < b:
        return Ordering.LESS
    elif a == b:
        return Ordering.EQUAL
    elif a > b:
        return Ordering.GREATER


match compare(a, 42):
    case Ordering.LESS:
        print("Less")
    case Ordering.EQUAL:
        print("The answer")
    case Ordering.GREATER:
        print("Greater")
Answered By: Thomas Sollie

In this example, it’s simpler to use good ol’ if-elif, even if it means repeating the variable name.

if a < 42:
    print('Less')
elif a == 42:
    print('The answer')
elif a > 42:
    print('Greater')

P.S. Using an enum and comparison function like in Thomas Sollie’s answer is good for adding more structure to your program, but it seems like overkill for basic scripts and such.

Answered By: wjandrea