r/Python • • Mar 19 '21

Match is more than a Switch-Case The New Switch-Case Statement in Python 3.10

https://youtube.com/watch?v=2qJavL-VX9Y&feature=share
1.4k Upvotes

233 comments sorted by

380

u/MeDotPy Mar 19 '21

Finally

234

u/[deleted] Mar 19 '21

Continue

28

u/N3RO- Mar 19 '21

pun intended?

254

u/seniornachio timfi Mar 19 '21

Calling it a Switch-Case Statement simply does not do it justice imho. It's a Match Statement that can do a lot more than just Switch-Case...

Haven't watched the Video yet, just talking about the Posts title.

44

u/[deleted] Mar 19 '21

They should have made it an expression not a statement

28

u/seniornachio timfi Mar 19 '21

My thoughts exactly. Additionally I would have enjoyed PEP-642, it's more verbose but explicit is better than implicit and additionally it makes it more clear that python is duck-typed.

11

u/[deleted] Mar 19 '21

explicit is better than implicit

Java flashbacks

28

u/[deleted] Mar 20 '21

Explicit doesn't mean endless repetition and needles ceremony, though.

16

u/toyg Mar 20 '21

A single letter separates boring ceremonies that nobody really needs, from images of sinister ceremonies involving needles. The marvels of language...

3

u/[deleted] Mar 20 '21

Lol that stays in!

2

u/grrrrreat Mar 20 '21

summoning malloc the devil of details and harbinger of nulls

1

u/Plane_brane Mar 20 '21

Huh?

6

u/W_Hardcore Mar 20 '21

Needless needles

2

u/Plane_brane Mar 20 '21

Lol didn't catch that

0

u/[deleted] Mar 19 '21

[deleted]

16

u/steven_h Mar 19 '21

It was written by a major contributor from back in the 0.9.x days but you do you.

-1

u/nerdzrool Mar 19 '21

Just because it was written by a major contributor to Python doesn't mean it isn't BS platitude and never really applied to Python, or its ecosystem/community.

Beautiful is better than ugly. - No shit. Platitude. Simple is better than complex. - No shit. Platitude. Readability counts. - No shit. Platitude. etc.

And, as was mentioned, it never really was used by Python as language, or its ecosystem or even its community to a large degree. Django, one of the main Python libraries, was popularized because it uses convention over configuration, directly opposing the Zen of Python's "Explicit is better than implicit." The Zen of Python says namespaces are great, but python's namespace tooling is inferior to some other languages that have explicit namespacing keywords, rather than implicitly deciding namespaces based on only on where and when a python file is executed (A topic where Python violates 2 Zen of Python rules) or how many times you pounded the spacebar prior to writing code. There is definitely not "one, and preferably only one, obvious way to do" a lot of things in Python considering how long Python used to have xrange and range and 95% of the time the correct answer was always "use xrange", the not obvious one. And yes, I asked a Dutch person which one they would think is the obvious correct answer, and they thought it would have been range too.

I agree with most of the Zen of Python, for the most part, but that doesn't change the fact that it hasn't been applied throughout most of Python's life, and some of the statements in it should be obvious to anyone.

8

u/steven_h Mar 20 '21

The particular selection of “platitudes” is important. Some potential “platitudes” that didn’t make it into this list:

  • Correct is better than concise.

  • Interoperability is key.

  • Concurrency everywhere.

  • Don’t write programs. Write programs that write programs.

  • Everything is an object.

  • Type checking is a really great honkin idea — let’s do more of it!

1

u/[deleted] Mar 20 '21

The platitudes that you see as obvious are eye openers for people just discovering python (and often, programming in general).

7

u/SuspiciousScript Mar 19 '21

This strikes me as a really unforced error. Hell, the trend is toward even if constructs being expressions; why kneecap match like this when making it an expression seems so obvious?

-1

u/[deleted] Mar 19 '21

Because you like ceremonies?

5

u/FewerPunishment Mar 20 '21

What would the difference look like in terms of syntax/features?

2

u/[deleted] Mar 20 '21

1

u/FewerPunishment Mar 20 '21

I mean more in terms of this matching functionality, like an example of something you wish you could execute. But thanks for the reference, I should study these terms.

7

u/[deleted] Mar 20 '21

Making it an expression wouldn't have any impact on pattern matching functionality, it would improve flexibility.

If match was an expression you could do this:

a = match ...

instead of


match something:
       case 1: 
               a = ...

2

u/hughperman Mar 20 '21

That seems to skew the use case to assignments only though, whereas switch and match statements are (ime) more useful as control flow - which may include assignments inside them, but not as their primary goal. It seems to me that it would be like wanting try/except/finally to return a value.

