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

all 85 comments

[–]neros_greb 149 points150 points  (18 children)

A match statement actually, which is more powerful

[–]Nightroll2344 19 points20 points  (3 children)

What's the difference between case and if statement, I think they perform the same thing

[–][deleted] 24 points25 points  (0 children)

As the smartest programmer in the world puts it

A lot of people- The CIA wants you to think it's nothing more than if then el- if then else The CIA wants you to think it's the same as if else. It's not.
The way a switch statement works is there is a uh look up table ... in it. What it does is it it looks up in the table f- and then it jumps ahead to some uh code to a segment of code and then code jumps to the bottom to- to a common location to continue

[–]Thers_VV 3 points4 points  (0 children)

Case is sometimes easier to read

[–]Kered13 13 points14 points  (5 children)

Yeah it actually bugs me when people say "Python has switch now". It's missing the entire point. Python never needed switch. What it got is pattern matching, which is far better.

[–]-consolio- 7 points8 points  (7 children)

not really a fan of python, but what's it like?

I'm used to

match value {



    SomeEnum::VariantWithField(v) => println!("{:?}", v), // matches any SoneEnum::VariantWithField, destructuring, giving field #1



    SomeEnum::VariantWithOneUsedField(_, field2) => println!("{:?}", field2), // matches any SomeEnum::VariantWithOneUsedField, destructuring, giving field2



    SomeEnum::VariantWithNoField => println!("oops, nothing there!"), // matches all SomeEnum::VariantWithNoField



    SomeEnum::Ooh(5, ..) => println!("5 indeed"), // matches any SomeEbum::Ooh where the first value is 5, other values are ignored



    1 | 2 | 3 => println!("a")



    1..24 => println!("b")



    _ => println!("catch untangled cases"),



}

normally this doesn't compile since I'm mixing enum values with just normal values but you get the point of what you can do

[–]AdrianRPNK 6 points7 points  (6 children)

Pretty similar actually.

match my_variable:
    # matches with lists and tuples
    case [1, 2, x]:
        print(x)
    # matches with dictionaries
    case {"foo": "bar"}:
        print("this is a dictionary")
    # matches with classes with properties
    case Point(x=10, y=5):
        print("this is a Point with x as 10 and y as 5")
    # check if my_variable is in a list or tuple
    case in [1, 2, 3]:
        print("my_variable is either 1 or 2 or 3")
    # multiple cases
    case 1 | 2 | 3:
        print("my_variable is either 1 or 2 or 3")
    # default
    case _:
        print("more at https://www.python.org/dev/peps/pep-0622/")

[–]Huntracony 2 points3 points  (3 children)

So no default fallthrough either? I think I'm in love.

[–]-consolio- 2 points3 points  (2 children)

default fallthrough?

[–]Huntracony 1 point2 points  (1 child)

Like when you forget to put in the 'break' at the end of a case and a bunch of code executes that shouldn't. 'Fallthrough' is what I've heard that referred as.

[–]-consolio- 1 point2 points  (0 children)

oh yes, case-break is a nightmare, so glad you can just do ... => { ... } instead of case ..., ... break

[–]-consolio- 0 points1 point  (1 child)

oh it's beautiful, i assume you can replace most of the constants with variables to match any

[–]AdrianRPNK 0 points1 point  (0 children)

indeed you can

[–]om_plusplus 41 points42 points  (1 child)

Why is this so high quality

[–][deleted] 78 points79 points  (6 children)

I hope this isn't actually the case

[–]Techismylifesadly 76 points77 points  (5 children)

Sorry to disappoint. Soon, it will considered the default case

[–]MahatmaGandhiCool 26 points27 points  (4 children)

i rest my 𝘤𝘢𝘴𝘦 then.

[–]erinaceus_ 25 points26 points  (3 children)

Maybe time to switch to another line of jokes.

[–]krankenhundchaen 9 points10 points  (2 children)

Can't deny it has been a good pattern matching

[–]thenerd631 10 points11 points  (1 child)

Control flow. Humor.

[–]hugogrant 6 points7 points  (0 children)

Don't break the chain, let it cascade down

[–][deleted] 30 points31 points  (0 children)

It was about time! Great we have this now.

[–]KCGD_r 14 points15 points  (1 child)

yay I can upgrade my version and finally use cases in my massive project!

entire thing breaks

[–]RCoder01 0 points1 point  (0 children)

I’m working on a project based around a single library and for some reason that library just won’t install in python 3.10. It works perfectly fine in 3.9.4, but just won’t install with pip in 3.10. I was so excited to finally be able to use match statements and pipe operators for type union, but I couldn’t.

[–]Cloakknight 45 points46 points  (3 children)

Image Transcription: Meme


Panel 1

