How To Write Better Functions In Python

28.9k views2615 WordsCopy TextShare
Indently
In today’s video we’re going to be learning how we can improve our Python functions using 5 easy to ...
Video Transcript:
this video was brought to you by IND dentle IO learning python Made Simple how's it going everyone in today's video we're going to be learning how we can write better functions in Python using some very easy to remember tips so to get started we're going to create a very simple function that grabs the local time and returns it to the user in their current local and to do so we're going to import from date time the date and the time then we can create our function which is called get time time and the first tip
for every function that you create is to keep the name short and concise you don't want to write get time in current users local because that's going to take a lot of space every time you call it and at the end of the day this is overkill at most I would write get current time even though I would consider this part to be redundant because if you're getting the time it's not like you're asking for a Time in the future or a time in the past get time is self-explanatory anyway every time you create a
function keep the name short and concise and one of the few exceptions I can think of is if you're testing your code usually tests have really long names such as test X is the same as Y in tests you'll probably see this but if you're just creating a normal script there's no need to complicate the name anyway anyway moving on we're going to specify a return type and this is something I always recommend you do at the beginning of the function because this makes it extra explicit that you're trying to return that data type and
I'll show you the benefits of doing this in just a moment so here we're going to grab the time and we're going to return it as a string so here we can add a comment that says specify a return type next we're going to grab the current date and time and we're going to call that variable now and that's going to equal date time. now which is going to return to us a date time object and finally what we're going to do is return the date and time but what you're going to notice is that
we're going to get some syntax highlighting on now because now is not a string it's a date and time object and this is a mistake I always make when I'm creating functions but luckily since I specified a return type any static type check or most code editors are going to catch this mistake and let me fix it before I even run the code because here we explicitly specified that we want to return a string so returning a date and time object will raise a red flag not only are we returning the wrong type but we're
not even returning what I said we would return so here we're going to return now and use the special date time format specifier of percent X which will return the current time in the user local and we can test this function by printing get time and here as you can see it is 8: in the morning and instead of keeping these inside here I'm going to take them out because there are some tips that I can't really comment in there such as for the third tip every time you create a function what your ultimate goal
should be is to make it as simple and reusable as possible so here we can type in make as simple and reusable as possible in general it's a good idea to keep dependencies outside of your function if you want to include a dependency introduce it as an argument right now our function depends on the date time dependency we're using functionality from a different module that this function depends on now this dependency is extremely reliable it's something that all the python versions have so it's not something I would worry about but the more dependencies your function
has the harder it can become to maintain in the future so that's something you should keep in mind when you are using external functionality in your functions but in this case it's already incredibly simple and Incredibly reusable it does one task it grabs the time and returns it as a string nothing else which means the chances of this function breaking in the future are near to none and that we can use this in more complex code anytime we please without any complications but there's still one thing we can do to this function to make it
even better and this is documenting it so so we're going to type in document all your functions and documentation is incredibly important if you expect other people to use your functionality anytime in the near future or even if you expect yourself to use your functionality in the near future if you're creating a simple script that you'll never see again or you will never use again in most scenarios you can skip on writing documentation it's not something you're going to go back to so there's no point in wasting all that space writing documentation but if you
actually expect other people to use use it in the future please write documentation it's going to save everyone so much time when it comes to learning how your program actually works so that they can use it and modify it as they please for example in this get time function we have all the basic functionality which is quite easy to read but it still would be nice to have the documentation written so that when we hover over the function we get a better description on how this works so that we don't actually have to go to
this function declaration and learn how it works works there so what we're going to do is add some triple quotation marks and in this example I'm just going to remove the Sphinx markdown and start writing my documentation this is a function that gets the current time in the users's local and returns it as a string then below I'm going to provide an example and this is something I love to see in documentation because it actually gives us a real example that can be run and tested before actually using the function for example here we type
in get time that is the example and what it returns goes directly below that so I'm just going to run the script real quickly and grab whatever is here and paste it inside here as an example and that will be the documentation for this function this one's quite simple of course you can write more and I'm going to show you in another example how much you can actually write when you are creating documentation but now the benefit of this is that anytime that someone else decides to use your function and doesn't truly understand how it
works they can just hover over it and they're going to get something descriptive regarding that function and an example of what it returns such as right here we call get time and it returns this string over here I cannot stress how important documentation is most of the problems that arise in programming come from poorly written documentation or no documentation at all because then it leaves it to the developer to guess how the function works or to use it to the best of their ability the more clear your documentation is the less are the chances that
other people are going to make mistakes using your function and finally for tip number five I recommend you always try to handle the errors that your function can produce appropriately so here we'll just type in handle errors appropriately and in this function there isn't really anything that can go wrong as far as I know so there's nothing to be done here but but in the next example I'm going to be showing you exactly what I mean by that so for the next example I'm just going to remove this part and I'm going to remove this
function over here and instead of writing it all out I'm going to paste it in and explain it line by line so here we'll just paste it in it's actually quite a big function or it's not that big It's usually the doc string that takes most of the space but once again the doc string is incredibly important anyway to get started I have a function called get total discount and it's going to get the total discount for a list of prices and that can be any ital of type float then it's going to take a
percent which allows us to create that discount on the prices in that iterable and what this is going to return to us is a float so we're expecting to get a price back at the end of the day with the discount applied so we're getting the total discount of all these prices so so far we have a short in prise name and we specified a return type which will help prevent us from making silly mistakes when we try to return something next we want to try to make it as simple and reusable as possible and
for now I'm just going to remove the documentation so we can actually see how the function looks and this time you're going to notice that I actually included some validation for our function such as if the percentage is not between zero and one both zero and one being inclusive then this function is going to raise a value error that we have an invalid discount rate with the percent provided because if we put any number that's not in that range it's going to be hard to make that calculation then we also tell the user explicitly that
it must be between 0o and one inclusive after that we check that all the prices are non- negative numbers so to keep it short we're checking that each price is either an INT or a float and that each price is more than or equal to zero then we calculate the total and return the total times the discount so it's still an incredibly simple function it has one job which is to calculate the discount of this iterable and it doesn't rely on any external dependencies other than the itable type from the collections. ABC module which is
a core module in Python so that's not something we really have to worry about there's nothing inside this function that relies on external factors if you ever have a global variable for whatever reason such as X is equal to 10 and you use Global X this is something I would recommend you try to avoid because if anything goes wrong on the outside that's going to affect your function on the inside making it much harder to keep track of changes so personally if you want to use x inside here I would recommend you create a new
argument or a new parameter for that and just apply it there and then continue using it inside your function but using the global keyword isn't really something I recommend you do that often unless you absolutely have to anyway now our function is simple and reusable so what we're going to do next is provide some documentation for it I mean you can add comments everywhere but comments aren't that useful for anyone who's just hovering over your function so what we're going to do is the right thing and add some documentation and this time I am going
to be using some Sphinx markdown so what we have here is a function that calculates the total price after applying a discount this function calculates the total sum of prices in the provided list and then applies a discount based on the given discount rate if the discount rate is invalid for example negative or greater than one the function raises a value error then we have all of the information regarding the parameters the types the return and what it raises such as the parameter of prices is a list of item prices the type of prices is
list of type float which is obviously different because I changed that off camera and I didn't update any of this then we have the parameter of percent which is the discount rate to apply and there's no default anymore cuz that's something else I deleted as well so I'm going to remove that then we have a type of percent and that is no longer optional so that's just a float and the return type is the total price after applying the discount which will be of type float and finally this raises a value error if the percent
is not between zero and one inclusive or if prices contain non-numeric values so there was actually a lot of information I accidentally updated off screen which I didn't update here but good thing we fix it here what's important is that you write accurate documentation based on what your function does and what it contains then at the bottom we also have an example so if we call get total discount with this argument being the prices and this discount we're going to get this as an output and we can actually go down and test that so we
can type in Main and that's going to create my main entry point and the if name is equal to Main Check where we call Main but now inside here we can just go here and copy the example and paste it inside and when we run it what we should get back is nothing because it returns a float silly me so print get total discount and then we should get that as a return now we can also type in something such as 1 10 25 50 and 1,000 and we're going to give this list a 50%
discount so 0.5 and what we're going to get as a return is 543 because that's half of the sum of this so the function works perfectly fine it doesn't rely on any external factors all it relies on is the information that we insert as arguments and now if we hover over get total discount we're also going to get some very useful documentation it's going to tell us exactly how the fun function works it's going to give us an example it's going to talk about the parameters such as the prices which is a list of item
prices and the discount rate to apply then it Returns the total price after applying the discount and it raises a value error if this condition is not met and just like that we've written another maintainable python function which is short and concise it specifies a return type it is simple and reusable it is documented and it handles the errors appropriately but yeah that's actually all I wanted to cover in today's video do let me know what you think about all of this and whether you have any advice or tips for creating better functions in Python
but otherwise as always thanks for watching and I'll see you in the next video
Copyright © 2024. Made with ♥ in London by YTScribe.com