gustafbstrom
gustafbstrom

Reputation: 1933

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

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')

Upvotes: 52

Views: 19536

Answers (4)

Neal
Neal

Reputation: 1

Seems like the answer is to use elif here.

Obvious case (no pun intended) for allowing a simple boolean expression here. It maybe not what it was intended for but it's an obvious use case. For example VBA does it well and I used the case construct there rather than if all the time because of it.

Upvotes: -2

Thomas Sollie
Thomas Sollie

Reputation: 85

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 clause (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")

Upvotes: 6

wjandrea
wjandrea

Reputation: 32987

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.

Speaking of code style, avoid magic numbers: If all three 42's in your code represent the same thing, give it a name, for example:

the_answer = 42
if a < the_answer:
...

Upvotes: 12

Ajax1234
Ajax1234

Reputation: 71451

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')

Upvotes: 71

Related Questions