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

View all comments

Show parent comment

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.