DEV Community

Cover image for New Switch-Case Logic in Python
James Briggs
James Briggs

Posted on

New Switch-Case Logic in Python

Python 3.10 is beginning to fill-out with plenty of fascinating new features. One of those, in particular, caught my attention - structural pattern matching - or as most of us will know it, switch/case statements.

Switch-statements have been absent from Python despite being a common feature of most languages.

Back in 2006, PEP 3103 was raised, recommending the implementation of a switch-case statement. However, after a poll at PyCon 2007 received no support for the feature, the Python devs dropped it.

Fast-forward to 2020, and Guido van Rossum, the creator of Python, committed the first documentation showing the new switch-statements, which have been named Structural Pattern Matching, as found in PEP 634.

Let's take a look at how this new logic works.

Top comments (2)

Collapse
 
lifelongthinker profile image
Sebastian

GoTo statement considered harmful 😜 And Switch Case is GoTo's little brother.

Like any tools, they're good to use when you really just need them, but beware of the dangers they bring.

E.g., in any OOP paradigm make sure you are not violating OCP (Open-Closed Principle). Also see if polymorphism isn't a better alternative.

Collapse
 
jamescalam profile image
James Briggs

Definitely agree that it shouldn't be used for the sake of using - but looks great in some use-cases.

Awesome info though, thanks!