2

u/[deleted] Mar 20 '21

1

u/hughperman Mar 20 '21

Right but python isn't a functional language in that sense, that's why I compared to try/except/finally. You can just wrap the control statement in a function if you wish to go that way, like any other statement in python. I agree if you are implementing a functional language that you would return - but then everything should match (😉) that same paradigm.

1

u/[deleted] Mar 20 '21

Look at Kotlin

1

u/[deleted] Mar 20 '21

Wouldn't you be able to do both if it was an expression?

1

u/backtickbot Mar 20 '21

Fixed formatting.

Hello, Iuse_arch_btw: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.

3

u/[deleted] Mar 20 '21

it's Reddit's job to fix it

1

u/[deleted] Mar 20 '21

backtickopt6

5

u/thekingofthejungle Mar 20 '21

What's the difference?

10

u/seniornachio timfi Mar 20 '21

Matching, or rather pattern matching, allows you to match patterns. A switch-case is just the simplest form of that where you only match using literal patterns, like in the thumbnail of the video. But you can take this further and for example say you want to match all tuple with two element or a list with at least three elements or even an object with an attribute or an object of a specific type and so on. I highly encourage you to read the associated PEP, it's a good read, even if I personally don't enjoy the selected syntax choices, it brings the point across with a lot of examples.

2

u/VideoCarp1 Mar 20 '21

AFAIK it’s pattern matching?

1

u/GoofAckYoorsElf Mar 20 '21

This should be the top comment

1

u/batisteo Mar 25 '21

I wonder if it’s inspired by Rust

0

u/lockieluke3389 Mar 20 '21

What’s the difference

1

u/seniornachio timfi Mar 20 '21

tl;dr... read some of the answers to this question either in siblings to your comment or some siblings to my comment. I've seen alot of them up until now. ;)

79

u/Jyan Mar 19 '21 edited Mar 19 '21

Read the PEP: https://www.python.org/dev/peps/pep-0634/ It is so much more than a fancy if-else.

21

u/zurtex Mar 19 '21

FYI I know it mentions it in the PEP but to be explicit about it PEP 622 was Superseded by PEP 634: https://www.python.org/dev/peps/pep-0634/

There are a lot of changes between the 2 PEPs, in particular they removed "The Match Protocol" in favor of letting match bake in to Python for a bit and adding at a later date when there are concrete examples and motivation to allow classes to implement their own custom match logic.

2

u/Jyan Mar 19 '21

Thanks

15

u/[deleted] Mar 19 '21

The feature isn't even out yet and it's being molested, misrepresented and missold already.

10

u/Tyler_Zoro Mar 19 '21

People are coming from lower level languages where you can only do a fraction of what this can do with similarly named language features. It's not shocking that the presumption is that it only does those things. I'm of the opinion that it should have had a name that wouldn't lead people to assume it was similar to those features, but then what do you call it?

When Perl 6 (now Raku) did something similar, they called it given/when for exactly that reason. Maybe following suit would have been a better call...

15

u/[deleted] Mar 19 '21

Is that not why they called it "match" rather than "switch"?

3

u/Tyler_Zoro Mar 19 '21

Yes, but then they fell down on "case".

3

u/[deleted] Mar 19 '21

Yeah, good point.

2

u/mihalis Mar 20 '21

Agree. I thought about alternatives. Maybe bind or unify, along the lines of variable unification/binding in languages like Prolog.

3

u/[deleted] Mar 20 '21

Or how about match x where x is y?

-2

u/13steinj Mar 19 '21

Because it's not a switch statement, it's a pattern matching statement. Most commonly seen only in functional programming languages, which most people hate on because traditionally such a style is considered difficult.

https://en.wikipedia.org/wiki/Pattern_matching

https://stackoverflow.com/a/215968/4443677

→ More replies (1)

3

u/13steinj Mar 19 '21

Yeah, because pattern matching isn't common in most languages for people less experienced. You usually see pattern matching in functional languages which many people just hate and think that functional programming should die in a fire.

32

u/awesomeprogramer Mar 19 '21

ITS NOT A SWITCH CASE

0

u/[deleted] Mar 19 '21

[deleted]

20

u/awesomeprogramer Mar 19 '21

Because, "hEy LoOk PyThON hAs A sWiTcH CaSe nOw"

85

u/Laser_Plasma Mar 19 '21

Except it's not a switch, it can do more, hence - match

10

u/SidoNotYetMaster Mar 19 '21

dope; like in caml or haskell :)

37

u/[deleted] Mar 19 '21

Why are you comparing a match statement with a switch statement?

25

u/Tyler_Zoro Mar 19 '21

