Python set variable with match

Setting a variable with a match can be done simply like this:

Mode = 'fast'
puts = ''
match Mode:
    case "slow":
        puts = 'v2 k5'
    case "balanced":
        puts = 'v3 k5'
    case "fast":
        puts = 'v3 k7'

But can you do something like this?

Mode = 'fast'
puts = match Mode:
    case "slow": 'v2 k5'
    case "balanced": 'v3 k5'
    case "fast": 'v3 k7'

>Solution :

Not as far as I know in python. In this case I wouldn’t use pattern matching at all:

puts = {
    "slow": "v2 k5",
    "balanced": "v3 k5",
    "fast": "v3 k7"
}.get(Mode, default)

Clearer, more declarative, and no repeating yourself. But of course you can’t use clever pattern destructuring.

Leave a Reply