Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
like image 282
gustafbstrom Avatar asked Oct 25 '21 14:10

gustafbstrom


People also ask

Does Python have match case?

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.

How do you match a pattern to a list in Python?

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.


Video Answer


2 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')
like image 67
Ajax1234 Avatar answered Oct 27 '22 11:10

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")
like image 2
Thomas Sollie Avatar answered Oct 27 '22 13:10

Thomas Sollie