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

Viewed 1885

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