The real purpose of Python's match statement, feat. CSTs

preview_player
Показать описание
What's the purpose of the match statement in Python?

The match statement is commonly mistaken for being Python's way of adding a switch-case statement. NOPE! This is not the intended purpose of the match statement, and it does not have similar performance benefits. Let's see what the match statement is REALLY for by parsing concrete syntax trees (CSTs).

SUPPORT ME ⭐
---------------------------------------------------

Top patrons and donors: Jameson, Laura M, Dragos C, Vahnekie, John Martin, Casey G

BE ACTIVE IN MY COMMUNITY 😄
---------------------------------------------------

CHAPTERS
---------------------------------------------------
0:00 Intro
0:20 Switch case?
2:52 ASTs and CSTs
4:14 True, True, True
4:46 Visiting the CST
5:50 Matching the CST
7:50 Addressing complexity
Рекомендации по теме
Комментарии
Автор

My day job is to write these cst visitors and transformers for our static analysis platform, and upgrading our infrastructure to python 3.10 was an absolute game changer for me.

sadhlife
Автор

pattern matching is one of the best features of haskell, and i'm really happy to see it come to python too

kurtmayer
Автор

For a semester at my Uni, We have been thought a functional programming language called OCaml. I cannot express how much I liked the concept of structural pattern matching in OCaml back then. Being able to make a recursive call for the rest of a list by using pattern matching was really satisfying.

kaancayli
Автор

I watched this ages ago, thought it was neat, but didn't have any use for it. Now I'm working on a large and complex codebase and when I realized I needed to be able to find all the instances of a specific structural pattern, I came back here for a refresher. This is great; exactly what I need to solve my problem!

RandallStephens
Автор

This channel is pretty damn advanced! Gives me more reason to not string-parse Python code again 😅

Mutual_Information
Автор

Matching XML, DOM and similiar structures is another application that comes to mind after watching this very nice video.

falknfurter
Автор

The other thing about the match statement that's useful is that it allows you to both check the structure of something, and pull values out of it. In the jumble of if statements, there's a couple places where you check something, then pull a value out of the structure, then check against that, and so on. It's useful to match against the structure, and be able to pull out a value and use it straight away

erikgrundy
Автор

I'm mind-blown every time I watch your videos, absolutely perfect.
Keep it up, we need a lot more youtubers like you!

DrDemolition
Автор

Thank you for making a video on this, I've had to explain the whole match vs switch cases countless times in discord help servers. Appreciate showing a great example with csts as well, anyone who has written an interpreter/compiler before knows how valuable structural pattern matching is.

UnFallenRain
Автор

Thanks for this very insightful video. Not only the match case is a bunch of if statements in disassembly, but it's also a very unoptimized one. It is bound to be the slowest of all three cases.

victornoagbodji
Автор

You're such a good teacher and your videos look absolutely great. Thank you for your work

Sloth
Автор

Where I am usually running into use cases for match/case is parsing file formats, where cases are along the lines of "contains three tokens: two keywords and one value". E.g. a proprietary format where a line might be "add key user.name". Such things might make for simpler examples, and demonstrate a case of (a) code getting both clearer AND shorter and (b) extracting values from the matched structure.

klaus
Автор

You always amaze me: so much content, well explained, in such a short video!
About the "jump table" dictionary: of course, you are not limited to integer keys, and I would claim that it does make more sense with strings. For when you want to be able to add functions at runtime, say, for a kind of plugin system.

malteplath
Автор

cst is a pretty niche application, matching JSON, YAML or XML trees is probably a more common use case however the issue I see with this approach compared to the if-chain is that you don't get specific errors, you only get a "match or not" and that will make debugging harder, you'll have to look for the problem in the whole structure. I think it's better to use a third party parser and validator if possible.

SamusUy
Автор

The performance benefit of switch isn't the only reason it's valuable. In my opinion, the far more important part is that it promotes DRY. You aren't writing "x ==" a zillion times, and there's only one place to change if you need to change the value being switched on. This, I think, is a very Pythonic benefit, and one that's worth the additional level of indentation.

codahighland
Автор

Thank you for the high quality educational content !
about the switch_dict_example() method at 1:50, line 10, it seems to me that the built in "get" function's default argument doesn't have the name "default" and so we should write :
do_next = _switch_dict.get(x, default)
instead of : do_next = _switch_dict.get(x, default= default)
the default parameter should be put positionally otherwise we get the following error : "get() takes no keyword arguments"

samihani
Автор

Honestly, I really appreciate the sarcasm at the beginning. Having been in a position of having to explain new features to users, I *really* understand the pain of having someone completely misunderstand, or worse still is to misuse, a new feature set. I also really appreciate the dictionary example. I've used that pattern in multiple languages for abstracting a branch of code that hoists functions from another scope into the main operation of an application.

Lastly, while I understood what pattern matching meant, it was really nice to see a concrete example in Python. In C#, I used to love pattern-matching for If-Else chains that relied on variable declarations, since C# allows the pattern match to initialize a new variable of that static type. Python had no use for such a concept, because of dynamic typing, but the obvious benefit is that it is an extremely expressive statement that is (relatively) easy to read.

Always great stuff here. Keep up the great work.

penguindrummaster
Автор

I actually like the match statement as a switch statement better than elif's
Yes, it is one more layer of indentation. But it syntactically separates the thing to be tested from the things to be tested against.
It can be hard to tell at a glance which value each elif is testing against. (a simple '==' isn't too bad so long as the number of clauses is low, but when a block has multiple matching values, it becomes kind of ugly)
With match, it pulls the value tested against separately, make it much clearer at a glance what values do what.

TechSY
Автор

Really thank you for that pauses after explanation. So you don’t need to pause video to observe written code.

iiiiii
Автор

Thanks, I actually learned quite a bit from this showcase.

xelaxander