5 Tips To Write Better Python Functions

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
this video was brought to you by IND dentle IO learning python Made Simple how's it going everyone in today's video I'm going to be showing you five tips and tricks that can help you write better functions in Python and for the very first tip imagine you have some sort of function that does something such as connect and that can connect to the Internet or to some sort of database and probably the first thing you learn to do in Python is to insert the pass keyword for anything you don't want to create the functionality for just yet the problem with this approach is that if you do this for a lot of functions and you later forget that you've done this for any of your functions you're not going to get any information back when you run your script so those errors are going to pass silently which in small programs probably won't be an issue but as your programs grow in complexity this can become a huge issue so as a pro tip I recommend you never pass in pass or ellipses as a a placeholder for functionality that you need to take care of later instead you should raise a not implemented error because here you can explain exactly why you didn't implement the functionality here and optionally you can also specify a message such as connect is missing code in this case this could probably be considered redundant because not implemented States just that but maybe you have other useful information regarding why you did not implement it just yet yet anyway the next time we call this function in our program we're going to get this not implemented error that tells us that we did not Implement that functionality and that's just going to save us the trouble from scratching our heads and wondering why we're not getting a return from our connect function tip number two specifying return types why would anyone want to do such a thing well to better explain that I'm going to create a function called get users and here we're going to simulate that we have some sort of data base of users and that's going to be a dictionary of type int to string because it's going to contain the ID of one with the value of Bob the ID of two with the value of Jeff and the ID of three with the value of Tom and I honestly always make this mistake I use a comma instead of a colon and python usually complains and directly under that I'm going to return these users and for now ignore this warning this is just my pel me that I did not specify a return type and that it's not happy but otherwise the function works just fine if we were to print get users we would get our users back there's no problem there but using this function isn't as straightforward as it looks we do have to do some digging to understand what it actually does and what it actually returns with intelligent code editors you can just hover over the function and see what type it returns and that's great if you're using the function but if you are reading the code or reading the function declaration it can be much more complicated to understand what this returns this here is quite an unrealistic example of returning a type directly I mean obviously we could have just returned it like this and that would have worked just fine but again we get no context here of what we are returning to actually see what we're returning we either have to read the return type explicitly or we need to hover over the function but something I recommend you do which is much more safe in terms of type checking is specifying your return type and we should also return the users because now we can read this function and immediately at the first glance we're going to understand that this returns a dictionary of integer to string we don't have to read through that function to understand that and on top of that if you using a code editor you're going to get some very useful warnings because here we returned a dictionary of type integer and string but maybe you might accidentally return a dictionary of string and string and static type Checkers are not going to be happy about that they're going to warn you that we're returning the wrong data type so that's already a huge benefit of specifying a return type but also just in general I recommend you specify types whenever you can because in a majority of cases they're going to give you a lot of helpful information another example would be if you had a function called display users that took some users of type dictionary of int and string and returned none with these annotations we provide some self documentation I'm not saying you should ignore documenting your code but you just provide enough context for someone to understand what this does at a single glance it takes an argument called users of type dictionary of int to string there's no confusion about what you should insert there and by specifying that this returns none we understand a immediately that we should only run this function we shouldn't bother with trying to assign this to anything it was only meant to be executed now we can do something simple such as for key and value in users. items print KV with the separator set to this colon and something else that's really cool about specifying the data type in your function signature is that when you refer to that argument you actually get the context actions of that type so key is going to have the context actions of integer and value is going to have the context actions of a string if we were to remove this and we were to refer to the context actions of these arguments you'll notice we would get nothing back because pycharm or your code editor has no idea what users is supposed to be and neither do we it's so easy to make a mistake there because again they might pass in a dictionary of string and string they might pass in a twole they might pass in an integer whoever is using this function needs to read some documentation before using it correctly but if you specify the type they're going to know immediately what they have to pass in and now below we can create our if name is equal to Main Check and inside here we're going to create some users of type dictionary of int to string and we're going to get our users and with that we can display our users and the next time we run this we should get an output such as this one moving on to tip number three as I mentioned just a moment ago providing return types and type annotations in your function signatures can be very useful for self-documenting those functions but I want to stress that it's not a replacement for documentation I still recommend writing documentation for all your code when possible because while these type annotations tell us about what we should insert and what we will get back they don't really tell us anything regarding what it actually does and it might be straightforward to read the code but if it isn't you're going to have a lot of people using your functionality in a way that you did not intend so as the third tip I always recommend you add a dock string and to do so you just need to insert triple quotes now on pycharm if you tap on enter depending on your function signature it's going to automatically insert some Sphinx markup and I'm going to leave a link to the docs regarding that in the Des description box down below but essentially it's going to look like this and if you provide even more information in your function you're going to see that it's going to even insert more of this Sphinx markup so now instead of just having a return type we're also going to have a parameter called users because that's what we specified here and there are actually many things you can do with Spinx markup all you need to do is type in colon and then you can specify the documentation for a lot of these things such as parameters what it raises what the type is what it returns but in general I just keep it as simple as what the parameters are and what it returns so let's go back to get users and let's add some simple documentation such as retrieves the IDS and usernames from a database here it might be good to be specific but I don't have anything to specify so I'm just going to say from a database as a dictionary and this information might be very useful because just by reading our function we understand already that it returns a type of dictionary of int to string but we don't really know exactly what in string is unless you've been working on that code base for weeks but otherwise at a first glance you probably will have no idea what this information actually is so using a doc string to provide that extra information can be very useful and then here you can specify what it returns you can type in something such as a dictionary of users or you can specify something such as a dictionary of int to string here you just provide what it returns and now the next time we actually hover over our get users function we're going to get this very nice documentation back retrieves the IDS and usernames from a database as a dictionary and then it returns a dictionary of type integer to string and personally if I ever need inspiration for writing documentation I would just import something such as a module that is built into Python and just read the documentation for that so we can say for random integer example and if we hover over that you'll see how the professionals did it many years ago but for more upto-date inspiration I definitely recommend you look at documentation or read the doc strings from more recent packages but let's also go down to display users and here I'm going to type in that it prints each user to the console in a nice format and the parameter of users should be the users to display and it returns to us nothing and again the next time we hover over our function we should get that cool information back tip number four here I'm going to be showing you how you can force whoever is using your code to be a little bit extra explicit and for this example I have two enms one that holds the quality of video that someone's uploading and one that holds the information regarding whether that video should be private unlisted or public I then created a function that takes a file of type string and that's just a file path and then that takes the quality it should be uploaded in and what the Privacy should be set to and since this is a function that only uploads the content it's obviously going to return none as for the print statement all it says is uploading that file in that quality with that privacy and to call the function all we need to do is pass in first the file path which in this case is just going to be a local file called cat. MP4 we're going to set the quality to low and and the Privacy is going to be set to private so far this was all self-explanatory and if we were to run this we should get a nice output such as this one that we are uploading cat. MP4 in 480p with the visibility set to private but as your functions grow in complexity passing parameters in like this can be quite confusing and yes you can also choose to specify this as a keyword argument to make it more explicit and that would work just fine but this is completely optional and whoever is using your functionality can decide whether they want to do that or not so in case you want to make sure that there are no confusions with what they are passing in you can also force them to pass in keyword arguments by providing a star or an asterisk in front of the parameters that you want to force them to use so in the function signature we now have a file of typ string a star and then the quality and the Privacy so everything that comes after the star they must pass pass in as a keyword argument which means we can no longer pass in quality. low and privacy. private without their respective keywords which can lead to much less confusion and optionally of course you can put these on separate lines if that's how you like to format it this time I'm going to upload it in quality. high and I'm going to make the video public and the next time we run this it's going to run exactly the same way except we forced whoever is using our function to be extra explicit with the arguments that they're passing in and finally for the final tip of the day I'm going to be showing you another cool feature that we can use with the asterisk so what I'm going to do here is create a function called join text and here we're going to take text one of type string text two of type string and text three of type string then I'm going to provide an asterisk so that the user is forced to be extra explicit with the separator and this will return to us a new string because what we want to do here is combine these texts with the given separator and to do so we're going to return separator do join and we're going to pass in the iterable of text one text two and text three then we can test it out just to make sure that everything works fine and here I'll just print join text with a b and c and the separator is going to be set to a d Dash and when we run this we should get the output that we expect a b and c separated by a dash here we successfully combined these texts with the given separator but we do have a few issues here imagine you only want to insert two strings well that's not going to work unless we provide a default for text number three but even if we provide a default there imagine we want to insert a fourth text then we're going to have to specify a fourth variable so this is just not a maintainable solution for joining text so what we're going to do instead is remove these three parameters and instead of providing an asterisk by itself we're going to say asterisk strings and this is going to convert this variable into something that we call augs and usually you'll see it written as such in most tutorials but you can give it whatever variable name you want and instead of passing in these three texts all we have to now is pass in our strings and with that being done we can pass in as many arguments as we want it can be four and it will work just fine it can even literally be one argument and it will work just fine and I'll just copy this and paste it one more time and maybe add one more letter such as Zed and this time the separator will be a slash so that the next time we run this we will get this funky output and in case this is completely new to you what the asterisk does is grab all of these elements and turn it into a tuple and you can verify that just by printing these strings if you were to run this you'll see that each time we run the script or each time we call the function we're going to get a tuple as an output before it uses it so practically you can read all these arguments as a tuple and I mean theoretically you could make this a list as well but for the sake of convenience sometimes s you're just going to want to use the asterisk and one place you'll see this being used all the time is in the print statement itself the very first argument it takes is this star parameter which allows us to pass in as many values as we want but yeah that's actually all I wanted to cover in today's video do let me know in the comment section down below whether you have any tips and tricks for writing better functions otherwise with all that being said as always thanks for watching and I'll see you in the next video
Info
Channel: Indently
Views: 96,579
Rating: undefined out of 5
Keywords: pyton, pyhton, pythn
Id: 7fSHTqM8gHs
Channel Id: undefined
Length: 15min 58sec (958 seconds)
Published: Mon Apr 01 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.