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

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

mCoding

2 года назад

220,336 Просмотров

Ссылки и html тэги не поддерживаются


Комментарии:

Atur Sams
Atur Sams - 14.11.2023 14:21

This was hard to follow. It would have been 100% to start with a simple example where you match a normal dict and/or tuple.

Ответить
Flávio Lisbôa
Flávio Lisbôa - 13.11.2023 00:29

Honestly, I think the `if` version is clearer and easier to communicate, and should be the default option for those kinds of problems.

In the `if` version, what is being checked is almost self-evident. For the structural matching, you'll end up second-guessing yourself or, in your example, drill down the structure so much that the tree becomes unwieldly and hard to read. If only Python had a terser syntax for structures, this problem could be alleviated (example: JSONPath, etc.).

Also, with an `if`, you can add complex logic that depends on multiple criteria (sometimes including non-structural ones), which in the `match` version is something that (AFAICT) cannot be done (by the nature of such functionality), so why bother at all?

The way I see it, `match` is mostly useful for very simple cases, or for value extraction.

Ответить
mmxgn
mmxgn - 28.10.2023 12:56

Ugh had a recent use case for this which I ended up using if statements because I had forgotten about match statements! I feel stupid now. Nice video!

Ответить
Fabiolean
Fabiolean - 26.10.2023 22:22

I'm so glad to stumble upon this video, because I've been preaching about the advanced use-cases for the new match statements since 3.10 released.

Ответить
Noido Dev
Noido Dev - 19.10.2023 04:20

I think this pattern matching could be useful for natural language parsing and matching patterns to react on it, also it looks cleaner than if - elif - else.
What bothers me, though, is that I can't define every pattern as some kind of object, e.g. foo_pattern = 1 | 'one' | 'I' won't work. if "1" in [1, 'one' , 'I'] does work and I can define a variable with that list inside.

Ответить
ncrohawk
ncrohawk - 17.10.2023 04:22

"wonky features in python" shows +=
meanwhile every language ever:

Ответить
thevalarauka101
thevalarauka101 - 16.08.2023 23:59

I always thought of it like a regex but for Python objects, once I found out what it could do

Ответить
Dave A
Dave A - 01.08.2023 03:15

I have used a dictionary function dispatch structure in a job where they frequently changed the requirements. It made it simple to quickly alter the code flow using a simple properties file.
Yes, that is a horrible use case. But when you have real clients you have to do whatever is necessary to accomodate their foibles.

Ответить
Braderbell
Braderbell - 17.07.2023 10:04

Watching this with no intention to ever stop using match statements as switch statements '_'

Ответить
angelorf
angelorf - 09.07.2023 11:33

This kind of structural pattern matching is great! It's a shame it's limited to only this new match case, rather than on the lhs of any assignment.

Ответить
Michael Cetrulo
Michael Cetrulo - 08.04.2023 21:28

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.

Ответить
Michael Mueller
Michael Mueller - 04.04.2023 19:34

"Just a simple match-statement" ...I was expecting easy stuff and now I'm brainfucked

Ответить
Dip-Dip Potato Chip
Dip-Dip Potato Chip - 22.01.2023 07:27

What's wonky about +=? lol

Ответить
MC Dolla
MC Dolla - 14.01.2023 18:39

i donno how yu were able to understand this complex, but u r a true gem or anyone who understand this, altough ,as per the understanding part i think i got your point but , i know deep inside i cannot implicate this like you to show up to anyone, gr8 hatsoff

Ответить
Randall Stephens
Randall Stephens - 12.01.2023 06:26

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!

Ответить
Dhahri Mohamed Amine
Dhahri Mohamed Amine - 07.11.2022 13:30

I have no idea what are you talking about. I'm still learning classes, but the videos is still enjoyable.

Ответить
Kacper Kwaśny
Kacper Kwaśny - 30.10.2022 22:54

Thank you so much for all those videos!

Ответить
Sędziwój
Sędziwój - 16.10.2022 13:50

Sorry but your "longer if statement" is BS and code readability is more important than if it have 10 or 12 lines or intend. Some people forget what is important in code and what is not.

Ответить
Incremental Failure
Incremental Failure - 12.10.2022 15:15

I normally play videos at 1.25x or 1.5x speed. I tried it with your stuff and was immediately overwhelmed.

Ответить
AdroitBit
AdroitBit - 12.10.2022 13:01

That is some aggressive feature added right here

Ответить
vinzent1992
vinzent1992 - 11.10.2022 16:28

I spend a lot of time writing Python code and I would say that I have a pretty good understanding of python < 3.10, but this just left me with a million unanswered questions:

1) Where did you define _? it looks to me like you are creating an instance of cst.Tuple, passing it a list as keyword argument "elements", and the list contains a variable "_" as the first two elements, unpacked and not unpacked. But you don't define "_" anywhere. After all this is not a function definition right?!.

2) How does the comparison work? does the cst.Tuple instance that you create take care of the comparison between "node" and the cst.Tuple(...) structure you created? or is this also some new feature in Python 3.10?.

3) How can I create my own classes that support this type of structure matching?

