Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the matched value in the default case of structural pattern matching?

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?
        )
like image 519
ideasman42 Avatar asked Oct 16 '25 21:10

ideasman42


1 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}")

Or, the variable name can be assigned directly:

match expensive_calculation(argument):
  case 'APPLE':
    value = 'FOO'
  case 'ORANGE':
    value = 'BAR'
  # Assign the default value to `argument_calc`.
  case argument_calc:
    raise Exception(f"Wrong kind of fruit found: {argument_calc!r}")
like image 116
Ajax1234 Avatar answered Oct 19 '25 11:10

Ajax1234



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!