Тёмный
No video :(

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

mCoding
Подписаться 231 тыс.
Просмотров 223 тыс.
50% 1

Опубликовано:

 

28 авг 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 332   
@sadhlife
@sadhlife 2 года назад
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.
@sebastianmestre8971
@sebastianmestre8971 2 года назад
Awesome! I'd love to work on language tooling. How did you get that job?
@mCoding
@mCoding 2 года назад
I guess I should also point out that libcst has "matchers" that do effectively what the match statement does and can be used pre-Python3.10.
@pranavnyavanandi9710
@pranavnyavanandi9710 2 года назад
Hello 👋. What does "static analysis" mean? Thanks.
@sadhlife
@sadhlife 2 года назад
@@pranavnyavanandi9710 it's the process of analyzing code by looking at its structure
@truthmatters7573
@truthmatters7573 2 года назад
@@pranavnyavanandi9710 to add to what Tushar is saying: static analysis is basically inferring facts about a program without running it, by looking at the source code or sometimes binary (analyzing the instructions) This is in contrast to dynamic analysis / run-time analysis, which looks at the characteristics of a program while it is being run. (Analyzing the behavior)
@kurtmayer2041
@kurtmayer2041 2 года назад
pattern matching is one of the best features of haskell, and i'm really happy to see it come to python too
@katech6020
@katech6020 2 года назад
I am glad that Rust and Python both copied it
@MrMaxtng
@MrMaxtng 2 года назад
Scala too. Its awesome for functional programming.
@Yotanido
@Yotanido 2 года назад
I just wish python also had sum types. It would make things so much easier.
@MrMaxtng
@MrMaxtng 2 года назад
@Jamie Walkerdine functional tools? Python has the biggest repository of plugins, modules, etc. You can literally do anything with python, from making a full stack website to a neural network, pattern recognition, data science, ETL, etc. Perhaps you mean functional tools as in functional programming, in which case I dont understand your point at all since structural pattern matching is a feature (one of many) of functional programming.
@Yotanido
@Yotanido 2 года назад
@Jamie Walkerdine Pattern matching is very useful. In fact, it's pretty much the only way to differentiate between different variants of a sum type. Of course, python doesn't have sum types, so... it doesn't add super much. It does mean you can more easily deal with deeply nested structures, but let's be honest - that is pretty rare.
@kaancayli
@kaancayli 2 года назад
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.
@jupahe6448
@jupahe6448 2 года назад
same here, only with prolog
@harrytsang1501
@harrytsang1501 2 года назад
Agrees in Scala
@waytospergtherebro
@waytospergtherebro 2 года назад
You should demand a refund on your tuition if they taught you OCaml.
@oddmerlin9797
@oddmerlin9797 2 года назад
@@waytospergtherebro whats wrong with ocaml
@TheRevAlokSingh
@TheRevAlokSingh 2 года назад
@@waytospergtherebro if you can understand ocaml, no normal language can break you
@RandallStephens397
@RandallStephens397 Год назад
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!
@mCoding
@mCoding Год назад
Great to hear!
@Mutual_Information
@Mutual_Information 2 года назад
This channel is pretty damn advanced! Gives me more reason to not string-parse Python code again 😅
@mCoding
@mCoding 2 года назад
Me: patiently waiting the next advanced video from YOUR channel
@Mutual_Information
@Mutual_Information 2 года назад
@@mCoding Lol new one coming tomorrow in fact. I've been taking time away from writing/shoot/animating to read about Reinforcement Learning.. and why it doesn't work well (yet) in production. Not rushing this one. Would like to make a series that's useful and not totally redundant with what's out there.
@DavidCamperos
@DavidCamperos 2 года назад
This is mutual respect for each other 👍🤝
@falknfurter
@falknfurter 2 года назад
Matching XML, DOM and similiar structures is another application that comes to mind after watching this very nice video.
@erikgrundy
@erikgrundy 2 года назад
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
@JSaretin
@JSaretin 2 года назад
That's true, like checking if (x == 1) and pulling the answer from the statement like true or false You can also use if (is_true:= (x == 1)) and use the new variable to check against other conditions Probably not the most readable code.
@sebastianjost
@sebastianjost Год назад
That's exactly what the walrus operator, introduces in 3.9 is meant for. (See the other comment)
@6Sloth9
@6Sloth9 2 года назад
You're such a good teacher and your videos look absolutely great. Thank you for your work
@mCoding
@mCoding 2 года назад
You're very welcome!
@codahighland
@codahighland Год назад
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.
@calyodelphi124
@calyodelphi124 Год назад
Agreed. The terser syntax of switch statements is much easier to skim and read imo.
@DrVictorVasconcelos
@DrVictorVasconcelos 2 месяца назад
​​​​​@@calyodelphi124 100% that. It has the exact benefit of color coding. You know exactly what you're dealing with the moment you lay your eyes on one of those colors. I have no idea why people have been gaslighted into believing that switch is bad. It sounds very Apple-y "you don't need that feature" to me.
@farpurple
@farpurple 2 месяца назад
If you want to easily vhange compared variable, use some temporal variable.. patt = x if patt == case1: ... elif patt == case2: ... else: ...
@UnFallenRain20
@UnFallenRain20 2 года назад
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.
@pranavnyavanandi9710
@pranavnyavanandi9710 2 года назад
Hello. I'm a novice programmer, I know basics of C and am decent in Python. That said, can you tell me what really is the core difference between a compiled vs. an interpreted language? Because, in a compiled language, the code directly gets converted into machine readable code - which is then executed by the processor **line by line**. In interpreted languages like python, the source code is first converted into something called "bytecode" at once - that is, _compiled_ into bytecode, after which, the bytecode is executed again *line by line*. There really seems to be not much difference. Except that, the conversion of code to bytecode in case of interpreted languages makes the code portable, since the 'Virtual Machine' as I have heard, then converts the bytecode to machine code specific to that machine. Is it that the bytecode is converted line by line into machine code and then immediately executed before moving on to the next line of bytecode, is that the difference? Thanks.
@marcosm5772
@marcosm5772 2 года назад
A big difference is that python bytecode is not executed directly by the processor. A Python source file is just a high level way of generating instructions for another program: the python interpreter. And a C source file is just a high level way of generating instructions for the CPU. If you create a C source file or change a C program's source code, you need to recompile it (that is, you need to (re)generate the binary): nobody is going to do that for you. On the other hand, when you create or change a Python file, you don't need to compile anything (in the traditional sense of the term) because the thing that "talks" to the CPU (this is, the python interpreter) has not changed at all. c source -> ... -> instructions for the CPU python source -> ... -> instructions for the Python interpreter -> ... -> instructions for the CPU I think this is the key to your doubt: the python interpreter DOES NOT convert bytecode into machine readable code. Instead, this bytecode contains instructions for the virtual machine. The virtual machine just follows those instructions, executes them (side note: a line of python code does not translate directly intro one instruction for the virtual machine, so there is no such thing as a *line by line* interpretation). Try to think an extremely simple example. A C program that enters a while-true loop and prompts the user for one of 2 characters: d or t. If the user enters "t", the program prints the time on screen. If the user enters "d" the program prints the date on screen. Now the next step is to introduce a small modification on your program in such a way that instead of waiting for the user to input anything, it has the ability to process files with strings of "d"s and "t"s. Your program has become a (rather useless...) interpreter for a new kind of (rather limited...) programming language. Eventually, you can make your C program a little bit more useful by having it accept things like "1000000 t" and not force the user to actually type a million times the letter "t" on a file. Of course, your program gains complexity, it has to parse the file and discover its structure. A nice performance boost: once your program figures out what to do with a line like "100 t" in a file, it would be nice to save it for future use if the input file does not change (think `__pycache__` and bytecode....). In some way, you start "compiling" these files into simpler strings of "d"s and "t"s. But do not forget: these "d"s and "t"s are far far far away from being instructions the CPU can understand. hope this helps! it's a difficult thing to discuss in a youtube comment thread :D
@penguindrummaster
@penguindrummaster 2 года назад
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.
@SamusUy
@SamusUy Год назад
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.
@MagicGonads
@MagicGonads Год назад
you can recurse your match statements however
@samihani9629
@samihani9629 2 года назад
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"
@mCoding
@mCoding 2 года назад
Thanks for catching this! I even checked the docs, but in the docs the parameter name is "default" and it is not mentioned that the arguments are positional only, oops!
@fat_pigeon
@fat_pigeon 2 года назад
Yeah, it's really annoying that many built-in functions take positional-only arguments, even when users might reasonably want to explicitly use a keyword. Someone should write a PEP.
@TechSY730
@TechSY730 2 года назад
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.
@mCoding
@mCoding 2 года назад
I guess time will tell if people use it this way. I will be happy to change my mind if the community agrees it is a better switch. Apparently some of those integer-only optimizations might actually be on the way, that would be cool!
@dpcolombotto
@dpcolombotto 5 месяцев назад
If the purpose of this video was to explain where to use match statement, you failed it. I'm more confused than before.
@kylwatson9240
@kylwatson9240 2 месяца назад
Agreed. I would have liked a real life example of where on is better than the other
@Dunning_Kruger_Is__On_Youtube
@Dunning_Kruger_Is__On_Youtube 2 месяца назад
If you watched the video and you’re more confused about match statements, then maybe you should quit programming since this was quite straightforward.
@malteplath
@malteplath 2 года назад
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.
@qwerty11111122
@qwerty11111122 Год назад
It might make even more sense with Enum over strings if there is an a priori known finite number of cases
@klaus7164
@klaus7164 2 года назад
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.
@DrDemolition
@DrDemolition 2 года назад
I'm mind-blown every time I watch your videos, absolutely perfect. Keep it up, we need a lot more youtubers like you!
@iiiiii7503
@iiiiii7503 2 года назад
Really thank you for that pauses after explanation. So you don’t need to pause video to observe written code.
@user-hk3ej4hk7m
@user-hk3ej4hk7m 2 года назад
Wile I totally understand the value of using the switch statement, I think the imperative if alternative could have benefited from some early returns, not using the arrow anti pattern. Great video otherwise!
@mCoding
@mCoding 2 года назад
Good point! I actually considered whether to also compare against the early-return version that would be less indented, but I decided not to since it would require additional refactoring. In my opinion, the early return one is still less readable than the match, but let me know if you think otherwise!
@mrwensveen
@mrwensveen Год назад
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.
@lightless
@lightless 2 года назад
dont get me wrong, i like my lecturer, but i can easily learn more from this/youtube videos than sitting at a desk in a lecture with white lights making me tired. my lecturer and me talked over match case but you gave me more clarity on the topic thanks.
@mCoding
@mCoding 2 года назад
I find the most benefit from a live lecture is being able to ask questions.
@UnfamiliarPlace
@UnfamiliarPlace 2 года назад
2:35 On the other hand, adding a lookup for callbacks rather than enumerating them in code is sometimes a good way to achieve some forms of abstraction / extensibility that can't be achieved by simply listing out each case (same reason one would use a dictionary rather than individual variables)
@iMaxBlazer
@iMaxBlazer 2 года назад
That's called polymorphism in OOP paradigm. Please use it, and do not use switch case of function references.
@lamjeri
@lamjeri 2 года назад
@@iMaxBlazer Is using a dictionary of functions instead of huge elif statement really such a bad practice? It always seemed more readable and much more editable to me.
@thomaskolar90
@thomaskolar90 2 года назад
hard same, I pretty much always do this when possible. python is multi-paradigm, the fact that functions are first-class objects and we can easily use elegant FP patterns like this is awesome.
@mishikookropiridze
@mishikookropiridze 2 года назад
This is what i have been using, and is match more readable and maintainable .
@MagicGonads
@MagicGonads Год назад
@@iMaxBlazer were we in a language that makes use of code locality (cache misses and branch prediction misses can be avoided on typical use cases), it could be a huge hit to performance, so only use it when you explicitly need it as part of a library if performance is a concern (just saying be aware of its potential pitfalls)
@victornoagbodji
@victornoagbodji 2 года назад
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.
@darvil82
@darvil82 2 года назад
discord gang 😎 And yes, structural pattern matching is amazing, I'm so happy we got something like switch-cases, but infinitely better!
@no_fb
@no_fb 2 года назад
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.
@no_fb
@no_fb 2 года назад
it would be interesting to compare the performance of the match and the if solutions, but hopefully that's going to improve
@mcmaddie
@mcmaddie Год назад
0:36 'less indented' . sounds like python only problem. switch/case is _so_ much more readable than bunch of if/else statements even with elif.
@xelaxander
@xelaxander 2 года назад
Thanks, I actually learned quite a bit from this showcase.
@MrMaxtng
@MrMaxtng 2 года назад
Imo structural pattern matching is most useful in functional programming. This, in conjunction with recursive functions is what makes languages like Scala so interesting. It is then so much easier to parallelize and thus we get tools such as Kafka, Spark, etc.
@talideon
@talideon 2 года назад
I'd be careful not to confuse functional languages with languages with algebraic data types. While there's a huge amount of overlap between the two, it's the presence of ADTs where having pattern matching shines. Languages like Erlang that lack ADTs use tagged tuples to similar effect, so the end result is the same.
@yaiirable
@yaiirable 2 года назад
Err what's wrong with +=?
@MichalKoziatek
@MichalKoziatek 2 года назад
Wow, this is a first video of yours you mostly lost me 😅 Will have to rewatch but there are a lot of new concepts for me here
@fabiolean
@fabiolean 10 месяцев назад
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.
@GiveMeTheTacos
@GiveMeTheTacos 2 года назад
Everyone else's comments: "Ah yes. You are a genius. This video makes so much sense." Me: "....what the heck is going on...."
@angelorf
@angelorf Год назад
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.
@megasmileys6321
@megasmileys6321 2 года назад
“It is unlikely this performance improvement will be added” python in a nutshell
@talideon
@talideon 2 года назад
The point of this feature isn't performance, but readability and boilerplate elimination. Python 3.11 gives you a speed boost of ~40%, OTOH. So no, not Python in a nutshell. Python's speed is held back by its C API, and that's hard to fix without breaking stuff.
@maleldil1
@maleldil1 2 месяца назад
There's also my favourite aspect of match: exhaustive Enum checks. If you're not using Enums instead of strings (you know what I'm talking about), you should, and you get exhaustiveness checks for free by using match instead of if/else.
@mCoding
@mCoding 2 месяца назад
Do type checkers support this now!? I've been waiting since it came out!
@dhahrimohamedamine8657
@dhahrimohamedamine8657 Год назад
I have no idea what are you talking about. I'm still learning classes, but the videos is still enjoyable.
@ardenthebibliophile
@ardenthebibliophile 2 года назад
As someone without a formal CS background, I am quite lost as to the utility of the match statement, what the cst is, or why this code is more or less readable than the other. Yet still, I watched.
@lllIIlllI
@lllIIlllI 2 года назад
The cst and ast are both objects that help with working with program source code. Without them working with program source code is hard. Think about how hard it would be to find all the places x is assigned to in a string of python code. You could search through the string for 'x=' but then that would find "yx=2" as well, or even " 'x=2' " which is not an assignment but a string expression. If you have the cst or ast you wouldn't run into these problems. Both the cst and ast are tree representations of the source code. They are trees because of the nested nature of source code. Like you can have a number in a function call in an expression in a variable assignment. Ex: x = 3 * f(2) The cst and ast both make it easy to find the assignment to x. All you have to do is look through all the nodes and see if they are an assignment node and if so see if they are an assignment to the variable x. the ast for the above code would look kinda like assignment | expression | multiplication | \ number:3 function call:f | number: 2 The difference between the cst and ast is that the ast just cares about what was written while the cst also cares about how it was written. Things like the extra whitespace in "x= 2" would be ignored by the ast but included in the cst. This is why in the video he needed to use the cst, because what he was looking for was not just any tuple but a tuple written in a way signaling it was likely meant to be something different.
@MrTyty527
@MrTyty527 2 года назад
you may want to look at "meta-programming", I am learning too while the readability point is just compling with the zen of Python I guess
@no_name4796
@no_name4796 3 месяца назад
Honestly it's great that python added in their language one of the best feature of rust. Although what makes it so powerful in rust is the strong type system, which python lacks, so idk how it compare to the rust match
@timber2lease
@timber2lease Год назад
that was propably the worst example to show the benefits
@programaths
@programaths 2 года назад
It's also available in Godot ^^ Match is very useful whit data driven development. (i.e. your app behavior is described as data too)
@falxie_
@falxie_ 2 года назад
I wouldn't be surprised if they *did* add optimizations for match statements to make them like switch statements in other languages
@mCoding
@mCoding 2 года назад
We can hope! I honestly don't see why not in some specific cases except that Python doesn't usually place much emphasis on changing things for performance reasons. Would love to be proven wrong in 3.11 or 3.12!
@flisboac
@flisboac 9 месяцев назад
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.
@karigucio
@karigucio 2 года назад
The feature most languages lack is sum types primarily. Then pattern matching makes the most sense. I can't look at "match" in python differently than just as a flashy new syntax sugar that will make some new idioms emerge.
@talideon
@talideon 2 года назад
If I can pattern match on a type, I can tilt my head a little to the side (because Python's dynamically typed) and see type constructors for sum types. If Python were statically typed, the lack of algebraic types would be a real problem. Go, for instance, would suck so much less if it had sum types: imagine how much less clumsy its error handling alone would be...
@mcdolla7965
@mcdolla7965 Год назад
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
@Aang139
@Aang139 2 года назад
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
@sajjadhossan7972
@sajjadhossan7972 2 года назад
Always wait for you
@Firigion
@Firigion 2 года назад
2:00 regarding the use of a dictionary as a switch case, I think that when properly written, it can be more readable than a big if/elif/.../else block. You need the function names to be very declarative and define the dictionary inside the function. This would of course not be done for speed, since defining the dict inside the function is dumb for anything that needs to be called somehwat often, but I think that for an ammount of cases that is not too big nor too small, the following is really readable: def switch(x): switch_dict = { 0: do_0, 1: do_1, 2: do_2, 3: do_3, } switch_dict.get(x, default)() as long as the cases are not just integers, but explicit things, I think that my_condition: do_somehting is nicer to read than elif x==my_condition: do_something().
@waynezor
@waynezor 2 года назад
It's even better to match against enum cases
@MagicGonads
@MagicGonads Год назад
you can avoid re-creating the dict by assigning it as a member of the function directly after writing the function, so it still 'belongs' to the function def switch(x): return switch.dict.get(x, default)() switch.dict = { 0: do_0, 1: do_1, 2: do_2, 3: do_3, } also added a tail call return in case python ever optimises tail calls also now that it's a publicly accessible member of switch it could still be potentially extended by other parts of the code without having to replace the original function or mess with its dunders
@vinzent1992
@vinzent1992 Год назад
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.
@mCoding
@mCoding Год назад
Great questions! I made a video about the intricacies of the match statement that I think would clear things up for you ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE--gf4z3g71Mg.html
@omidgholami2594
@omidgholami2594 2 года назад
Thanks for this precise explanation of match statement.
@robertbrummayer4908
@robertbrummayer4908 2 года назад
Excellent video, James. I know pattern matching from Haskell and I definitely like it that they added this feature.
@mCoding
@mCoding 2 года назад
Thanks! Indeed, the pattern matching in haskell and a few other languages is listed as inspiration for the pep that introduced this feature to python.
@callbettersaul
@callbettersaul 5 месяцев назад
Quite sad it's slow tho. It noticeably slowed down my code when I changed a bunch of isinstance checks to a nice match-case.
@incremental_failure
@incremental_failure Год назад
I normally play videos at 1.25x or 1.5x speed. I tried it with your stuff and was immediately overwhelmed.
@mCoding
@mCoding Год назад
In your opinion, should I change any of: talk slower, increase breaks between sentences, or repeat myself more?
@incremental_failure
@incremental_failure Год назад
@@mCoding If anything, add a small break when going to the next example/paragraph, it will help digest the information. But really, that's what the pause button is for. I find your videos challenging enough that I have to go back more than a few times as the topics are not always easy to grasp. Talking slower probably wouldn't help as you'd need to artificially achieve this, it's best to do what feels natural.
@nollix
@nollix Год назад
That's because most people are just craftsmen, amateurs who picked up their knowledge through playing around and so their videos are easy and reflect the shallowness of their knowledge. mCoding is obviously a university-educated individual who actually remembers everything he learned, and so has true, properly deep knowledge in CS and math. Therefore, you have to actually think about what he's saying a lot of the time, especially if you're not super familiar with it. There is nothing wrong with this, and nothing to fix. In my opinion, his videos have the best possible balance between rigor and accessibility, given the subject matter. You're just not used to rigor.
@incremental_failure
@incremental_failure Год назад
@@nollix Not sure "university educated" is all that awesome nowadays nor that it's what makes his content so intense.
@nollix
@nollix Год назад
@@incremental_failure Don't listen to the foxes about their sour grapes. You basically cannot learn these topics with proper rigor without education unless you're a super self-motivated prodigy.
@tonispiip8054
@tonispiip8054 2 года назад
Good video, but I wish it had also tested against basic data types like nested dicts. From what I understand _ is only use able inside the case expression. But if you're not familiar with the node parser api, it can see like mayne it has some other comparison method, and that under the hood its just doing == and the comparison is done inside the node objects.
@talideon
@talideon 2 года назад
You can use _ everywhere already. Really, this just plain old destructuring assignment.
@frankgomes4184
@frankgomes4184 2 года назад
Damn! I learn something new with every one of your videos!!! Utmost respect for you!!
@thevalarauka101
@thevalarauka101 Год назад
I always thought of it like a regex but for Python objects, once I found out what it could do
@rollinOnCode
@rollinOnCode 2 года назад
Python got pattern matching? Awesome! Love it 😀 😍 ❤
@jursamaj
@jursamaj 2 года назад
Your _switch_dict could have been done with an array, avoiding the hash.
@mCoding
@mCoding 2 года назад
Good point! I suppose the switch dict would only be useful if your inputs are not consecutive ints. I'd love to see the performance comparison!
@Rajivrocks-Ltd.
@Rajivrocks-Ltd. 2 года назад
So basically the same as in F#, or am I mistaken?
@mCoding
@mCoding 2 года назад
The proposal lists C#, Elixir, Erlang, F#, Grace, Haskell, Mathematica, OCaml, Ruby, Rust, Scala, Swift, and Thorn as inspirations for the match in Python, so yes!
@vincentperrollaz5261
@vincentperrollaz5261 2 года назад
Excellent video. match feels closer to haskell than to c indeed...
@NoNameAtAll2
@NoNameAtAll2 2 года назад
finally a switch case video!
@zakyvids6566
@zakyvids6566 2 года назад
Hi there I’m new to python and found that your explanations are quite in dept and easy to follow for beginners. I was wondering would you be able to make a short python crash course that covers the basics to get started with thanks
@Cynthia_Cantrell
@Cynthia_Cantrell 2 года назад
Socratica has and excellent series of those: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-bY6m6_IIN94.html Enjoy!
@MrTyty527
@MrTyty527 2 года назад
you may want to start with some basic topics or applied-level topics first.. these are pretty non-essential
@mmxgn
@mmxgn 10 месяцев назад
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!
@sethbettwieser
@sethbettwieser 2 года назад
I get what the video is saying, but I'm still using it as a switch-case.
@mCoding
@mCoding 2 года назад
You are certainly welcome to do that :). Just curious, is the reason because you feel that it expresses the intent clearer? Or some other reason?
@sethbettwieser
@sethbettwieser 2 года назад
@@mCoding yes, to me a switch-case conveys that you have a specific intent, which if-elif-elif-else doesn't immediately do. I usually use them for things such as factories where I might need to create instances differently for different options, or for parsing text-based commands. It's also much more readable to me.
@thelosc2
@thelosc2 2 года назад
This might be a silly question, but I can’t seem te find how the words ‘match’ and ‘case’ get a color (aka get detected as a standard python word) in my code. I got python 3.10 and updated all my packages on atom, and if I manually indent and put the case match statement in the code will work. It’s just not detected and subsequently highlighted and auto indented, which really deters me from using it. This might be a stupid question, but I couldn’t find any info online about it and I’m looking at a working example right now. Anybody have a clue?
@niter43
@niter43 2 года назад
I'm not familiar with python ecosystem, but that sounds like syntax highlither/parser hasn't been updated yet. It's provided by Atom or one of its packages/addons for python support, not a part of python installation itself.
@mCoding
@mCoding 2 года назад
Yeah this sounds like an issue that would likely be fixed by updating atom or updating your python plugin for atom. It's possible the plugin doesn't support 3.10 yet, but its been a while since it was released so i would hope 3.10 is supported!
@alexanderoransky7601
@alexanderoransky7601 2 года назад
The "switch statement" use case was wanted for years. The pattern existed since K&R and it is a shame it took 30 years to finally include it in Python . The switch-case pattern is much much easier to read and maintain than the ugly if - elif - elif - else.
@codingcrashkurse6429
@codingcrashkurse6429 2 года назад
If your code has got this many if-else statements like in the example, you probably did not write good code anyway. There are plenty of ways to overcome this with classes or even with simple dictionaries. Edit: mCoding explains it pretty well at 1:56
@ansonmiu8464
@ansonmiu8464 2 года назад
Great video! The CST matcher example definitely reminds me of Clang libTooling’s AST matchers :)
@itsmanikandanraju
@itsmanikandanraju 2 года назад
Does clang lib python bindings works in windows?
@NoidoDev
@NoidoDev 10 месяцев назад
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.
@joeeeee8738
@joeeeee8738 2 года назад
I really appreciate the explanation. Always clear, although this doesn't look like the best real life example. I personally find it easier to read the second way as it explains in a more logic format what its trying to do, despite more code and more error-prone. Just by this video, pattern matching feels like regex, where you always need to explain what it does !!
@emilejetzer7657
@emilejetzer7657 2 года назад
Everyone knows Python’s switch-case is dictionnaires and the get method XD
@curtis6919
@curtis6919 2 года назад
The problem is you contradict yourself: originally you say that it's not a simple switch statement because that can be represented by a series of if-elifs--but then you show how the ast/cst can also be written by if-elifs. So it doesn't seem that the match statement is solving any issue that hasn't already been solved, but is only trying to make an alternative, possible cleaner way of getting around if-elifs. But using a match statement as a switch is also cleaner than a series of if-elifs--so your entire point is futile!
@mCoding
@mCoding 2 года назад
That the match statement does not add any new functionality to the language is not a contradiction. Python is turing complete, and therefore nothing added to the language does anything that could not already be done. The reason new features are added to the language is to make it easier to do things that could already be done, or to increase performance, readability, etc.
@cleverclover7
@cleverclover7 2 года назад
we're just gonna have to disagree on this one :) def not just for syntax trees. love your videos!
@mCoding
@mCoding 2 года назад
Hahaha of course, use whatever YOU think is clearest. Don't ever let a video tell you otherwise.
@jamhamtime1878
@jamhamtime1878 2 года назад
No one even uses switch cases the way they're meant to be used. The fallthrough is there by default for a reason. If you're just going to put break on everything, then just use ifs (the performance "benefit" is negligible for most use cases)
@talideon
@talideon 2 года назад
No, it's there because it was an easy way to implement things back in the '70s and enabled some clever coding, but subsequent to that, it's been nothing but an albatross around the neck of most people using switch statements as you rarely want to pass through, it's a pain to explain to beginners, and a common source of bugs. Every code base that I've had to deal with that uses them ends up with comments like "/* pass through */" all over the place to indicate the pass through was intentional. Sure, that's anecdotal, but I wouldn't be surprised if it's common, and that would be a strong indicator that an explicit "passthrough" keyword would've been a better option than making it the default.
@davea136
@davea136 Год назад
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.
@bigBlackBlocks
@bigBlackBlocks 2 года назад
When you always just used a dictionary to accomplish the switch statement but everyone else says they've struggled ....
@official_mosfet
@official_mosfet 3 месяца назад
Fun fact: the switch statment is slower than ifs, i did a test using timeit.
@MAlanThomasII
@MAlanThomasII 2 года назад
As someone who cut his teeth on digital humanities, where navigating and matching against complex semantic markup trees was the order of the day, this now makes sense to me.
@MagnumCarta
@MagnumCarta 2 года назад
How would you describe "digital humanities" to a layperson such as myself who has never come across that term before? It sounds quite interesting. Not as a career choice but just out of general curiosity (this is coming from a guy who reads papers on Pubmed [a medical database] because I have random thoughts like "how does capsaicin [the oil in chilies that makes them spicy] work?"). By the way the way capsaicin works is it interacts with a "protein channel" (a big ole hole in nerves that regulates the intake of electrolytes [sodium, potassium, and calcium] by getting wider or narrower) called TRPV1 or "Transient Receptor Potential Vanilloid 1". Capsaicin causes the TRPV1 channel to open up wider, thereby increasing the flow of electrolytes into the nerves which in turn causes the nerves to fire off signals to the brain that makes you experience a warming/burning feeling! ...You didn't really need to know that last part but perhaps it was interesting! By the way I am not a medical expert just a computer nerd with a penchant for eating spicy peppers no matter the amount of water loss in sweating!
@mnsosa
@mnsosa Год назад
the author is from my university. we learn using Haskell, so I guess that's the origin from this feature
@ufogrindizer5038
@ufogrindizer5038 2 года назад
Thank you, I haven't had the chance to sit with this new addition yet. I suspect it will be specifically handy when coupled with dataclasses, to provide more powerful pattern matching capabilities, no?
@michaelstreeter3125
@michaelstreeter3125 2 года назад
Python 3.10 learner here. In a nutshell you're saying don't use 'switch' instead of 'if elif else'; switch has a use, and this isn't it, correct? Apart from abstract and concrete syntax trees, are there any other good uses for switch?
@talideon
@talideon 2 года назад
You can use it as a switch statement if you like, but it's going to be a tad more verbose. This is just trying to make the point that it does much more than that. In my case, it's going to make the code for a whole bunch of finite state machines in my codebase a lot simpler to deal with.
@bartolhrg7609
@bartolhrg7609 Год назад
8:29 why not use "if not: cancel" pattern So, in this case "if not isinstance: return;"
@fuelformind
@fuelformind 2 года назад
I love the thumbnails man
@Adroitbit
@Adroitbit Год назад
That is some aggressive feature added right here
@SkrtlIl
@SkrtlIl 2 года назад
What is the issue with += ?
@delta3244
@delta3244 2 года назад
ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-cGveIvwwSq4.html
@delta3244
@delta3244 2 года назад
oh yeah right, bots provide comments in that format. The link I provided links to a video which explains why Python's += operator can act counterintuitively
@SkrtlIl
@SkrtlIl 2 года назад
@@delta3244 Thanks, didn't know about that. Also a quick shoutout to mcoding for not greedily using every opportunity to plug his own content (like this one or the hint saying the last video is not a prerequisite)!
@NoNameAtAll2
@NoNameAtAll2 2 года назад
TL/DW: can be either x=x+y or x.operator+=(y) first makes new object, second adjusts old one and you can't know which from the callsite
@mCoding
@mCoding 2 года назад
@skrt You are welcome. I guess it worked out in this case, but I didn't realize plugging my own content was a bad thing though! I would assume if you liked this video you would like my others too!
@aonodensetsu
@aonodensetsu 2 года назад
pattern matching is a cool feature in itself but using it as a switch is cool too
@brenoverissimo3846
@brenoverissimo3846 Год назад
Dude, I study python mainly for web. I havent understand or seen any of this stuff before... how advanced is this subject?
@XCanG
@XCanG 2 года назад
Your example is interesting, but where CST is using? I never heard about it in the first place, not that anyone write code in string to do something with it later.
@mCoding
@mCoding 2 года назад
If you've ever used a code formatter like black or the one built into your IDE, this is exactly what your code formatter needs to do. You can also use it for refactoring, e.g. rename all instances of the name x in this function to y. Think code that modifies other code!
@Llxr
@Llxr 2 года назад
Hey I'm sure you get asked this alot but would you ever consider making videos on rust?
@mCoding
@mCoding 2 года назад
I would love to but I don't know rust!
@Llxr
@Llxr 2 года назад
@@mCoding Me either! But I've been making my way through Programming Rust 2nd Edition. Pretty dense but my work keep mentioned rust so I thought I should learn it.
@sebastianandrade8500
@sebastianandrade8500 2 года назад
Does the Java switch works the same way as the C switch? (with these jump tables that he had mentioned)
@mCoding
@mCoding 2 года назад
It's up to the compiler to decide if it will use a jump table or not, in both Java and in C. If your cases are compile-time known nearly consecutive integers or enum values, it typically will turn into a jump table.
@sebastianandrade8500
@sebastianandrade8500 2 года назад
@@mCoding thanks for replying
@acasualviewer5861
@acasualviewer5861 Год назад
Structural pattern matching is most similar to what is done in languages like Prolog or O'Caml.
@bsheldon2000
@bsheldon2000 Год назад
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.
@qm3ster
@qm3ster 2 года назад
Does Python have `if let` yet? Because using a `match` to extract only a single case is frowned upon in the real world, for whatever reason.
@MrMaxtng
@MrMaxtng 2 года назад
With structural pattern matching you can catch several case in one statement.
@qm3ster
@qm3ster 2 года назад
@@MrMaxtng Yeah, which isn't what they're doing in this lint.
@DavidDLee
@DavidDLee 2 месяца назад
I don't think that adding CST into the explanation of match was a good idea, if you wanted to discuss match
@rollinOnCode
@rollinOnCode 2 года назад
Hell yes 🙌! Pattern matching to save the world!
@kacperkwasny3848
@kacperkwasny3848 Год назад
Thank you so much for all those videos!
@SolidBuildersInc
@SolidBuildersInc 2 года назад
I'm liking Case and Elif better. This Match, reminded me of the collage of voices in the beginning of the video. However, there may be advantages I have not considered... It must be a cleaner way. I am thinking an assinged index with Mathematical Induction for a solution.
@mr.norris3840
@mr.norris3840 2 года назад
Or just: Pattern Matching
@MidnightSt
@MidnightSt 2 года назад
oh, now I know how pattern matching looks in a language which has a syntax not made for pattern matching.
@KuroKazeZX
@KuroKazeZX 2 года назад
youtube random recommending a previous not-sub viewer of your vids gang
@terrynt
@terrynt 2 года назад
curious. why += is a wonky one?
@mCoding
@mCoding 2 года назад
I have a whole video explaining. Search for python's sharpest corner!
Далее
Python lists remember what you did to them
10:04
Просмотров 127 тыс.
مسبح السرير #قصير
00:19
Просмотров 2,1 млн
Woman = best friend🤣
00:31
Просмотров 3,5 млн
why are switch statements so HECKIN fast?
11:03
Просмотров 405 тыс.
Modern Python logging
21:32
Просмотров 180 тыс.
Metaclasses in Python
15:45
Просмотров 153 тыс.
C++ Developer Learns Python
9:26
Просмотров 2,7 млн
5 Tips To Write Better Python Functions
15:59
Просмотров 103 тыс.
Python Generators
15:32
Просмотров 135 тыс.
Compilers, How They Work, And Writing Them From Scratch
23:53