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?
)
Advertisement
Answer
You can use an as pattern:
match expensive_calculation(argument):
case 'APPLE':
value = 'FOO'
case 'ORANGE':
value = 'BAR'
case _ as argument: #here, using `as` to save the wildcard default to `argument`
raise Exception(f"Wrong kind of fruit found: {str(argument)}")