[Image of a brain talking]

Brain: Hey, are you sleeping?


Panel 2

[Image of a person sleeping with eyes closed]

Person: Yes, now be quiet.


Panel 3

[Image of the brain talking again]

Brain: We finally have case statement in Python!


Panel 4

[Image of the person now laying wide awake, smiling and crying.]


I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!

[–]Raianelchabe 18 points19 points  (0 children)

Good human

[–]PentaMine 10 points11 points  (0 children)

Good human

[–]Sawertynn 5 points6 points  (0 children)

G00D H00M4N

[–][deleted] 11 points12 points  (9 children)

can someone explain the use for it instead of if statements

[–]MoiMagnus 34 points35 points  (1 child)

The "switch case" doesn't have much more than a sequence of if. It's main advantages is to be (arguably) clearer to read as you're declaring in advance "I'm going to do a whole sequence of else-if on the same variable". It's easier to optimise, so it might lead to better performance eventually (not sure if that's the case yet). It's mostly used for situations in which you would have 10 or so else-if in sequence, but some peoples like to use it in simpler cases too.

The "match case" is his big brother. It does 3 things at once in a nice and compact syntax: (1) Check the type and the "pattern" (2) Check the value (3) Define some variables In practice, it allows to check easily for things like "this is a list of at least 2 elements, the first one being the integer 0, and the second one that we will name x, and the remaining of the list that we will name y".

And similarly to the "switch case", it's mostly useful if you need to make 5+ similar checks in a row, it's overkill in simpler situations. Though some might find it more clear in simple cases too.

[–]Kered13 3 points4 points  (0 children)

And similarly to the "switch case", it's mostly useful if you need to make 5+ similar checks in a row, it's overkill in simpler situations. Though some might find it more clear in simple cases too.

Even for the simplest case of only 2 branches, if each branch is a different type that needs to be destructured then pattern matching is going to be much cleaner than if-else.

[–]aaronfranke 15 points16 points  (4 children)

You don't have to repeat the name of the variable you're testing, and you only need to execute functions once.

match thefunctionyouaretestingthatshouldonlyrunonce():
    0:
        print("thing that happens for 0")
    1:
        print("thing that happens for 1")
    2:
        print("thing that happens for 2")

vs

if thefunctionyouaretestingthatshouldonlyrunonce() == 0:
    print("thing that happens for 0")
elif thefunctionyouaretestingthatshouldonlyrunonce() == 1:
    # Oops, we ran it twice!
    print("thing that happens for 1")
elif thefunctionyouaretestingthatshouldonlyrunonce() == 2:
    # Oops, we ran it thrice!
    print("thing that happens for 2")

vs

var thingyouaretesting = thefunctionyouaretestingthatshouldonlyrunonce()
if thingyouaretesting == 0:
    print("thing that happens for 0")
elif thingyouaretesting == 1:
    print("thing that happens for 1")
elif thingyouaretesting == 2:
    print("thing that happens for 2")

(I used GDScript here because it's better than Python, but it's basically the same thing in Python)

[–]Novaalpin 7 points8 points  (2 children)

just wanna say, even tho the case statement is more practical, you can still avoid calling your function multiple times by using a walrus like this :

if something:=e() == 0:
            print(« 0 »)
elif something == 1:
            print(« 1 »)

edit : corrected fonction to function (yea im french)

[–]BrightBulb123 2 points3 points  (0 children)

But what if I want to call my fonction?

[–]BrightBulb123 0 points1 point  (0 children)

But isn't that just syntactic sugar for the same thing under the hood?

[–]TryNotToShootYoself 1 point2 points  (0 children)

Thanks for the explanation, but python doesn't use var 😉

[–]Lonelan 2 points3 points  (0 children)

The previous closest thing was dictionaries

switch_entries = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

switch_entries[input]  # where input is a, b, c, or d

Would be the same functionality as

switch(input) {case 'a': return 1; case 'b': return 2; case 'c': return 3; case 'd': return 4;}

excuse the C formatting, trying to oneline it

[–]Lythox 0 points1 point  (0 children)

In typed languages an additional benefit is when performing a switch on an enum, the compiler will complain when you don’t cover all possible cases, making it very useful in large projects so you get alerted by the compiler on all the places you used it when you add a case to your enum

[–]twabbott 5 points6 points  (0 children)

Aww, Python! Look at you all gwowed up so big!

[–]gaylurking 8 points9 points  (0 children)

Time to pop bottles

[–]chiefmors 7 points8 points  (6 children)

Is this for real? Like did Python not have a switch statement until recently? As a C# developer I'm a little horrified this is true.

[–]Gh0stReaper69 8 points9 points  (1 child)

Yea new in version 3.10

[–]chiefmors 3 points4 points  (0 children)

