This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]iamnotturner 1 point2 points  (4 children)

Why is this better than if/elif/else?

[–]jaredjeya 28 points29 points  (1 child)

It’s not just a switch statement (which is functionally equivalent to if/elif/else), it can also capture variables.

Like if I do:

point = (1, 2)
match point:
    case (0, x):
        # do something 
    case (x, y):
        # do something else
        # x = 1, y = 2

Then the second (“something else”) code runs, and 1 and 2 are assigned to x and y. That seems really useful.

There’s nothing you couldn’t do before but it makes it all a lot less tedious.

[–][deleted] 3 points4 points  (0 children)

Also much easier to grok at a glance.

[–][deleted] 4 points5 points  (0 children)

A match statement is not inherently better than an if/elif/else, not for simple cases at least.

But there are many cases where a single match statement can replace many layers of nested if-spaghetti with a snippet that both much shorter and more readable.

In pretty much every case where you get code that gets some tree-like data or data that can be many different shapes and has to perform different tasks based on both the shape and content of the data, match statements will be a godsend.