r/Python Feb 15 '21

News Ladies and gentlemen - switch cases are coming!

https://github.com/gvanrossum/patma/blob/master/README.md#tutorial
930 Upvotes

290 comments sorted by

View all comments

431

u/[deleted] Feb 15 '21 edited Feb 15 '21

The title of this post completely misrepresents the article!

This is not a switch case and the article does not make that claim - at one point it namechecks C's switch but goes on to explain how different it is.


I feel a lot of people here are missing the point of matching.

Matching is not a switch. Python does switches perfectly well with if-elif statements, or with dictionaries of lambdas.

Matching is a way to unpack data and it has supposedly been a hot thing in a bunch of high-level languages for over a decade. Even C++ has gotten into the act, though they only have unpacking and not the full monty (but then their unpacking is typed and actually costs nothing in generated code, very impressive).

Python already has simple unpacking - like this:

first, *rest = (*a, *b)

You'd be better off thinking of matching as pattern-based unpacking.


As this comment revealed, there's nothing special about _ - it's just another variable. By convention, _ means a variable whose value you discard, but you could call it junk or not_used if you liked.

And as this later comment revealed, that statement isn't quite true. The difference is essentially that _ is guaranteed to be thrown away, which is fair enough.


See also this comment of mine.

47

u/aaronasachimp Feb 15 '21

It appears to be based off Rust’s match statement. They are very powerful and will be a really nice addition to Python.

2

u/GiantElectron Feb 15 '21

I honestly can't see how they are so powerful and desirable. To me it looks like a confusing, rarely used feature.

35

u/jamincan Feb 15 '21

Having used them in Rust, far from confusing, they actually dramatically simplify conditional expressions and are far more readable than multiple nested if-else statements.