Because the article doesn't explain the difference, most likely... why don't you explain the difference rather than acting as if everyone should already know how a feature that was literally released today works?

8

u/[deleted] Mar 19 '21

You’re right about that, the article gets the heading wrong for starters. I meant is to point out that one is literally called “match” and not “switch”, and different things and pattern matching exists in other languages already. You could use match and pattern matching for switch case but it’s semantically not ==. I get with your point (other comment) that if a good old switch as we know behaves differently it could throw some folks off, that is true. For example in python OOP private isn’t really private, but that’s what makes languages special :)

0

u/xigoi Mar 20 '21

a feature that was literally released today works?

It's not like there are hundreds of languages with pattern matching already…

14

u/Humanist_NA Mar 19 '21

Still learning python, quick question. What would be the benefit of this as compared to one of my learning projects right now, where I just have:

if code == 404:
    something()
elif code == 200: 
    thing()
else: 
    pass

is the case matching just less code and cleaner? is it more efficient? am I entirely missing the point? Thanks for any response.

106

u/Yoghurt42 Mar 19 '21

It's more than a switch statement, it's pattern matching, read https://www.python.org/dev/peps/pep-0636/ for a tutorial.

You can do stuff like:

match foo:
    case Person(address=Address(street="barstreet")):
        bar()

and it will be equivalent to something like:

if isinstance(foo, Person) and hasattr(foo, "address") and isinstance(foo.address, Address) and hasattr(foo.address, "street") and foo.address.street == "barstreet":
    bar()

22

u/Etheo Mar 19 '21

That's a good example for someone who hasn't been keeping up with the news, thank you.

8

u/Humanist_NA Mar 19 '21

Thank you, appreciated.

4

u/[deleted] Mar 19 '21

So Python will not actually create a new Person instance?

12

u/Yoghurt42 Mar 19 '21 edited Mar 19 '21

Exactly. It's basically new syntax.

You can also do stuff like

case [1, _, x, Robot(name=y)] if x == y which would match if it is a four-element list that starts with 1, and the 4th element is an instance of Robot class which has a name attribute set to the same value as the third element. The _ is a special new token that means "wildcard/match anything" in this context.

Pattern matching is incredible powerful and the only feature I was really missing from other languages. Now all they need to get rid of the GIL and have decent JIT (or get PyPy to be API compatible with CPython) and it would be the perfect language for every task for me.

3

u/[deleted] Mar 20 '21

Awesome! I can already imagine how this is going to be incredibly useful.

As for the GIL, do you really think they will ever get rid of that?

1

u/azur08 Mar 20 '21

Out of curiosity, do you have an example of a task you'd use another language for if not for the things in your last paragraph? I've heard that modules like concurrent.futures, multiprocessing, asyncio, etc., don't completely remove the limitations but I'm not sure why.

2

u/Irtexx Mar 19 '21

I would also like to know this. The isinstance method never calls init of Person, but the match method looks like it will.

8

u/13steinj Mar 19 '21

match will call the __match__ method, unless the PEP changed since I last looked at it. A new instance will not be created.

2

u/[deleted] Mar 19 '21

It could be possible that it doesn't evaluate as an expression, but that would mean that you couldn't put expressions into the pattern.

1

u/Mini_Hobo Mar 19 '21

No, it doesn't use the class's __init__ or __call__ methods.

4

u/[deleted] Mar 19 '21

Fantastic example. This really does elevate the clarity and eloquence of the language. I feel like this really is going to add so much to Python.

1

u/Irtexx Mar 19 '21

if Person was a dataclass, couldn't you just use:

if foo == Person(address=Address(street="barstreet")):
    bar()

10

u/tongue_depression Mar 19 '21

not if Person or Address have other fields that need initializing

8

u/Yoghurt42 Mar 19 '21 edited Mar 19 '21

If Person has more attributes, like name, the equality check would probably fail, because the name attribute of foo would probably not be None.

Furthermore, it would create a new Person instance each time the if condition is checked.

Pattern matching doesn't require this, and also works for non dataclasses, it also allows insane stuff like

case [1, [2, _, x], y]] if x == 2*y, the _ is a wildcard.

It would be equivalent to if isinstance(foo, list) and len(foo)==3 and isinstance(foo[1], list) and len(foo[1]) == 3 and foo[1][0] == 2 and foo[1][3] == 2*foo[2]

21

u/zurtex Mar 19 '21

The match statement allows much more complex types of matching. For example:

action = {"open": "door"}
match action:
    case {"move": direction}:
        ...
    case {"look": direction}:
        ...
    case {"open": thing}:
        if thing == "door":
            print("The door is locked")
        elif thing == "box":
            print("A monster escaped")
        else:
            print(f"I don't recognize {thing}, try looking around")

