How to access the matched value in the default case of structural pattern matching?
Question:
With Python 3.10’s match statement, is it possible to use the value met in the default case?
Or does this need to be assigned a variable before match
so it can be used in the default case?
match expensive_calculation(argument):
case 'APPLE':
value = 'FOO'
case 'ORANGE':
value = 'BAR'
case _:
raise Exception(
"Wrong kind of fruit found: " +
str(expensive_calculation(argument))
# ^ is it possible to get the default value in this case?
)
Answers:
You can use an as
pattern:
match expensive_calculation(argument):
case 'APPLE':
value = 'FOO'
case 'ORANGE':
value = 'BAR'
# Using `as` to assign the wildcard default to `argument_calc`.
case _ as argument_calc:
raise Exception(f"Wrong kind of fruit found: {argument_calc!r}")
With Python 3.10’s match statement, is it possible to use the value met in the default case?
Or does this need to be assigned a variable before match
so it can be used in the default case?
match expensive_calculation(argument):
case 'APPLE':
value = 'FOO'
case 'ORANGE':
value = 'BAR'
case _:
raise Exception(
"Wrong kind of fruit found: " +
str(expensive_calculation(argument))
# ^ is it possible to get the default value in this case?
)
You can use an as
pattern:
match expensive_calculation(argument):
case 'APPLE':
value = 'FOO'
case 'ORANGE':
value = 'BAR'
# Using `as` to assign the wildcard default to `argument_calc`.
case _ as argument_calc:
raise Exception(f"Wrong kind of fruit found: {argument_calc!r}")