r/pythontips • u/electroica • Apr 27 '21
Python3_Specific Finally Switch case statement in python.
No more "where is switch case in python?"
In the python 3.10 release according to the accepted PEP634,635,636 Match-Case statement will be added which is similar to Switch-Case statements in other languages. Match case is structural pattern matching which will match 'cases' against the subject value 'match'.
https://blog.electroica.com/switch-case-is-match-case-python/
7
u/RojerGS Apr 27 '21
Thanks for the link :)
I just want to clarify that Python's match is not a simple switch statement and, in fact, if all you want is a simple switch statement, than you probably have better options than using match. Python's match is useful for structural pattern matching, e.g. when working with recursive data structures or otherwise structured data.
(Disclaimer, I linked to articles written by myself to back up my claims, but the articles themselves have may references from which you can learn more and decide by yourself if what I'm saying makes sense)
3
u/gary1994 Apr 27 '21
I just used dictionaries for switch statements...
Granted I'm still learning.
1
u/mjmacarty Apr 30 '21
Yep, same. Not sure why this is needed. I would go so far as to call it anti-Pythonic, but maybe I will change my mind when I see it in action.
2
2
u/Dorlo1994 Apr 27 '21
We've had a lot of workarounds for this, but it's good to have a more straightforward possibility
1
u/Verbose_Code Apr 27 '21
“Brandt Bucher and Guido van Rossum talks about the specification of adding a match statement which is exactly similar to switch statements in other languages.”
I just like the phrase “exactly similar”
Can’t wait to see this implemented!
1
u/h7hh77 Apr 27 '21
Honestly, it was fine all this time without it. It's a bit of an improvement, but not significant.
4
u/geekyhumans Apr 27 '21
I seriously developed the habit of using if-elif but was missing a lot when switching from PHP