Python 3.10 match case with arbitrary conditions
Question:
Is there any way to use arbitrary conditions on cases in a Python 3.10+ match statement or is it necessary to fall back on if-then control structures?
Clarification: an arbitrary condition might be a function with myVariable
as argument that evaluates to type bool.
The constraint here is to keep the order of the cases (since the first few cases appear extremely often and performance is essential).
match myVariable:
case 'a': ...
case someConditionOnMyVariable: ...
case someOtherConditionOnMyVariable: ...
case 'bb': ...
case _: ...
Answers:
If you mean the match
statement, you could probably use a wildcard pattern with a guard for your arbitrary condition:
def check(x):
return len(x) % 3 == 0
def test(my_var):
match my_var:
case 'a':
print("aa!")
case _ if check(my_var):
print("yup!")
case _:
print("no match")
test("a")
test("bbb")
test("blop")
prints out
aa!
yup!
no match
Is there any way to use arbitrary conditions on cases in a Python 3.10+ match statement or is it necessary to fall back on if-then control structures?
Clarification: an arbitrary condition might be a function with myVariable
as argument that evaluates to type bool.
The constraint here is to keep the order of the cases (since the first few cases appear extremely often and performance is essential).
match myVariable:
case 'a': ...
case someConditionOnMyVariable: ...
case someOtherConditionOnMyVariable: ...
case 'bb': ...
case _: ...
If you mean the match
statement, you could probably use a wildcard pattern with a guard for your arbitrary condition:
def check(x):
return len(x) % 3 == 0
def test(my_var):
match my_var:
case 'a':
print("aa!")
case _ if check(my_var):
print("yup!")
case _:
print("no match")
test("a")
test("bbb")
test("blop")
prints out
aa!
yup!
no match