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')
Python 3.10 was released in mid-2021 and comes with structural pattern matching, also known as a match case statement. This is Python 3.10's most important new feature; the new functionality allows you to more easily control the flow of your programs by executing certain parts of code if conditions (or cases) are met.
Method : Using join regex + loop + re.match() In this, we create a new regex string by joining all the regex list and then match the string against it to check for match using match() with any of the element of regex list.
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')
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With