For your example of individually handling each value an if/elif/else statement is a great choice.

1

u/Humanist_NA Mar 19 '21

Interesting, thank you for the thoughtful response.

0

u/[deleted] Mar 19 '21

[deleted]

4

u/zurtex Mar 19 '21

In Rust that makes sense, but Python and Rust are 2 very different languages. Python's compiler doesn't make any guarantees about the match statements return values and enums are not common or native to Python (the enum in the standard library is a very complex object when you peer under the hood).

So when you're doing this:

match code:
    case 200:
        something()
    case 404:
        thing()
    case _:
        pass

It really just is a longer backwards incompatible way of writing:

if code == 200:
    something()
elif code == 404: 
    thing()
else:
    pass

Now I am sure there are examples where using the match statement with HTTP status codes makes a lot of sense, but as a simple check of getting 200 or 404 or something else I'm missing the motivation.

1

u/13steinj Mar 19 '21

It really just is a longer backwards incompatible way of writing...

This is what I really hate about the Python ecosystem. Everyone jumps on the new way without thinking of backwards compatibility even though there is little benefit. I really hope static analysis tolls will by default warn against using match in simple cases like this, where it's literally using a backwards incompatible keyword simply for syntactic sugar (no optimization at all, and in fact even in compiled languages there isn't necessarily optimization performed on switches).

7

u/GreatDemonSquid Mar 19 '21

This isn’t just a switch. It can also do pattern matching, basically cases for specific properties (for example lists or instances of classes). Think of it like a switch statement combined with regex for objects

4

u/diamondketo Mar 19 '21

Read the PEP

https://www.python.org/dev/peps/pep-0622/

There's an example where the match is done on a tuple (x,y,z).

4

u/[deleted] Mar 19 '21

I believe it is more efficient (like most other langs where switch-case is efficient) and also can "match" stuff (and not just work like an ordinary switch-case)

11

u/Ecclestoned Mar 19 '21 edited Mar 19 '21

I highly doubt match is more efficient in python. The advantage in other languages is that switch statements can sometimes be reduced to jump tables.

The python interpreter is 100x more high-level than this, and also has to a lot of checks in the match statement that it doesn't need to do in an if.

4

u/Tyler_Zoro Mar 19 '21

It's easier for the parser to identify easily combined options for lookup tables. That doesn't mean that it will do so.

For example, if all of your cases are constant values, you can reduce a match to a lookup table through a dict. If they are all small integer constants, then it can be reduced to a list lookup.

Yes, match can do much, much more, but this makes optimizations much easier to identify.

2

u/Ecclestoned Mar 19 '21

Sure, but I think it's important to differentiate between "easier for the compiler engineers to optimize" and "faster/more efficient" (the actual comment).

This comes down to the CPython implementation, which I haven't looked at. However, the PEP says:

Although this PEP does not specify any particular implementation strategy, a few words about the prototype implementation and how it attempts to maximize performance are in order.

Basically, the prototype implementation transforms all of the match statement syntax into equivalent if/else blocks - or more accurately, into Python byte codes that have the same effect. In other words, all of the logic for testing instance types, sequence lengths, mapping keys and so on are inlined in place of the match.

Which makes me think that the current implementation is literally if statements, so the same speed.

1

u/Brian Mar 20 '21

For example, if all of your cases are constant values, you can reduce a match to a lookup table through a dict.

Not in python you can't. Even if all your cases are constants, you can't really know how your match variable will interact with them, unless it too is a constant (in which case, what's the point of the match?), or you can do sufficient analysis to at least know the type is also an integer.

Eg. there are plenty of objects that you can compare to an int, but not be an int (or convertable to one). And even if it is a subtype of int, its not hard to create an object that would have different behaviour depending on the order of comparisons, meaning any such optimisation is invalid.

The best you could probably do is to have two codepaths - one for ints and one for arbitrary objects, but outside of a JIT, that doesn't seem like a good approach (and if you are writing a JIT doing that level of optimisation, I suspect you'd be able to optimise the if/elif tree similarly anyway).

0

u/[deleted] Mar 19 '21

I’m asking myself the same question

-4

u/Goel40 Mar 19 '21

I don't think there's a big advantage for switch cases in Python. But comming from languages that make heavy use of semicolons it looks way cleaner than if/else statements for those languages. I think thats the main reason they implemented it. People comming from other languages are used to use switch cases for programs with a lot of logical elements. So mostly old habits i guess.

1

u/Humanist_NA Mar 19 '21

Interesting, thanks.

3

u/[deleted] Mar 20 '21

