I have a match case that I want to execute even if a previous statement already matched.
Here's what I currently have:
key: Literal['all', 'a', 'b'] = 'a'
def do_a():
pass
def do_b():
pass
match key:
case 'a':
do_a()
case 'b':
do_b()
case 'all':
do_a()
do_b()
Is there any way to simplify the code so I can remove the case 'all'
?
Something like
match key:
case 'a' | 'all':
do_a()
case 'b' | 'all':
do_b()
Example Setup:
from typing import Literal
key: Literal['all', 'a', 'b']
def do_a():
print('do_a')
def do_b():
print('do_b')
Solution I: You can just use if
:
if key in ('a', 'all'):
do_a()
if key in ('b', 'all'):
do_b()
Solution II: You could use a function mapper, like so:
function_mapper = {
'all': (do_a, do_b),
'a': (do_a,),
'b': (do_a,),
}
key = 'all'
for func in function_mapper[key]:
func()