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?
JavaScript
x
12
12
1
match expensive_calculation(argument):
2
case 'APPLE':
3
value = 'FOO'
4
case 'ORANGE':
5
value = 'BAR'
6
case _:
7
raise Exception(
8
"Wrong kind of fruit found: " +
9
str(expensive_calculation(argument))
10
# ^ is it possible to get the default value in this case?
11
)
12
Advertisement
Answer
You can use an as
pattern:
JavaScript
1
8
1
match expensive_calculation(argument):
2
case 'APPLE':
3
value = 'FOO'
4
case 'ORANGE':
5
value = 'BAR'
6
case _ as argument: #here, using `as` to save the wildcard default to `argument`
7
raise Exception(f"Wrong kind of fruit found: {str(argument)}")
8