5 Useful Python Decorators (ft. Carberra)

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 we're going to be looking at five useful decorators that you can use in Python now some of these are going to be custom made while the others are going to be built in and I also want to mention that all of the code you're about to see can be found on my GitHub repository so in case you want to copy and paste any of this code into your own project you can now do so by following the link that I left in the description of this video anyway let's get started with the first useful decorator and this is one that I manually created called retry so let me show you how it works and to demonstrate it I'm going to create a function called connect which returns none so here all we're going to do is try to establish some sort of connection and we're going to give it a delay of 1 second and we're also going to raise an exception and this exception is going to state that we could not connect to the internet and practically all we're saying here is that the user has their Wi-Fi turned off so no matter how many times we're trying to connect it's going to raise this exception but regardless of what's Happening Here we're going to want to try to use this function again if it fails and to make this very convenient I've created a decorator called retry and personally I can import that from a module that I created called indent and this is not a real module do not try this in your own projects because you will not find it this is just a module I created in my project that contains the decorator and again you can find this in the GitHub repository and I actually messed up here what we wanted to do was import from indent the retry decorator and here we can specify that we want to retry this function and it also takes two optional arguments one being the amount of retries that we want to go for and by default this this is set 2 three but maybe we want to try it even four times and you can do that by entering four and the delay in seconds between each attempt and here I'm just going to enter let's say 1 second now all that's left for us to do is to create our main entry point and try to run this function so right here we can try to connect and when we run our code what you should notice in the console is that it's going to continuously try to run this code and it's also going to give us back the error each time it fails and after four retries it's just going to give up because that was the limit that we specified so that's one great idea for a decorator that can really make your life a little bit easier when you are testing certain functionality now before we move on with this video I just want to bring in today's sponsor which is absolutely nobody so I hope you're having a great day today and moving on with the second decorator we're going to be covering one called Cash and this is a personal favorite of mine and to demonstrate how it works I'm just just going to paste in one of the functions I created from earlier and all this function does is count the amount of vowels in a given string as you can see the function name is called count vowels it takes some text of typ string as an input and then it returns an integer and to make it work I start by creating a vowel count which is set to zero and then I pretend that it's some sort of expensive operation by making the program sleep for 2 seconds of course it doesn't take this long but we're just pretending that this is a very expensive op operation otherwise we try to count those damn vowels and we return the vowel count so up until this point it's a normal function but let me show you one of the small problems it has and to demonstrate it we need to create our main entry point and inside here I'm going to call this function a couple of times with the exact same argument so here we can print count vowels for Bob and we're going to do that twice or even three times why not and what you're going to notice is that when we run this code it's going to take 2 seconds to count the vowels in Bob each time we call the function but waiting 2 seconds for a computation that we already performed earlier is a huge waste of resources so one simple thing we can do instead is cache the result by using the at cach decorator and just like that the next time we actually try to run our script the return value of the first function call is going to be cached so each subsequent call is just going to grab the value immediately I do want to mention though that this is not free functionality and it can lead to memory leaks in your program because now you're caching a lot of data which of course takes memory so every now and then you might want to actually see the cache info and to do so you can refer to the function you're using the cash on and call Cash info and just to make this more interesting I'm going to introduce James to the equation so now if we run this we're going to have to wait 2 seconds because Bob was cashed but James wasn't but at the end you're going to get some cash info back and the first value tells us how many times we successfully used the cached value misses refers to how many times we had to perform a fresh calculation Max size is the max size of the cache and the current size is how many values we have cached so far and finally at any point you can always clear that cache in case it grows too big or you don't care about those values anymore and you'll notice that right below this if we were to print count vowels with Bob as the text that the next time we try to print it after having had cleared it it's going to have to perform this computation once again moving on to decorator number three for this example we have a couple of functions that we're going to want to time because maybe we create ated it very fast and we don't know really how long they actually take so of course you can import the timeit module or you can perform your own tests but that could take quite a bit of time to write what would be more convenient is if we could just add decorators to these functions to time them and that's exactly what we're going to do so once again let's import from my imaginary module the get time decorator and again the code for this decorator can be found on my GitHub repository but all we have to do to use it is decorate each one of these functions with at get time and we'll copy and paste that on 50 million Loops as well and I didn't really explain what these do just yet one tries to connect to an imaginary database and I use the time do sleep function to simulate it taking some time to actually achieve that and the second function just performs 50 million iterations with pass although do keep in mind that if you really want this to be an accurate Benchmark you're going to want to remove all the information that does not have to do with the functionality that you are testing anyway to use this decorator all you need to do is just call it somewhere so in our main entry point we're going to call connect and we're going to call 50 million Loops so that the next time we actually run this function it's going to try to execute that code and it's also going to give us back the amount of time it took to execute both of these functions so connect took 2. 5 Seconds to execute while 5050 million loops on my computer took 675 seconds to execute now for the next two tips I'm going to be bringing in another python specialist who goes by the name of carara he also has a really cool python Channel filled with tips and knowledge that I learn from every day but anyway here's carara hey everybody I'm carara the first decorator that I want to talk about and the fourth decorator in this video is the deprecated decorator and this is coming to the warnings library in Python 3.13 however it's not around yet but you can use version from the pi the python packaging decks if you want to do that you just do pip install uh deprecated and then you have it uh with you I will be showing the differences between the two but for now we can do from deprecated uh import deprecated and say we had um this function add that took in X that was a time int and Y that was a type int and it returned a typee int and then we would just simply return x + y everything's very innocuous so far but what if we wanted to deprecate this function well we could use the deprecated decorator and we could provide a deprecation message now this is optional you don't have to if you don't want to but we could if we wanted to do adding eight uh call no more or something like that and on top of that we can also put in a version number uh I'm going to put version say 1.0.0 uh and this is the version that the function was deprecated since not the version in which the function will be removed which does slightly call into question how useful that actually is but you know I did want to to point that out anyway that that was a thing and if we use our run guard so if name equals main I don't have the fancy pie charm shortcuts that uh feder Eco has and if we do print ads 57 and then run that in the ter like so it's called deprecations uh we can see that we get this warning back so we have a deprecation warning uh call the deprecated function or static method add and this is the name and then in Brackets if we have a reason it will put these here um if you don't have a reason it won't put these brackets here at all and if you have a version it will add this bit at the end saying deprecated since version 1.0.0 and then it will you know put the stack Trac in the right place and then you know you'll get the number anyway and this is basic basically the idea of what pep 702's implementation will do what it will do additionally is it will if I can find it it will additionally raise type errors as well using type Checkers so if I scroll up a bit this is an example implementation so you have to deprecate it it uses the same message but do note that the version parameter isn't there in the pep 702 implementation uh if we come down here we can see you know this is showing that we'll get the error uh you know use of deprea and blue uh it is pining for the fs that's a nice little thing so you have you know this um kind of message that's in there as well but you will get the you know the standard era use of deprecated function so the type Checkers will actually be able to do that which is something that cannot be done here but either way this is a really nice feature especially if you're developing a python package for you for you to be able to deprecate things and for people to be able to you know upgrade their code bases to match your new specification the second decor I want to talk to you about and the last in this video is the at exit. register decorator uh so we do import at exit and then we can decorate uh using this and what this will do is it will register a function to be called when the program terminates so we can do exit Handler here and this will return none it takes no arguments you can't make it take any arguments and we can just do prints uh whoops we're exiting remember how to spell now I've literally just finished work as I record this so this is all fun and games and then we just do a main function to show that it's working so for I in range 10 print two * I or two to the power of I I should say and then we have our rung guard again uh like that and then we simply just print main so you'll notice that we're not calling exit Handler at all and that's that's because um we don't need to you can see it it prints we're exiting now and that's because we registered this function to run uh when the program terminates and I've realized here that we don't actually need to print this so I'm just going to get rid of that the important thing to note about this is it will run whenever the program terminates for whatever reason so if you were to introduce an error down here say a zero division error we can run this again and we'll still get the trace back saying you that we got a zero division error but it will still print that we're exiting now it will still run so it is literally the last thing or one of the last things that is run before a program terminates so this is particularly useful and I'm just going to show you an example I was going to type out but I think it'd be easier just to kind of walk you through it um when you have a database connection especially a global one so we create our Global database connection here we then initialize the database and at the moment this is all this program is doing but in our exit Handler here we can say that we want to commit changes to the database and we want to close the database if you wanted to make this logic a bit fancier you could come up with some way to work out whether the changes should be rolled back or not but in this case we're just committing and enclosing so even if you get an error then we close the database um in a you know a safe Manner and we don't you know leave any hanging connections open so that's just one really useful example for something like this before I hand it back I do quickly want to show you that you can also unregister functions so we can do exit. unregister and then we simply just pass the function in and now if we run this um it won't call that function anymore because we unregistered it so if you wanted to dynamically unregister something say you had some other logic somewhere else then you could do that if you wanted to yeah that's all I wanted to talk about I hope to see you again soon but for now I'll pass it back to federo in the studio amazing and just like that we learned about five useful decorators that you can use in Python personally the two that carara mentioned are completely new to me but now is also a good time to mention that if you are interested in learning more about Python and all its cool features do check out my friend carara on YouTube because he makes videos about a lot of interesting topics that I just don't tend to cover so I've left a link to his channel in the description box down below do make sure to check him out but otherwise that just about sums up this video so if you have any questions or any comments do leave it in the comment section down below but otherwise as always thanks for watching and I'll see you in the next video
Info
Channel: Indently
Views: 91,544
Rating: undefined out of 5
Keywords: pyton, pyhton, pythn
Id: 3_P-dxrNCq8
Channel Id: undefined
Length: 14min 34sec (874 seconds)
Published: Mon Mar 11 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.