This is a great example of a very neat new feature, and I appreciate the video a lot, but I would really love a much more detailed video that really does a "deep-dive" into the mechanics that make all of this work under the hood.

Ответить
BrianJS
BrianJS - 04.10.2022 11:23

I still want an optimized switch-case in Python, especially now that I use python on microcontrollers. A lot of low level applications are best implemented using a basic jump table. Using any kind of jump based on function calls can be too costly.

Plus I also prefer switch-case over if-else-if in cases like this.

switch ( v ):
case 0: # comment
code
break
case 1: # comment
case 5: # comment
case 7: # comment
code
break

Easier to read and especially easier to comment than,

else if ( v == 1 || v == 5 || v == 7 ):

Not saying we should optimize the match-case, just have a separate switch-case. I wish this new trend of deciding for us how we should use everything, from devices, to applications, to programming languages, would end. Especially from these dictators that seem very narrow minded.

Ответить
Tim Brown
Tim Brown - 29.09.2022 02:49

The video could do without the pedantic rant on match not being switch to pad the video. Match is a superset of switch. See how simple that was?

Ответить
Fake Trump
Fake Trump - 28.09.2022 06:27

stopped watching at 5 min. what's the topic?

Ответить
mrwensveen
mrwensveen - 26.09.2022 01:35

You almost make it sound like the match statement is for parsing syntax trees specifically, which isn't true. It's a good example, but there are many many more situations where pattern matching is useful.

Ответить
Tigrou7777
Tigrou7777 - 24.09.2022 21:02

Switch in C/C++ are likely to be converted to a binary tree search rather than a jump table, unless there is lot of statements

Ответить
Calyo Delphi
Calyo Delphi - 22.09.2022 03:02

I dunno about you, but I find switch statements to be MUCH easier to read than a ladder of if-else-if statements, so I'm pleased that Python 3.10 has a construct that can now be used akin to a switch statement for the off-times that I may actually need it. I consider the terser syntax of the match statement utilized as a switch to be more Pythonic than an if-else-if ladder. Just like in the example you showed, where the terser verbosity of using match against an abstract structure is easier to read and more Pythonic than a multi-layer of if statements.

Ответить
Breno Veríssimo
Breno Veríssimo - 21.09.2022 03:06

Dude, I study python mainly for web. I havent understand or seen any of this stuff before... how advanced is this subject?

Ответить
Coda Highland
Coda Highland - 20.09.2022 21:05

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.

Ответить
acasualviewer
acasualviewer - 19.09.2022 07:23

Structural pattern matching is most similar to what is done in languages like Prolog or O'Caml.

Ответить
t2l
t2l - 18.09.2022 12:57

that was propably the worst example to show the benefits

Ответить
esphi LEE
esphi LEE - 14.09.2022 03:55

Dictionary is more readable than switch.

Ответить
Matías Nicolás Sosa
Matías Nicolás Sosa - 13.09.2022 19:12

the author is from my university. we learn using Haskell, so I guess that's the origin from this feature

Ответить
Marcos Sartori
Marcos Sartori - 13.09.2022 11:33

This is just pattern matching on algebraic datatypes

Ответить
ThreeCube
ThreeCube - 12.09.2022 00:33

True, True, True!

Ответить
Nathan St.Marie
Nathan St.Marie - 07.09.2022 12:26

When you always just used a dictionary to accomplish the switch statement but everyone else says they've struggled ....

Ответить
Aang139
Aang139 - 20.08.2022 23:04

Depending on how you are using dictionary switch statements i don't agree that it's less readable. I think especially in the polymorphic like case it's much more readable, and easier to extend

Ответить
intheblink
intheblink - 20.08.2022 04:44

Oof, this requires some brain power to understand. Great job walking through it, though.

Ответить
Daniel
Daniel - 17.08.2022 06:29

+= is not a "wonky feature". It's the proper way it should be done!

Ответить
Travis Weedon
Travis Weedon - 06.07.2022 17:56

Whats wrong with the '+=' ? :(

Ответить
Frank Gomes
Frank Gomes - 28.06.2022 10:11

Damn! I learn something new with every one of your videos!!! Utmost respect for you!!

Ответить
Red Eye Orb
Red Eye Orb - 22.06.2022 05:33

Finally a match statement for my dumb ass

Ответить
nofebak
nofebak - 18.06.2022 12:40

Thanks for the video! In truth, adding case to replace the long and less readable chain of 'if' would make a lot of sense to me, more specifically from a performance point of view (even if that's not optimized now, it leaves the possibility for later, it would be much harder with the 'if' pattern). But yeah, it's obvious that they've gone way further and implemented Rust-like patterns. It really improves the clarity of code.

Ответить
TechSY730
TechSY730 - 09.06.2022 00:42

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.

Ответить
III III
III III - 07.06.2022 10:52

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

Ответить
Mr. Norris
Mr. Norris - 30.05.2022 01:18

Or just: Pattern Matching

Ответить
Cookie
Cookie - 24.05.2022 15:05

I'm definitely not high enough to learn this.

Ответить
kreo debunk
kreo debunk - 18.05.2022 08:24

yeah, the default library for ast is so ugly

Ответить