95% of people in this thread need to Google "pattern matching functional programming". Then you will understand.

4

u/BobFredIII Mar 19 '21

Wow, this feels illegal

4

u/sam-lb Mar 20 '21

Wow. Started reading the PEP, this is incredible. Not a switch statement though mate. It's much better than that.

2

u/spiker611 Mar 20 '21

Does anyone know what adding type hints to these statement will look like?

2

u/azur08 Mar 20 '21

Holy shit. I just started learning Rust for <reasons> and came across match statements today and was like, "man, I want that."

I find out today it's now going to be in Python!

2

u/[deleted] Mar 20 '21

It's been too long.

4

u/[deleted] Mar 19 '21

Why do you call it a switch statement, when it is called a match? Where did you find the word 'switch' in this statement?

3

u/[deleted] Mar 19 '21

Just learned the wonders of pattern matching in Scala. This makes me so happy.

0

u/Phunny Mar 19 '21

Great video!

1

u/0ajs0jas Mar 19 '21

I'm sorry, I could not find python 3.10. Where is it?

3

u/[deleted] Mar 19 '21

Release candidate right now. I've always compiled RCs from source cause I'm a dork so I'm not sure if they provide installers for them.

3

u/mouth_with_a_merc Mar 19 '21

pyenv is your friend for that - both for rcs and stable versions (distro packages are usually outdated).

Also, 3.10 is alpha, not beta or even rc.

2

u/[deleted] Mar 19 '21

Interesting, wasn't aware of such a tool. That'll come in handy

3

u/nim65s Mar 19 '21

you can:

1

u/mr_whoisGAMER Mar 20 '21

Finally 😎

1

u/SkylitYT Mar 20 '21

Wutttt! no way

1

u/itsthooor Mar 20 '21

I‘m lovin‘ it. Can’t wait to use it and make my code cleaner.

1

u/haloweenek Mar 20 '21

Ohhhh yesss.

1

u/kopsutin Mar 20 '21

I just use dictionary as a switch.

1

u/Sanic1984 Mar 20 '21

The greatest moment on history

1

u/AleTons Mar 20 '21

Sorry guys I’m a newbie with this language, and I don’t get the difference between this and the If Elif Else statements.. wouldn’t be all the same stuff?

1

u/x3x9x Mar 20 '21

Coffe made with a teapot,.. not like this

1

u/Orio_n Mar 20 '21

Can someone explain to me why switch statements are necessary when we already have if-else especially for a language like python

1

u/pitiliwinki Mar 20 '21

Aboooout time!!!

1

u/backdoorman9 Mar 20 '21

Yesss! One of the things I preferred about Javascript, now available in Python.

1

u/[deleted] Mar 20 '21

THANK GOD!!!!!!!!!

1

u/CireSnave Mar 21 '21

The video leaves me with more questions than answers about the match/case use. It has the potential of being game changing. I'm looking forward to seeing what I can really do with it once 3.10 is released.

1

u/astroprof1966 Mar 21 '21

This is incredible. It makes code so much better to read. It's come a long way from DECUS DEC PDP-11 Pascal compiler. That was the first time for me using Pascal ( a beautiful language) and eventually Pro T-SQL...

I'm impressed with this addition!!!!

Tony

1

u/sherwoodpynes Jul 31 '21

Hmm, interesting new feature. This seems like it can work a lot like the pattern matching in functional programming languages like ML/F#'s function definitions, which could make writing functional code in python quite nice (wrap one of these match statements in a function and voila).

1

u/TheTomer Mar 19 '21

It's crazy that it took this long to add this functionality to Python.

1

u/PhilipJayFry1077 Mar 19 '21

This looks great.

1

u/hidegitsu Mar 19 '21

Lol I literally was just bitching about not having this yesterday to my boss.

1

u/[deleted] Mar 19 '21

I’M PUMPED.

1

u/graingert Mar 20 '21

This is a bait and switch

1

u/[deleted] Mar 20 '21

Python is becoming JS and JS is becoming Python

3

u/xigoi Mar 20 '21

Since when does JS have pattern matching?

0

u/[deleted] Mar 20 '21

1990s i think

2

u/xigoi Mar 20 '21

Really? Can you show me how to do the equivalent of this?

match point:
    case (0, 0):
        print("origin")
    case (0, y):
        print(f"{y} on the y-axis")
    case (x, 0):
        print(f"{x} on the x-axis")
    case (x, y):
        print(f"({x}, {y})")

1

u/[deleted] Mar 20 '21 edited Mar 20 '21
switch (point){
    case [0, 0]:
        console.log("origin");
        break;
    case [0, y]:
        console.log(String(y) + " on the y-axis");
        break;
    case [x, 0]:
        console.log(String(x) + " on the x-axis");
        break;
    case [x, y]:
        console.log(String([x, y]));
        break;
}

