When thinking about adding case NAMES from EXPR
, this strikes me as adding the match statement to the match statement, if that makes sense?
The issue with the original example’s suggestion is there is way too much variability in the case handling. Implementing the desired behaviour with an if...elif...
ladder and regular expressions is pretty clear and straightforward:
import re
def test(text):
if m := re.fullmatch("prefix_(.*?)", text):
cmd, = m.groups()
print("got", cmd)
elif m := re.fullmatch("Hello (.*?), (.*?)!", text):
last_name, first_name = m.groups()
print(last_name, first_name)
else:
print(f"Don't know what to do with {text}")
test("prefix_Order66")
test("Hello Phol, Tom!")
test("foo bar")
Unlike a match
statement, this will blow up if passed a non-string, like test(100)
.
Otherwise, this looks kinda like a match statement, if f"{var}"
in a case
was matched by (.*?)
.
def test(text):
match text:
case f"prefix_{cmd}":
print("got", cmd)
case f"Hello {last_name}, {first_name}!":
print(last_name, first_name)
case _:
print(f"Don't know what to do with {text}")
Except … interpolation of f"prefix_{cmd}"
doesn’t require cmd
to be an string; it could be a integer!
match text:
case f"prefix_{cmd:d}":
print("Integer command", cmd):
case f"prefix_{cmd:f}":
print("Fractional command", cmd)
case f"prefix_{cmd}":
print("Vanilla string command", cmd)
But this open a whole new can of worms, which we probably don’t want to head down. For example, could prefix_(1+1j)
be matched by case f"prefix_{cmd!r}"
and assign cmd = 1 + 1j
???