First off: Thank you for your videos .. Keep them coming! You taught me a lot, already and I like your style. Constructive input: The "more space for displaying the code"-thing could be even more positive, if you increased the font-size. I can't watch your videos from the couch. I have to sit directly in front of the monitor (fine for a "type-along and we'll build e.g. a snake-game"-type of video .. but for binge-watching "I'll explain a concept or new language-feature"-videos, I'd prefer to be lazy and watch from the couch (as we all know: lazy === good). Or maybe you could zoom in/out, depending on what makes sense at that moment .. e.g.: - Very big font for looking at the currently interesting few lines of code .. - Zoom out, until all the relevant code is visible, whenever the context is needed. I'll continue watching your videos, whatever you decide to do/not to do .. and I don't know, what other viewers think about this .. it's just my opinion. Cheers :)
Idea for a future series: Go through a module, for example pathlib, and breakdown the inner workings. There is so much to learn from the professionals who write production grade code.
Honestly, love this addition to the language. Originating from C and being a procedural programming junkie myself, I missed the equivalent of a switch statement in Python and dreaded writing long-winded if-elif-else statements, so I'll def be using match a lot
I'm new to switch and match but Im going to start only using them to get practice
3 роки тому+14
Before this, I often used dictionaries to map from some string (like the command name) to a function to call. Usually this leads to quite a nice design, especially considering that you can build that dictionary in various ways. You can make classes register which command they should be instantiated for, for example.
@ Hey, Dr. Stüvel! Big fan of your work! I have also used dictionaries in this way before and I can say, in some cases it produces way cleaner code. For example, often in C, I would use a switch to create a mapping between one value to another and all I would have in a case's body would be an assignment expression, followed by a break statement. That can be written way cleanly in Python with the use of a dictionary and I still wouldn't refactor that as a match whenever I upgrade to 3.10. However cases where the dict maps to functions, it kinda feels like a hack, especially whenever some functions take different parameters and I have to wrap them with lambdas, it kinda reminds me of how some JavaScript APIs abuse the use of callbacks and I don't really like it
I skipped this video when it came out, because I wanted to watch it when I start using Python 3.10. But somehow UA-cam stopped recommending me your videos (have been watching one every day for the last weeks) - so I decided to go to your channel and browse the videos by myself. Turns out: this is the only one I haven't watched yet. Great job!
The amount of work goint into these videos is astounding. I am so happy that I have found your channel, there are so many ways one can write cleaner code but it's always explained a not easy to understand way, unlike here. Thank you for your awesome videos!
Great video. One huge opportunity is to follow the functional programming patterns of returning tuples of values from functions and matching results. Eg. function `def do_foo()` returns (ok: bool, reason: str, data: dict) . By using structural pattern matching you can write cleaner and intuitive invocation code. Once I get my code base moved up to 3.10+, I'll be using this heavily. T hanks for the great videos!
alternative: a dict where the keys are commands and the values are function pointers which handle the rest of the input. As demonstrated beautifully in Mike Pirnat's "Dungeons & Dragons & Python", one of my favourite conference talks "quit" and "exit" and "bye" all invoke the same function, in its own submodule elsewhere, which decides how to deal with "--force" or "-f" etc
what a great implementation of the classical Switch statement offering much versatility. As i am not a big fan of the argparse module, this certainly makes my life easier in the future.
Arjan I recently discovered your channel and honestly your way of expressing whatever the idea on your mind is very precise and neat. Me and my friends also have a channel for educational content mostly on software and your channel really re-inspired me. I have spent lots and lots of hours on UA-cam trying to find good quality and fun content on topics like these and you are golden. Thank you. Can't wait to see more of your content!
Another great video. Thank you for so many examples in a series to show the features and always appreciate the high audio/video production quality of your videos and I love your choice of background and lights.
Best tutorials on Structural pattern matching.... Thanks 🙏🙏🙏 After this tut, dev will use it for complex it-else, Waiting for V2 of it, with regex & using async task group on functions part of each case
finally switch command in python.. one of the most comfortable programming languages without switch sounded bad. Thanks for this tutorial and to see you in the next one ;)
I've learned that switch/case statements have their place in factory methods where different inputs lead to the creation of different classes. I think that's where this tool might become useful as well because you don't depend on switching over a primitive value like a string or an int.
Thank you!! Beautifully explained. You are a gifted teacher. I previously watched another video on this topic and was baffled. After your video I feel primed for the 3.10 release.
This was really helpful. How about a special on how to use it for minimal unique string matching when parsing commands and arguments, e.g. A - A*dd, Beg - Beg*in, Bef - Bef*ore, etc.
I just came across your channel for first time and I LOVE IT!!! Thank you so much for your videos! I'm a Python Developer too, who is learning Scala and I'm also a UA-camr 😂 So Hi Five for all our matching !!! 😂 saludos from Argentina 🥰
Hi, as someone who writes both a lot of Haskell and a lot of Python code, this is super interesting. One question, in run_command_v4 function, in the `--force` case, your code matches only arguments, that start with `--force` or `-f`. In the other versions the order did not matter. Is there a way to compare fields of objects not only by equality, but by any boolean construct (like `in`), as you did in the run_command_v3? Anyway super interesting, thanks for showing us :)
You can add a condition to a case when you're matching objects, like so: case Command(command="quit" | "exit" | "bye") if "--force" in command.arguments or "-f" in command.arguments: ... I don't think this is very readable though. It would be nice to have the possibility to write something like "--force" | "-f" in arguments in the case itself.
Very interesting. For the object pattern matching, is it actually instantiating a new object for every case check? Wondering whether this would have performance implications for classes with expensive constructors.
Great tutorial @arjan. One question. In your first example, you used None to mention the return type of the methods without any return. Is this the standard/preferred way? I don't really mention it if there is no return. Thank you.
Neat! One more question please, i think you didn’t said it explicitly; okay the case has an order importance, but if i dont qui the program as you do with quit() , may i go by many case or only one is possible as the elif statement ? Thanks i hope i could currently use python 3.10 its dope!
Question. at 9m34 looking at version 3 of the command. Comparing the "with --force" case with the "no force", the print statements are different, but the next command is quit() in both cases. Not seeing how the behaviour will actually be different.
Hi! I have just been introduced to your channel and I wanted to ask - how shall I navigate your videos from more like beginner level to advanced? Do you actually have videos for python beginners? Thank you!
Would it make sense to test for something like "quit" with the simple case and then put the rest of the complexity into that case, possibly by switching again? It seems like this would spread the complexity out in a more orderly way and make it easier to read.
Can someone explain how the pipe character is used in python? It seems like Arjan is using it here as a logical OR, but I can't seem to get that functionality out of it in other settings.
Nope. The usual argument is that a switch doesn’t provide anything new compared to a simple if-elif-else chain. Structural pattern matching, however, is way more powerful than a simple switch, enough to justify adding it to the language.
8:58 I'm not a big fan of v3 with two "case" clauses for handling same "quit" | "exit" | "bye" - repetition which could be error prone if you add "f*k off" as a 4th exit option but forgot to update all cause lines. This might be especially painful when you have more "--" options.
In v4, why did you use command as the variable for the match statement along with command being an element of the Command class? Doesn't overuse of the word command like that muddy the water for anyone reading it?
*Camera accidentally switches off* Arjan: Sorry for the camera, I'll try to put a positive spin on it. Me: Finally! Me and my ADHD brain can actually focus on the code being written, instead of constantly getting distracted!
Haven't tested that, but it's an interesting question. I don't expect the performance hit to be that big though, since accessing instance variables in an object should be pretty fast.
Was asking the same... docs.python.org/3/library/string.html#grammar-token-format-string-conversion. It's a conversion flag: r=repr(), s=str(), a=ascii().
Graag gedaan Arjan! Echt top dat je naast nieuwe Python features ook focussed op klassieke Design Patterns en andere boeken van oa Gang of Four. Keep up the great content! You Rock!
Hi Arjan, well explained, thank you. At least for me, your videos are the perfect middle between too little and too much information. Owned yourself a sub! Groeten uit Groningen :-)
What does the '|' do on string ? When I try outside of a match (e.g. : "a" | "b") in a python 3.9 cli I get an unsupported operand, does that mean the match syntax is different from "standard" Python and we will have a new syntaxe, adding a layer of complexity ?
The `|` in Python has a few meanings depending on context. It can be a set operation to form a union of two sets, e.g. set(["apple", "banana"]) | set(["pear", "cherry", "apple"]) == set(["apple", "banana", "pear", "cherry"]) I think in Python 3.9 it was extended to also work on dictionaries in a similar fashion. So it's used as a "Union" operator. It can also be a bitwise OR if used on binary data. Python 3.10 extends the idea to replace the `Union` type with a simpler `int | str` type syntax -- instead of `Union[int, str]` and also uses it in the context of case statements to mean "one of these"
Too bad my camera decided to switch off near the end. It probably couldn't handle the awesomeness of structural pattern matching 😎.
First off:
Thank you for your videos .. Keep them coming!
You taught me a lot, already and I like your style.
Constructive input:
The "more space for displaying the code"-thing could be even more positive, if you increased the font-size.
I can't watch your videos from the couch.
I have to sit directly in front of the monitor (fine for a "type-along and we'll build e.g. a snake-game"-type of video .. but for binge-watching "I'll explain a concept or new language-feature"-videos, I'd prefer to be lazy and watch from the couch (as we all know: lazy === good).
Or maybe you could zoom in/out, depending on what makes sense at that moment .. e.g.:
- Very big font for looking at the currently interesting few lines of code ..
- Zoom out, until all the relevant code is visible, whenever the context is needed.
I'll continue watching your videos, whatever you decide to do/not to do .. and I don't know, what other viewers think about this .. it's just my opinion.
Cheers :)
Arjan > Netflix
Idea for a future series:
Go through a module, for example pathlib, and breakdown the inner workings. There is so much to learn from the professionals who write production grade code.
10:35 since you're explicitly working with Pyton 3.10, you can just use list[str] instead of the typing import. Same with dict, tuple, set etc.
Honestly, love this addition to the language. Originating from C and being a procedural programming junkie myself, I missed the equivalent of a switch statement in Python and dreaded writing long-winded if-elif-else statements, so I'll def be using match a lot
I'm new to switch and match but Im going to start only using them to get practice
Before this, I often used dictionaries to map from some string (like the command name) to a function to call. Usually this leads to quite a nice design, especially considering that you can build that dictionary in various ways. You can make classes register which command they should be instantiated for, for example.
@ Hey, Dr. Stüvel! Big fan of your work! I have also used dictionaries in this way before and I can say, in some cases it produces way cleaner code. For example, often in C, I would use a switch to create a mapping between one value to another and all I would have in a case's body would be an assignment expression, followed by a break statement. That can be written way cleanly in Python with the use of a dictionary and I still wouldn't refactor that as a match whenever I upgrade to 3.10.
However cases where the dict maps to functions, it kinda feels like a hack, especially whenever some functions take different parameters and I have to wrap them with lambdas, it kinda reminds me of how some JavaScript APIs abuse the use of callbacks and I don't really like it
You took the words out of my mouth @THE JOB COMPANY
@@TheJobCompany totally agree with you
typing.List[T] => list[T] since python 3.9
Yes, realized that too. I’ll use the built-in types for my next examples.
I skipped this video when it came out, because I wanted to watch it when I start using Python 3.10. But somehow UA-cam stopped recommending me your videos (have been watching one every day for the last weeks) - so I decided to go to your channel and browse the videos by myself. Turns out: this is the only one I haven't watched yet. Great job!
Rust programmer: welcome to the club! This is an amazing language feature.
Agreed!
Swift programmer: ditto
Brainfuck programmer: guys what's this 'if' I keep hearing about?
Just starting to master structural pattern-matching in Scala and it's good to see it coming to Python 3. Loving your videos.
Thanks so much, Iain!
The best structural pattern matching tutorial I've watched.
The amount of work goint into these videos is astounding. I am so happy that I have found your channel, there are so many ways one can write cleaner code but it's always explained a not easy to understand way, unlike here. Thank you for your awesome videos!
Thank you, glad you like the videos!
Thank you so much for the explanation! Structural Pattern Matching is more powerful than I imagined and I can't wait to try it out!
You are so welcome!
Great video. One huge opportunity is to follow the functional programming patterns of returning tuples of values from functions and matching results. Eg. function `def do_foo()` returns (ok: bool, reason: str, data: dict) . By using structural pattern matching you can write cleaner and intuitive invocation code. Once I get my code base moved up to 3.10+, I'll be using this heavily. T hanks for the great videos!
I have learned more from 10 arjan videos that i have from any other source on python. another great video this.
Thanks so much, Chris glad the content is helpful!
This new version is looking promising! I've been waiting for this feature for so long. 😂
I appreciate your content, man. Keep up the good work!
Thanks Douglas, glad you like it!
Yeah, this is such a fundamental feature that python has been lacking.
alternative: a dict where the keys are commands and the values are function pointers which handle the rest of the input. As demonstrated beautifully in Mike Pirnat's "Dungeons & Dragons & Python", one of my favourite conference talks
"quit" and "exit" and "bye" all invoke the same function, in its own submodule elsewhere, which decides how to deal with "--force" or "-f" etc
That is the Pythonic way to do a simple switch. The new structural pattern matching is meant for more complex situations.
Finally a switch case ... My day is saved. I always used an external switch package as a standin
what a great implementation of the classical Switch statement offering much versatility. As i am not a big fan of the argparse module, this certainly makes my life easier in the future.
Switch case in python is something that I've been waiting for so long. Your tutorials are amazing by the way.
Arjan I recently discovered your channel and honestly your way of expressing whatever the idea on your mind is very precise and neat. Me and my friends also have a channel for educational content mostly on software and your channel really re-inspired me. I have spent lots and lots of hours on UA-cam trying to find good quality and fun content on topics like these and you are golden. Thank you. Can't wait to see more of your content!
Thank you so much! I'm happy you're enjoying the content!
Another great video. Thank you for so many examples in a series to show the features and always appreciate the high audio/video production quality of your videos and I love your choice of background and lights.
Thank you, I'm happy you enjoy the videos!
Best tutorials on Structural pattern matching....
Thanks 🙏🙏🙏
After this tut, dev will use it for complex it-else,
Waiting for V2 of it, with regex & using async task group on functions part of each case
finally switch command in python.. one of the most comfortable programming languages without switch sounded bad. Thanks for this tutorial and to see you in the next one ;)
Wished I have this channel so much earlier in my career!!
Hi 👋... Your videos are really good and very smooth . Can you please make a video on Mixin classes and when to use them . Thanks 👍
I've learned that switch/case statements have their place in factory methods where different inputs lead to the creation of different classes. I think that's where this tool might become useful as well because you don't depend on switching over a primitive value like a string or an int.
cool video thx, maybe a side by side comparison of the 3.10 and the previous version would be nice.
decidedly the best tutor on UA-cam
I appreciate the kind words, John! Thank you :)
Thank you!! Beautifully explained. You are a gifted teacher. I previously watched another video on this topic and was baffled. After your video I feel primed for the 3.10 release.
Glad it was helpful, Dovid!
This was really helpful. How about a special on how to use it for minimal unique string matching when parsing commands and arguments, e.g. A - A*dd, Beg - Beg*in, Bef - Bef*ore, etc.
This looks amazing for beginners that want to be able to easily parse input, or perhaps even files (by looping over lines).
I just came across your channel for first time and I LOVE IT!!! Thank you so much for your videos!
I'm a Python Developer too, who is learning Scala and I'm also a UA-camr 😂 So Hi Five for all our matching !!! 😂
saludos from Argentina 🥰
Your content is great, keep up the good work!
I just love to watch your videos when eating breakfast or just chilling after a hectic workday.
A suitable breakfast item would be (fruity) loops ;).
I think the maintainers of argsparse are going to be very happy with this. Big refactor though!
Learned Scala 5ish years ago and starred working with it, since then I get deja vu every time I see a new feature of another language being released.
Yeah, programming languages definitely get inspired by other languages all the time. (which is a good thing actually)
@@ArjanCodes Of course, I am just saying that Scala was quite the inspiration to many of them and doesn't always get the credit it deserves.
I've been enjoying your library of videos! Keep it up
Thanks, will do, Nicholas!
Having tried Rust after Python, it's a feature I was missing. Glad to see it coming to Python as well.
Quite a useful new feature, can't wait to try it out!
Agreed! Same here :)
I just studied functional paradigma applyin it to oCaml and i love this new feature
Great content. Very helpful for new Python programmers.
Commenting for UA-cam algorithm. Greate content!
Thank you!
Hi, as someone who writes both a lot of Haskell and a lot of Python code, this is super interesting. One question, in run_command_v4 function, in the `--force` case, your code matches only arguments, that start with `--force` or `-f`. In the other versions the order did not matter. Is there a way to compare fields of objects not only by equality, but by any boolean construct (like `in`), as you did in the run_command_v3?
Anyway super interesting, thanks for showing us :)
You can add a condition to a case when you're matching objects, like so:
case Command(command="quit" | "exit" | "bye") if "--force" in command.arguments or "-f" in command.arguments:
...
I don't think this is very readable though. It would be nice to have the possibility to write something like "--force" | "-f" in arguments in the case itself.
your videos are always very interesting. thank you !
Very interesting. For the object pattern matching, is it actually instantiating a new object for every case check? Wondering whether this would have performance implications for classes with expensive constructors.
much appreciated how you explain things!! Thanks again.
My pleasure! Glad you liked it!
Woooohooooo, anotther great video! However, I am not quite sure how much I will actually use this feature, let's see.
At 15:00 you mention that the order is important. This also applies to a if-elif-else construct.
Also I think you need some structural hair gel :)
hahhaha! I agree :)
Nice video. Don't you think adding OOP in the "run_command_v4 function is a bit overkill?
This reminds me of Elixir pattern matching, very cool!. BTW How about a comparison between `pyenv`, `pipenv` and `python -m venv`?
Thanks, man! Very clearly explained!
i already have router functions that basically do this with nested ifs and calling other functions, this will clean that up nicely :D
Great tutorial @arjan. One question. In your first example, you used None to mention the return type of the methods without any return. Is this the standard/preferred way? I don't really mention it if there is no return. Thank you.
This is pure magic… especially when objects get involved.
Yeah... I'm curious to see what use cases people come up with for this feature.
Thank you so much for the video, it was absolutely flawless.
Glad you enjoyed it!
Your videos are incredoble bro, nice job
Glad you like them, Eduardo!
Neat! One more question please, i think you didn’t said it explicitly; okay the case has an order importance, but if i dont qui the program as you do with quit() , may i go by many case or only one is possible as the elif statement ? Thanks i hope i could currently use python 3.10 its dope!
great job Arjan
Question. at 9m34 looking at version 3 of the command. Comparing the "with --force" case with the "no force", the print statements are different, but the next command is quit() in both cases. Not seeing how the behaviour will actually be different.
Very nice feature. Thank you
Thank You, Glad you like it.
Great video as always!
Glad you liked it!
Can you match by type and tuple, sorta like Scala's match?
Hi! I have just been introduced to your channel and I wanted to ask - how shall I navigate your videos from more like beginner level to advanced? Do you actually have videos for python beginners? Thank you!
Can you match a REGEX with this?
But is'nt it slower than if/elif/else? Or should I just use polars/panda/numpy for the heavy duty computing?
Would it make sense to test for something like "quit" with the simple case and then put the rest of the complexity into that case, possibly by switching again? It seems like this would spread the complexity out in a more orderly way and make it easier to read.
Just patiently waiting for Python to turn into Easy Haskell
Can someone explain how the pipe character is used in python? It seems like Arjan is using it here as a logical OR, but I can't seem to get that functionality out of it in other settings.
Wait, has python not had a switch statement equivalent for all this time and I never noticed? lol
nope :D
Nope. The usual argument is that a switch doesn’t provide anything new compared to a simple if-elif-else chain. Structural pattern matching, however, is way more powerful than a simple switch, enough to justify adding it to the language.
The closest Python had was that you used a dictionary, with the keys being tha cases, and lambda functions as values.
8:58 I'm not a big fan of v3 with two "case" clauses for handling same "quit" | "exit" | "bye" - repetition which could be error prone if you add "f*k off" as a 4th exit option but forgot to update all cause lines. This might be especially painful when you have more "--" options.
Fantastic video!
Thank you!
In the first example why did you use the ! in the "other" case?
@13:30 why use an array for the arguments? Is that just personal preference?
In v4, why did you use command as the variable for the match statement along with command being an element of the Command class? Doesn't overuse of the word command like that muddy the water for anyone reading it?
You are the best content creator for programming, love your channel
Cheers from Brazil
Glad you enjoy it!
*Camera accidentally switches off*
Arjan: Sorry for the camera, I'll try to put a positive spin on it.
Me: Finally! Me and my ADHD brain can actually focus on the code being written, instead of constantly getting distracted!
Keep up the good work, I appreciate the effort :)
Much appreciated!
What's that "other!r"? I don't recognise that use of the exclamation mark or what the r does.
Can this be used for factory pattern?
Actually, you don't need to import typing List and use more convenient and beginner-friendly 'list[int]' syntax!
Should i just stop bothering with learning if/else statements then?
I don’t think this will replace if-else statements. For simple branching by checking a condition, if-else is shorter than structural pattern matching.
I wonder, how does the object based matching affect performance/memory usage compared to the other alternatives?
Haven't tested that, but it's an interesting question. I don't expect the performance hit to be that big though, since accessing instance variables in an object should be pretty fast.
Oh wow I really want JavaScript to have this too
Agreed :).
¡Gracias!
Thank you very much! Glad you liked the video.
Thanks for this.
My pleasure!
what is difference between using IF/ELIF and case?
When there are a lot of options, case is easier to read. They do the same job.
Is this the new best way to keep track of states in an application?
Probably not. Orthogonal concept.
"Structural Matter Patching", eh
I need one of those signs to be behind me in Teams calls
What does the !r do in the string interpolation?
Was asking the same... docs.python.org/3/library/string.html#grammar-token-format-string-conversion. It's a conversion flag: r=repr(), s=str(), a=ascii().
Neat!
I'm pretty new to this channel. Is that some inside joke you put on the wall (STRUCTURAL MATTER PATCHING)?
I thought it would be fun, but I’ve actually stopped with the letter board since a while.
Surprised that there isn't a case statement in Python... why do I remember learning it? Maybe that was Javascript or something...
Thanks!
Thank you so much, Tony!
Graag gedaan Arjan! Echt top dat je naast nieuwe Python features ook focussed op klassieke Design Patterns en andere boeken van oa Gang of Four. Keep up the great content! You Rock!
Structural Matter Patching
More pydantic tutorials?
Hey do you have Odysee channel? I love these videos
Please, tell me you can implement duff's device in Python! XD
Make It So... Engage!
You can never not have enough Star Trek references... Live long and prosper!
I particularly like “shut up, Wesley!” ;).
@@ArjanCodes die arme Wil Wheaton heeft daar na 34 jaar nog trauma’s van. Iedere conventie waar hij komt roepen mensen: “Shut up Wesley!”
Hi Arjan, well explained, thank you.
At least for me, your videos are the perfect middle between too little and too much information. Owned yourself a sub!
Groeten uit Groningen :-)
Glad you like them, Thijmen! Ik ben overigens geboren in Groningen (niet de stad maar provincie).
What does the '|' do on string ? When I try outside of a match (e.g. : "a" | "b") in a python 3.9 cli I get an unsupported operand, does that mean the match syntax is different from "standard" Python and we will have a new syntaxe, adding a layer of complexity ?
The `|` in Python has a few meanings depending on context. It can be a set operation to form a union of two sets, e.g. set(["apple", "banana"]) | set(["pear", "cherry", "apple"]) == set(["apple", "banana", "pear", "cherry"])
I think in Python 3.9 it was extended to also work on dictionaries in a similar fashion. So it's used as a "Union" operator.
It can also be a bitwise OR if used on binary data.
Python 3.10 extends the idea to replace the `Union` type with a simpler `int | str` type syntax -- instead of `Union[int, str]` and also uses it in the context of case statements to mean "one of these"
Yeah but it's just the __or__ operand, here it seems different
Watering your flower
How to use 3.10 in anaconda