Datatype differences aside you can see how similar the syntaxes are getting.

1

u/xigoi Mar 20 '21
ReferenceError: y is not defined

Try it online!

1

u/[deleted] Mar 20 '21

Like Python you need to define your variables first or it will throw an undefined error.

2

u/xigoi Mar 20 '21

The match statement is what defines the y variable. I don't think you understand how it works. This:

point = [42, 0]
match point:
    case [x, 0]:
        print(x)

will print 42.

1

u/[deleted] Mar 20 '21

Great 👍 less code

0

u/lightestspiral Mar 19 '21

Is this a try-except-finally block but the try doesn't have to error out for the except to trigger? You can force the 'except' to run by stating its case?

9

u/bumbershootle Mar 19 '21

No, it's a way to match on the structure of values (rather than only boolean conditions, as in an if-else) while also allowing binding variables within the matches. It's much more than simple control flow. I would recommend reading the PEP, it covers the whole concept in great detail.

4

u/zurtex Mar 19 '21

The pattern matching is far more expressive than that but yes there are similarities to a try/except block.

We are choosing which block we want to execute based on the pattern of a value (e.g. except {ExceptionInstance}), we are can create assignments based on that (e.g. as e), and there is a final default branch if nothing else works (e.g. else).

The usage though is going to be generally very different, exception raising has a very different control flow to match statements.

0

u/1MightBeAPenguin Mar 19 '21

Pretty cool. I don't know a lot about Python, but from what I understand, these match statements seem to be much cleaner than if - elif - elif - else statements.

0

u/[deleted] Mar 20 '21 edited Mar 20 '21

I don't see the point, dictionaries are ubiquitous and more consice with similar functionality, it's pretty easy to see this is the same without all the extra case statements:

{"200": do_something, "418":coffee}.get(http_code, lambda: None)()

4

u/xigoi Mar 20 '21 edited Mar 20 '21

Now how would you do something like this with a dictionary?

match command.split():
    case ["echo", *words]:
        print(*words)
    case ["read", "file", name]:
        ...
    case ["convert", name0, "to", name1] | ["convert", name1, "from", name0]:
        ...

Another example taken from down the thread:

match point:
    case (0, 0):
        print("origin")
    case (0, y):
        print(f"{y} on the y-axis")
    case (x, 0):
        print(f"{x} on the x-axis")
    case (x, y):
        print(f"({x}, {y})")

1

u/[deleted] Mar 21 '21

Just create functions for each complex case and take the first key, being able to lump a ton of logic in a single line is not better than small, clear, and explicit.

-19

u/mysticalfruit Mar 19 '21

I'm not a fan, and here is why.. this behaves differently from every other switch statement I've ever used.. So this is going to only result in confusion.

"case" in point:

switch (foo)
{
case 1:
    printf("ding ");
case 2:
    printf("dong ");
}

If foo == 1 you'll get "ding dong"

if foo == 2 you'll get "dong"

match foo:
    case 1:
        print("ding ")
    case 2:
        print("dong ")

Now if foo ==1 you're only going to get "ding " not "ding dong"

I suspect may of us who cut their teeth on C/C++ switch syntax are going to get thrown for a loop.

58

u/[deleted] Mar 19 '21

Falling through is astonishing behaviour and should be absolutely explicit like, using 'continue' as a keyword at the end of the block.

36

u/MrDysprosium Mar 19 '21

I agree completely. It's hard to watch people fight so hard for such horribly abstract and unintuitive design merely because "well that's how we USED TO DO IT".

Please stop, making the language easier to understand and write is a good thing. Maintaining standards for the sake of maintaining standards makes you sound like a boomer.

8

u/St_Meow insert(caffeine) Mar 19 '21

You'd think these same folk would be aghast at using for each loops instead of for loops or even while loops.

-9

u/mysticalfruit Mar 19 '21

We can argue the merits of the behavior, but its a behavior that many programmers use. I've seen plenty of complex C that use cases in this way to handle cascaded logic situations.

21

u/[deleted] Mar 19 '21

That is true, but Python's style seems to be making the best design decisions they can instead of repeating poor decisions by previous designers just because its familiar. That's also why its called "match" instead of "switch"

4

u/mysticalfruit Mar 19 '21

Fair enough.

5

u/energybased Mar 19 '21

We can argue the merits of the behavior, but its a behavior that many programmers use.

Time to learn a better way to do things instead of hanging on to an opaque specification.

16

u/[deleted] Mar 19 '21

