Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading