A Closer Look At Structural Pattern Matching // New In Python 3.10!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Would you be able to nest a match within? In the v3 example, rather than having two cases where you match your array of quit keywords with and without params, could you then match on *rest?

👍︎︎ 1 👤︎︎ u/ImageOfInsanity 📅︎︎ Jul 11 2021 🗫︎ replies
Captions
structural pattern matching it sounds like a component of the transporter of the uss enterprise but it's not it's a new feature of python 3.10 and it's pretty powerful just like the transporter and i'm going to show you today what you can do with it if you're new here you want to become a better software developer get a deeper understanding of programming in general start now by subscribing and hitting the bell so you don't miss anything structural pattern matching is new feature of python 3.10 that's coming out later this year it looks a lot like the traditional switch case statements that you find in other languages such as java or c switch statements are generally easier to read than long sequences of if else's however they might also point to issues in your design if you need long complicated switches or if else's to handle the different cases then you might be better off with the design pattern such as the strategy now structural pattern matching actually does way more than the simple switch statements because it allows for pretty complicated pattern matching i'm going to show you an example today today's example is a simple command line interface if you look at the code there's nothing there it's just an input that gets stored in a command and then i'm printing that command and doing that in an infinite loop let me run this program to see what happens so i can type anything i want and it just prints out the command and goes back again to asking for another command as you can see i've used pyenvy here to select the latest version of python actually the beta version of python 3.10 what i'm going to show you today is how you can use structural pattern matching to parse and interpret a variety of commands let's start with a very basic example where we're simply matching the command to a number of keywords so i'm going to add a function called run command and inside this function i'm going to use structural pattern matching to find out what command the user typed and we do structural pattern matching using the match keyword so i'm matching the commands and then you can use cases to identify the various cases that you want to handle so for example if case is quit i can print something like quitting the program and then let's also actually quit the program so that actually does something and now you can add lots of different kinds of commands to do different things let's add one more something like this obviously just doesn't do anything but just to show how it works and then finally we have a special case other which is the case that's gonna handle anything else there we go i'm using the r option here so that it actually also takes care of printing double and single quotes and those kind of things so now i have my run commands function that uses match and a variety of cases so instead of printing here i'm going to call the run command function now and now let's see what happens so first let's see what happens if i type reset i'm getting the reset message i can type anything and i'm getting the unknown command and when i type quit i'm quitting the program so this is a very simple example of using match with a couple of fixed cases and also being able to handle a default case so now let's do something a little bit more complicated because obviously when we're writing a command line interface you often want to provide some kind of argument and also being able to parse that argument so let's write a second version of this run command function that allows us to do a little bit more let's call that run command v2 that also gets the command as a parameter and we're going to use a match case again but this time we're not going to use the command directly but we're going to split the commands so that we get a list of the command and the arguments that you provide and now what you can do is really interesting that you can match this array that you got with various different cases let me show you what i mean so for example i could do this so here the case is that we're loading a file name and the file name is provided as a parameter and let's add another one again it's not really doing anything it's just to show you how it works what you can also do in this pattern matching system is that you can allow different varieties of a keyword and handle that in the same case let me show you what i mean so for example we had quit but maybe you also want to be able to write exit or buy and then let's just copy this over there we go and now if we type any of these three keywords then this case is going to match it now for completeness let's also add another case now when i just copy this is not going to look very nice because other is actually a split command so this is an array so actually i want to print out the command itself like this but now other is not used so we can replace this by an underscore because it's an unused variable and then this is the second version of the run command that we have so let me call that here there we go and let's run the program to see what happens so now i can write load example.pi or whatever and then it's going to write that it's loading that file or i can write exit which is one of these three cases that i mentioned here and then it's going to quit the program so this is really nice and there are more things you can do when matching lists for example let's say you want to add an option to the quit command that forces the processes that are currently running in that case we might want to add a parameter dash dash force now i could do it like this but now i'm only matching the case where you write the word and you write dashed as force so just writing the quit word doesn't work anymore so there's another thing you can do i can use the asterisk character and provide a rest value that's going to be the other elements in the array so this is going to match any list that starts with quit exit or by and then any other remaining number of elements in the list and what i can do now is parse the rest of this list to do something else depending on the value so now depending on the value of this rest list the remaining elements in the list i'm doing something else let's run this code one more time to see what happens so if i write quit then we're simply getting to this part of the if statement and if i write quit force then it's going to go to this part now we might want to add another option like minus f you also see that sometimes so now i can also quit force quit using minus f though this works we're not really using the full power of structural pattern matching now because pattern mass can do even more it can even handle these kind of if else statement inside the case definition so let me create a third version of run command to show you how that works just copy this over here and then let's create a v3 and what we're going to do now is we're going to use this if statement here and actually make it part of the case we want to copy this over and i'm going to put it here and now what you can do is print out this message if this is the case and this is also a condition that you attach to the case and let me create another case to handle the regular quitting that looks like this copy this over so now we have two cases we have a case where we have this quit exit and buying the rest of the parameters assuming that force or minus f is in the rest list and we have the regular quit command so let's replace the version 2 by version 3 and let's run this code one more time and check that this still works so if i do quit i'm getting the regular quit and if i type quit force then we're actually going to this case so this is nice you can add these conditions to cases and then be able to handle specific things as well so as you can see it is quite powerful but there's even more you can do with structural pattern matching let's create yet another version of run command and do something else entirely here we're relying on the command being a string and that was splitting that command you can actually use objects as well in pattern matching for example what we could do is create a class command that contains the command information and anything else that you like and then we can actually do pattern matching on the attributes of the object which is really cool so let's create a command class to do this and we're going to use a data class for this so i need an import the command class has a string which is the the actual command and we have the arguments which is a list of string and then i'm also going to need to import list there we go now we're going to update the main function to actually create an instance of this command class that we just made and the first thing we need to do is we need to split the input a bit differently so let's create a command and arguments and we're going to read that from the input just like we did above but now we're going to split the input in here now we could use the regular split function to do this like so but there's also an sh lex library that does simple lexical analysis that does better job at splitting commands it can also take care of things like comments and other command line specific things that you want to do maybe like files that are put in quotes and stuff like that and it takes care of that as well so let's use that and i'm going to import it here first and then there's nothing else we need to do except call the split function from sh lex and pass it the input so then this is what you get so we have our command we have the arguments i can remove this first line actually and now what we can do is create a command and then run that command so for that i'm going to create yet another version of run command that doesn't accept a string but a command instance so this is a command instance and that's not defined because i need to define the class over here obviously and now what we can do we're going to do a match to the command because we have an object and then we can handle different cases based on the value of that object and i'm going to show you in a minute what that looks like i think i forgot to copy this over as well that belongs to the class obviously there we go now i'm gonna run the fourth version and what i need to pass it is a command instance that gets the commands and the arguments that we got from the sh lex split function now let's look at the structural pattern matching mechanism for objects like command over here so in this case what you can do is provide a special syntax to match objects for example if i want to replace this case of loading a file name by an object case i can do it like this so now we're matching a command object where the command is load and the argument is a list containing the file name and let's do the same thing for saving similar for quitting we can actually replace this case now by a object match and this is what that looks like so we use the same mechanism here for the various options that match the command and arguments is an array that contains either force or minus f and possibly other commands as well i can remove this case and in this case it's going to print out this as usual and then the final case we can make that as well using objects and that looks like this and now let's run the program again and see whether that still works as we expect so we have our command line i can load a file save a file i can quit simply quits the program and when i do minus force it's going to this case and obviously minus f works as well so as you can see you can do really quite a lot of things with this structural pattern matching and as you see with the object syntax here you can actually use nested patterns where we're first matching a command and arguments and then inside we're matching values again and that gives us a lot of power in designing what we should do depending on the value of that command so overall i think structural pattern matching is a really neat new feature of python 3.10 but there are a few caveats that you should know about the first is that these cases are run from the top to the bottom and that means that the order in which you put them has effect on what is happening for example here i'm first handling this complex quit case and then i'm handling the simple case if i would turn that around let's say i put this one above this one then the behavior is going to change let me show you what i mean so let's run this program again and now if i write quit we're going to get the regular behavior that we expect but if now i write quit force then we're also simply quitting the program and that's because even though there are arguments to the command this command actually matches so it's simply quitting the program and it doesn't even go to this case at all so that's something you need to think about when you define these cases are they in the right order and that leads to second caveat and this has to do with the match command looking a little bit like the switch command in other programming languages and switch command it's by some people it's also called the wicked switch because it tends to lead to bad design decisions when you use it one problem is exactly this that the order matters and the second thing is that if you have many of these different cases that you put below each other then your function starts to lose cohesion overall i do think it's a really powerful feature and in particular the pattern matching is really nice now next to structural pattern matching python 3.10 also has a couple of other interesting features for example there is a shorter syntax for union type so instead of having to write the word union you can actually use these or characters here that you also see that i use there in this code which really shortens the code a lot and in my opinion makes it a lot cleaner so i really like that so i hope you like this example post a comment to let me know what you think about it and if structural pattern matching is something that you're going to use in your code as well if you haven't joined our discord server yet here's the link it's become a really fun nice community so i hope you join us there thanks for watching take care and see you next time [Music] you
Info
Channel: ArjanCodes
Views: 77,196
Rating: undefined out of 5
Keywords: structural pattern matching, python 3.10, pattern matching, whats new in python 3.10, python tutorial, python 3.10 new features, match statement, pep 622, pattern matching python, python 3.10 pattern matching, python 3.10 switch, python 3.10 features, python 3.10 match, python 3.10 case switch, match statements require python 3.10 or newer, pep 6220, match statement vs switch, Structual pattern matching
Id: scNNi4860kk
Channel Id: undefined
Length: 17min 11sec (1031 seconds)
Published: Fri Jul 09 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.