C# explicitly forbids fall through, as in it's a compile error to end a case without a break, return or throw (unless it's a switch expression, but that implicitly inserts a break after each case). I think Java allows fall through, but I've not used java beyond toy things in years ago I don't recall.

This is also closer related to Rust's and Scala's match implementations than C's switch anyways. As in, you can use it for implementing a switch but there's more you can do with it then that.

9

u/St_Meow insert(caffeine) Mar 19 '21

Go uses a similar pattern of not falling through switch cases. I'm certain if you're a vet of older languages with switch statements it'll confuse you for a moment or two, but new programmers will grasp this better. I remember learning switch statements in college and having most of my class baffled at the fall through behavior.

1

u/mysticalfruit Mar 19 '21

Who you calling old ;-)

I think the danger is people are just going to assume it works a certain way.

2

u/xigoi Mar 20 '21

Everyone who has ever used Rust, Haskell, Swift, F#, OCaml, etc. knows how pattern matching works.

1

u/St_Meow insert(caffeine) Mar 19 '21

As the young hotshot coder I reserve my right to call anything from before 2010 old lol

But to be fair, it's not like it's a completely new take on switch statements. Users should be aware of how their language constructs function. Yes it's no conducive for C/C++/Java programmers but so is not having to declare variable and parameter types. We get over it in time.

5

u/jmreagle Mar 19 '21

That doesn't make sense to me. (I last used C/C++ decades ago...)

5

u/[deleted] Mar 19 '21

Okay, but the behaviour of most other languages you're describing is horrible and unintuitive and leads to loads of bugs when people forget to add break statements. Explicit is better than implicit, after all, and there's nothing explicit about executing case 2 when foo is not 2. If I saw your example in production code I'd say that was bad code even if the behaviour is desired, because it's unclear and looks like a bug. Sooner or later, someone's going to come along and stick in a break statement because it looks like one is missing.

9

u/the_other_b Mar 19 '21

The title of this video is incorrect and misleading, the PEP is not for switch statements and you shouldn't expect it to act as one.

7

u/AlbertoP_CRO Mar 19 '21

The future is now old man

2

u/Dwarni Mar 19 '21

I was taught to always put a break; in each case, to prevent that...

3

u/johnisom Mar 19 '21

Ruby would like to have a talk with you

1

u/Broan13 Mar 19 '21

This is somewhat how it works in Java. You have to use a break at the end of each case if you want it to be like the match version.

1

u/[deleted] Mar 19 '21

I never thought I'd praise Java but switch expressions, added in Java 12/13, are really good.

switch(value){
case 1 -> {System.out.println("Hey it's 1");}

case 2  -> {System.out.println("Hey it's 2");}

default -> {System.out.println("Hello there");}
};

If value == 1 then it prints "Hey it's 1" and if value == 2 then it prints "Hey it's 2". Otherwise default is the fall back.

0

u/catetcpasswd Mar 20 '21

Aah finally...

-19

u/baconcleaner Mar 19 '21

omg, seriously? What was wrong in using a dict to emulate a switch-case? Do we really need new statements at this point?

15

u/Jyan Mar 19 '21

It provides structural pattern matching https://www.python.org/dev/peps/pep-0622/ similarly to Scala -- it is extremely powerful and not easy to emulate.

12

u/nemec Mar 19 '21

Watch the video? This is structural pattern matching - some languages who have it build it upon their existing switch statement, but because Python doesn't have one, it seems like they've added a new switch statement when it's actually far more capable and full of features.

5

u/baconcleaner Mar 19 '21

ok I read more comments and I get it now: ITS NOT A SWITCH. The examples with pattern matching blow my mind. Can't wait to use it 2030 when autodesk maya will have it, for now lets continue with 2.7.

6

u/CashAccomplished7309 Mar 19 '21

If you don't like the feature, you don't need to use it.

I personally like it, coming from PHP.

1

u/baconcleaner Mar 19 '21

I wasn't saying that people should not use it, I was just wondering why at this mature point in python now is necessary to have the switch. For example, I 100% agree with the introduction of the walrus operator, wich is awesome and allows to do things that were imposible to do before. But, hey, its just my world view, nobody should care.

2

u/xigoi Mar 20 '21

How were they impossible before? You could always do

foo = bar
if foo:

instead of

if foo := bar:

1

u/baconcleaner Mar 20 '21

There's always a workaround for everything ;-), but for example with the walrus operator you can assign and use objects directly in nested loops:

class test:
  def __init__(self, v):
    self.v = v + 1

tests = [(obj, obj.v) for x in (11, 22, 33) if (obj := test(x))]
print(tests)

1

u/[deleted] Mar 19 '21

