Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match multiple different cases in Python

Using the match statement, one can specify multiple patterns for the same case\

match value:
   case 1 | 2 | 3:
     do_a()
   case 4:
     do(b)

What I want to do is the inverse, I want to match multiple cases, each of which executes a different code, with a single value - my idea was something like this

match value:
   case 1 | 2 | 3 | 'all':
     do_a()
   case 4 | 'all':
     do(b)
   case 'all':
     do(c)

I want to run both do_a(), do_b() and do_c() if value=='all'. This can be easily done with if-else, but I wanted to make use of the more elegant match statement. In other languages with switch, like Java or C, I could abuse the need for explicit break and let the subsequent cases be executed after the first match.

Is there a mechanism for this use-case in either fashion (executing multiple blocks with matching the same value or 'falling through' the statement) in python, or do I have to settle down for simple conditions?

Currently the working version is with simple if conditions, I've tried the naive approach described in the problem, but only the first match block executes.

like image 252
Tomáš Kořistka Avatar asked May 28 '26 14:05

Tomáš Kořistka


1 Answers

I believe the best you can do is:

match value:
   case 'all':
     do_a()
     do(b)
     do(c)
   case 1 | 2 | 3:
     do_a()
   case 4:
     do(b)

Note the order.

like image 179
Yevhen Kuzmovych Avatar answered May 31 '26 05:05

Yevhen Kuzmovych