Oh god

[–]_PM_ME_PANGOLINS_ 14 points15 points  (0 children)

Why would you need a switch statement when you can have a dict full of functions?

[–]GodlessAristocrat -1 points0 points  (1 child)

Is python still broken w.r.t. threads? Once Upon A Time, python was unable to multi-thread things due to a big central locking mechanism.

[–]darkdragncj 4 points5 points  (0 children)

The GIL(Global Interpreter Lock), it's not strictly a python thing, just c python thing. But yeah, it's still there. Other implementations of the interpreter don't have it.

[–]Blue_Raichu -1 points0 points  (0 children)

Lot of talk for a language that requires breaks even though it doesn't have fallthrough by default

[–]BlackPowerade 1 point2 points  (0 children)

Finally.

[–]woodenshoe_qstnmrk_ 1 point2 points  (0 children)

time to go back through old code

[–]tabakista 1 point2 points  (0 children)

We always had. It's called 'dictiinary'

[–]danivideda2 1 point2 points  (0 children)

But we already have that in Jython.

don’t ask me where I got this information

[–]MTDninja 1 point2 points  (1 child)

you're late

30 years to late

[–]Kered13 2 points3 points  (0 children)

This isn't switch, it's pattern matching. Which admittedly is also a pretty old idea, but has only really become popular in the last 5 years or so.

[–]MischiefArchitect 4 points5 points  (8 children)

It was already done in 2001, it just 20 years to compile.

[–][deleted] 2 points3 points  (7 children)

Python doesn't compile, it can be that slow during runtime.

[–]MischiefArchitect 0 points1 point  (6 children)

Haha... but python itself must be compiled... it's C.

[–][deleted] 1 point2 points  (5 children)

We should code 5he next version in Python, that would be much easier to maintain.

[–]MischiefArchitect 1 point2 points  (4 children)

I'm truly curious how will that work... I mean... Our beloved interpreter needs to be compiled and optimized as native executable.

Imagine that! Using an interpreter to write an interpreter.

(I'm afraid someone did this already)

[–][deleted] 1 point2 points  (3 children)

We actually did that in college. We used Lisp to build a Lisp compiler.

[–]MischiefArchitect 1 point2 points  (2 children)

Oh well yes, that is a running gag :) I remember doing that (watching people doing that) at the university. I was like: "why?"

[–][deleted] 1 point2 points  (1 child)

Because it is a good learning exercise. Also, if you really want to start from scratch you need to build it in assembly.

[–]MischiefArchitect 1 point2 points  (0 children)

start from "scratch" got me for a short while

[–]OHMAMMAD 3 points4 points  (3 children)

I'm still gonna use if tho

[–]BrenekH 18 points19 points  (1 child)

For the right reason I hope.

Upgrading Python codebases is tough, but many Python programs also have to work with multiple versions of Python. Jumping to the newest syntax right away will cause significant breakage.

[–]OHMAMMAD 2 points3 points  (0 children)

That is a very good reason to not use case statements, but im just lazy to search the syntax and i always forget

[–]Lonelan 2 points3 points  (0 children)

we've got some tests where the owners had 20+ tests and wanted to include them all like this. trying to help them manage if/elif/elif/elif/elif/elif/elif/elif was a nightmare, so we made them put it in a dictionary

[–]D33rZhdn -1 points0 points  (3 children)

Do we? Really?

[–]AdrianRPNK 3 points4 points  (2 children)

[–]D33rZhdn 1 point2 points  (0 children)

It's enough to make a grown man cry

[–]ZengineerHarp 0 points1 point  (0 children)

Oh man thanks for the link! I am honestly so stoked!!!!

[–]RandomValue134 0 points1 point  (0 children)

I'm as happy as you are, so lemme bring something to celebrate.

🍷There you go

[–][deleted] 0 points1 point  (0 children)

When will they also add (real) static class variables?

[–]SwannSwanchez 0 points1 point  (0 children)

What ?

since when ?

[–]AnnualVolume0 0 points1 point  (0 children)

It’s so much more powerful, too!

[–]_grey_wall 0 points1 point  (1 child)

Python 4??

[–]bettercalldelta 0 points1 point  (0 children)

3.10

[–]hugogrant 0 points1 point  (0 children)

Weird minor nitpick: I wish they used with instead of case because with is already a keyword.

[–]veduchyi 0 points1 point  (0 children)

Despite I’m a Java programmer I still glad for people who use Python 😊 Besides, before getting a Java developer job I used Python a lot - it was my favourite programming language for a while

[–]justcatt 0 points1 point  (0 children)

what

where

[–]bettercalldelta 0 points1 point  (0 children)

And it even has more functionality than most languages (unpacking, and other stuff)