If you read the PEP, it's more or less doing the same thing, just with a clean syntax.

-26

u/[deleted] Mar 19 '21

Tell it I hate it. Taking away very useful identifiers like 'match' and 'case' to use as a crappy if/elif replacement.

12

u/CashAccomplished7309 Mar 19 '21

Why is it crappy?

I'd much rather see

match page_slug:
    case 'status':
        return render('status.html')
    case 'about':
        return render('about.html')
    case 'contact':
        return render('contact.html')
    case _:
        return render('home.html')

instead of

if page_slug == 'status':
    return render('status.html')
if page_slug == 'about':
    return render('about.html')
if page_slug == 'contact':
    return render('contact.html')
return render('home.html')

5

u/jwallio Mar 19 '21

Can you elaborate a little more on why you prefer the first block? On first glance the second block seems fine to me.

12

u/jamescalam Mar 19 '21

Being able to do stuff like:

match qa:
    case {'answers': [{'text': answer}]}:
        pass
    case {'plausible_answers': [{'text': answer}]}:
        pass
    case _:
        answer = None

Looks a cleaner than with if-elif-else imo:

if 'answers' in qa.keys() and len(qa['answers']) > 0:
    answers = qa['answers'][0]['text']
elif 'plausible_answers' in qa.keys() and len(qa['plausible_answers']) > 0:
    answers = qa['plausible_answers'][0]['text']
else: 
    answers = None 

9

u/St_Meow insert(caffeine) Mar 19 '21

Reduced visual noise. Rather than worrying about what all those conditionals are and the repetition of the first few pieces, I just know they're all checking equality and I don't have to type my variable name a dozen times.

5

u/CashAccomplished7309 Mar 19 '21

I think it's easier to read and is easier to expand.

I'm newish to Python, coming from PHP, so the familiarity also is comfortable for me.

1

u/Tyler_Zoro Mar 19 '21

As with many features that reduce the use of a single value, this allows for the fact that not all values are side-effect-free. For example, if page_slug in the above example were instead an re.search, you would have to create a temporary variable explicitly in order to avoid perform the match over and over again (the walrus operator makes this less horrible, but still unnecessary clutter).

Think of it in terms of "what is the operation being performed?" In this case the operation being performed is a comparison between page_slug and several values. Now unroll that exactly as I just said it in english:

comparison between page_slug:
    and value 'status': ...
    and value 'about': ...
    ....

and reduce those chunks of English to keywords:

match page_slug:
    case 'status':
        ...
    case 'about':
        ...
    ...

It's exactly what it's most natural to say in English. You don't say, "a comparison between page_slug and value a, between page_slug and value b, between page_slug and value c, etc." You don't do this because English sounds wrong when there's lots of redundancy, and IMHO, so should Python.

0

u/Endemoniada Mar 19 '21

It resembles with statements, in my opinion, which is nicer. It’s like with case match foo. It just looks clean and easy on the eyes.

It’s also not the only use for case statements either, the main advantage as I read about it was handling not only different values in a variable, but different configurations of variables entirely. Like if foo can be a string, a 2-item tuple or a 5-item tuple. case makes that easier to deal with in a pythonic way.

7

u/[deleted] Mar 19 '21

Those identifiers are not taken away. I am not a fan of this addition either, but at least inform yourself before ranting.

7

u/[deleted] Mar 19 '21

What about the pattern matching makes it a "crappy if/elif replacement"?

0

u/kenfar Mar 19 '21

Wouldn't it be fair to say that it's a more readable and concise, but limited statement?

4

u/[deleted] Mar 19 '21

Match seems every bit as powerful as if to me. It's not limited to just checking if two values are equal.

For example, if you're writing a flask view decorator, you need to check to see if it's a response object, a single value, or a tuple of (rv, status) or (rv, headers), or (rv, headers, status) - I think (rv, status, headers) is supported as well. So you end with something goofy as hell like:

if isinstance(rv, Response): # handle response
if not isinstance(rv, tuple):
    rv = (rv,)
rv, headers, status = (rv + (None, None)[:3]

Whereas with match, you could do:

match rv:
    case Response():
        # handle response object
    case (response, int(status)):
        # rv + status
    case (response, dict(headers)):
         # rv + headers
    case (response, int(status), dict(headers)):
         # you get the idea
    case _:
         # just the response value

Hurrah, no more goofy tuple surgery.

1

u/kenfar Mar 19 '21

Yeah, that's nice

0

u/[deleted] Mar 19 '21

[deleted]

→ More replies (8)

-2

u/cuaubrwkkufwbsu Mar 19 '21

omg is this finally happening

-3

u/LionTion_HD Mar 19 '21

ey, elif statements begone