Jul. 19th, 2024
2024年 6月 14日

Post: Switch-Case Statements Are Coming to Python

Switch-Case Statements Are Coming to Python

Published 15:03 Mar 20, 2021.

Created by @ezra. Categorized in #Programming, and tagged as #Python.

Source format: Markdown

Table of Content

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 , 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.

What we have here is much more than a simple switch-case statement, however (hence match-case), as we will see soon.

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

Structural Pattern Matching

The pattern matching takes a value following match and allows us to write out several potential cases, each defined by case. Where we find a match between the match-case we will execute the respective code.

For example:

http_code = "418
"match http_code:
    case "200":
    case "404":
        print("Not Found")
    case "418":
        print("I'm a teapot")
    case _:
        print("Code not found")

Here we’re checking multiple conditions and performing different operations based on what value we’re finding inside http_code.


Immediately it’s evident that yes, we can build the same logic using a chunk of if-elif-else statements:

http_code = "418"if http_code == "418":
elif http_code == "404":
    print("Not Found")
elif http_code == "418"
    print("I'm a teapot")
    print("Code not found")

However, by using the match-case statement we remove the repetition of http_code ==Which can look much cleaner when testing for many different conditions.

Another Example

We can find some great examples of using the match-case statement to improve code readability in PEP 635. One of those is this example showing us how to use match-case to check the type and structure of our subject:

match x:
    case host, port:
        mode = "http"
    case host, port, mode:

Here we expect to receive connection details in a tuple format and assign the given values to the correct variables.

In this case, if the connection mode is not defined within the tuple (e.g., only two values have been provided — the host and port), we assume that the connection mode is “http”.

However, in other cases, we may expect that the mode is explicitly defined. So rather we might receive a tuple like (<host>, <port>, "ftp") — in which case we would not want to set mode to “http”.

Now, if we wanted to write this same logic using an if-else statement, we would get this:

if isinstance(x, tuple) and len(x) == 2:
    host, port = x
    mode = "http"
elif isinstance(x, tuple) and len(x) == 3:
    host, port, mode = x

Which option is preferred may vary, but for me, the match-case implementation looks much cleaner.

Personally, I think this new syntax looks really good — although I’m 50/50 on it at the moment. Once more users begin coding with match-case, I’m confident that the community will quickly establish a consensus and best-practices.

But for now, it looks cool — I’m excited!

Pinned Message
I'm looking for a SOFTWARE PROJECT DIRECTOR / SOFTWARE R&D DIRECTOR position in a fresh and dynamic company. I would like to gain the right experience and extend my skills while working in great teams and big projects.
Feel free to contact me.
For more information, please view online résumé or download PDF
本人正在寻求任职 软件项目经理 / 软件技术经理 岗位的机会, 希望加⼊某个新鲜⽽充满活⼒的公司。
如有意向请随时 与我联系
更多信息请 查阅在线简历下载 PDF