Python Decorators in 15 Minutes

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video I'll be discussing an advanced topic in Python called decorators now decorators are a way to change or modify the behavior of any of your functions or methods without directly changing any of the code they're extremely powerful have a lot of different use cases and throughout this video we'll go through a few different examples and discuss when and why you might use a decorator that being said we'll also discuss how they work on a low-level by understanding some fundamental concepts in Python and then we'll talk about creating our own and using them properly but before we dive in I want to show you a tool to turbocharge your Python programming called kite now kite is a free plugin for your IDE or text editor uses machine learning to give you the best possible completions for your Python code it's capable of completing entire lines entire function calls and it ranks all of its completions by relevance so you get shown the best ones first even as another feature called intelligence snippets which allows you to quickly tab through the different options and choose which completion you'd like one of the coolest features that comes with kite is called co-pilot now what code pilot does this provide one-click documentation it shows you information about modules classes methods and functions based on your cursor location now the best part of kite is that it's free and you can download it at the link below so before we can start to understand decorators we need to learn about a fundamental aspect of functions in Python and that is that they can be represented as objects now I'm going to show you an example to see how this works but I want to quickly illustrate that I have a function here called f1 and we know that when calling f1 what will happen is we'll simply print out called f1 very standard makes a lot of sense we all understand how that works now what I'm actually gonna do is rather than printing f1 or calling f1 I'm gonna print the function named f1 and not put the brackets beside it now some of you might have done this before accidentally but let's have a look at what happens you can see that we get I would hear some output function f1 at some random memory address now what this actually means is f1 is an object and since it's an object we can actually pass it around our program this is very powerful I'm going to show you exactly what I mean so I'm gonna create a new function called f2 and inside here it's gonna take an argument called F what I'm going to do is simply call whatever this argument is F and now what I'm going to do is call f2 and instead of simply putting in you know some value for F I'm actually gonna put the function f1 now take a guess at what's gonna happen here what are we gonna output is this an error is this correct well since we can represent functions as objects this is actually going to work properly and when I use my output here we can see that we get called f1 now the way that this worked fundamentally is f1 is an object that represents this function since this is an object we can pass it through parameters we can store it in variables we can do all kinds of things with it so when I call f2 I'm gonna pass through the object representing function 1 then I'm simply going to call that function from inside of f2 and I will get that value returned or outputted to my screen and that is the basic principle of functions in Python that we need to understand to understand decorators so now that we understand that functions are objects and they can be passed through parameters what I want to show you is another really interesting aspect of functions and that is something called wrapper functions so what I'm gonna do is actually define a function in this case I'm gonna call it f1 like we've had before that takes as its value another function or as its parameter so just like we had previously we're gonna take another function but inside of this function I'm going to do something very interesting and this is called creating a wrapper function now what this wrapper function is actually going to do is simply print out some value let's say maybe started it's actually gonna call the function that we grabbed here from the first parameter in our initial function and it's gonna print out another value here that just says ended so essentially what this you know whole function is gonna do is well it has another function defined inside of it called wrapper it's gonna print started it's gonna call this function and then once that function finishes running it's gonna call ended or print ended now what I need to do to actually trigger this wrapper function and have it work properly is well call it so what I could do is I could call wrapper just like this from inside the actual function but this isn't actually what I want to do what I want to do is return a value called wrapper so what I'm going to do now is whenever I call function one I'm gonna pass some function to it then what I'm gonna do is actually return another function that has this functionality inside of it that essentially prints started runs the function and then prints ended now you might be able to kind of figure out what's going on here but I'm gonna show you exactly what I mean let's create another function let's just call it F and inside here let's simply print out hello now what I want to do is every time I call this function f I want it to do this function one functionality I want it to you know say print started print hello for this function and then print ending well how can I do this well what I can do is I can say something like f1 and then in here pass F and watch what actually is gonna end up happening when I do this nothing that's pretty strange why did that happen well what do we get here when we have f1 what we do is we create a function and we return another function we don't actually end up calling this function inside here so that means we never actually end up calling the function f how can we call the function f well this is gonna be a really weird thing watch when I show you this I'm actually gonna put another set of brackets here and when I run the program now you see this changes our functionality in our output actually says started hello and end it very weird I know but the way to think of it here is that this value wrapper is a function so what I actually returned the value of f1 and I'll print it out so we can actually have a look at exactly what this is you're gonna see that we get the function f1 locals dot wrapper at some memory address which means that it's telling us you know when you call this function you got back a value which was actually equal to another function so if we want to call that other function well we know how to call functions we need to put our two brackets at the end of it like that now this property is what's actually going to allow us to what we call decorate a function so what I can do is if I want to say every time I call F I want it to do the functionality of f1 which essentially means you know do this call function do this I can say something like f equals f1 at in here F now this is really another strange line what I'll just show you how this actually works so when I run this and we call F we can see that rather than simply printing hello we're actually printing now started hello and ended and that's because I've set F which is a variable equal to the function f 1 with the parameter F passed into it so what happens when I call F is we actually call F 1 giving it the value of our function which is f right here then we have print started func print ended now I could easily change this name to be anything I want I could change it to be X and I now can call X like this and you can see when I run this we get the same result and this is what we call function aliasing essentially changing the name of a function and changing the functionality now you might be like well what the heck I thought this video is on decorators and we haven't even talked really about decorators yet well if you understand everything that I've just said you pretty much understand decorators so this line right here x equals f1 F can be replaced with a nicer thing called well decorators so what I can actually do is above my function f I can decorate it with the function f1 what this is gonna do is essentially write this line in Python for us that's automatically going to execute which means every time we call F it's actually gonna call f1 and pass the function f as a parameter to that so let's try this now and let's call F and we can see we get the same result we had before and now we no longer need to include that line that says F equals f1 at at for you know ASHP inside there so it made a slight modification to my code now to show you something wrong with the current way we've been doing things and that is notice what happens when I add a parameter to my function f so this is the decorated function f and now rather than printing a low we're printing a and you can see we call F with the value high now notice immediately that up here in our wrapper function we call this function f which is actually function right and it doesn't have any parameters and this wrapper function doesn't have any parameters as well so how can we actually go about fixing this now this is where we can use something called args and kwargs now you've probably seen this before it's a fairly commonly used thing in the python language I'm not really going to explain exactly how these work but I will give you a brief explanation so what I'm gonna do is actually put star arcs and star star kwargs in the parameters of my wrapper function and I'm gonna copy this and put the same thing inside of my function here now the reason I'm doing this is so that we know that this wrapper function will have a certain amount of arguments we don't know what those arguments are gonna be we don't know if there's any keyword arguments or regular in-place arguments all we know is that we will have some kind of arguments and same thing goes for whatever function is gonna be wrapped by this function f1 we have no idea what arguments to expect or what kwargs are gonna be passed to that specific function so what we simply do is put star args star star quarks now this will actually allow us to have any amount of arguments on any specific decorated function and this will work properly so you can see I actually ran this code before when I didn't have those Star Wars or Star Star args and we say you know wrapper takes zero positional arguments but one was given so watch what happens now if I actually run this code we get the same value that we expected before and we get this value high print it out and if I decide to add another argument maybe we say something like B equals 9 and then I'll put just print B here as well when I run this this continues to work and there's no issues with it and that's what this star so args and kwargs is gonna do for us so the final thing to talk about and something that I'm hoping you guys were actually looking at is returning values from decorated functions now so far all I've been doing inside of some of my functions is printing out values but what if I want to return those actual values well this is pretty easy to do and I'm gonna make another example by creating a new function so in this case I'm gonna create a function called add which is gonna take two parameters X Y and what its gonna do is simply return the summation of beads so X plus y and what I need to do now is find a way that I can modify this wrapper function such that it's actually gonna return that value well what some of you might say is well why don't I just do something like this return and then whatever the function call is and that way when I return this wrapper function well we can simply return that value well okay what's gonna end up happening is will print started and then we'll simply finish execution after we return the value of this function so if there's things that we need to happen after the function is called those won't happen so what I need to do and this is pretty easy is simply store the value returned by the function in a variable and then return that variable at the end of my wrapped function or my wrapper function so here we get value equals whatever the value that was returned by this specific function that was passed in and then what we'll do is return that value at the end of this so this wrapper function that we return here when we decorate will work like this original function and actually returned to us that value so if I decorate f one and now what I do is decide to print out add of four and five we should see that we get our value nine which we do we get started ended nine like we were assuming so that is essentially how you return values from a decorated function pretty straightforward just make sure you keep track of this value inside of this wrapper function and return it at the end and that being said you don't necessarily need to return this specific value if you always want to return one value from a decorated function you could just hard code that and put that in here this also Illustrated that you can use a decorator on more than one function at a time and when you call it it will work just like any other function that is decorated with that so that has been the basics of decorators I'm going to quickly go through a few examples just just show you in case any of you are still confused or you want to see when we would actually end up using these in a real-world situation so I'm just gonna run through a few quick examples now to illustrate when you might actually use these decorators in some different ways of using them so first of all I just wanted to show with this example that you actually can use a decorator for a method so I've been showing specifically functions but you can do this with a method in the same way we create our decorator up here we can see that I've actually only to take in positional arguments for this wrapper because I knew that would only be positional arguments that's fine to do that if you want to and then I print before print the function and print after or in this case I guess it will be the method so if I run this we can see that we get the same functionality that we would have assumed and that works for a method so moving on to example two this is the timer decorator example very common probably a lot of you have seen this before but in many cases you want to record how long it takes for a function or a method to run and that's when you would use something like this time or decorator so without dragging this on too long I will run this and show you what happens you can see that inside of this function I've delayed two seconds and now it's telling me the function took two point blank whatever seconds to run very useful if you're trying to compare the runtime of different algorithms or methods and you want a really quick way that you can just decorate a function in it tells you how long it takes to run and finally on to example three so this is the most complicated example I've written here just to show you a few different things you can do with these kind of decorators and this is a log decorator so what this is actually going to do is tell you when you've called a function with what specific arguments so in this case it's actually gonna be keyword arguments and at what time and save that into a log file so sometimes you want to record when specific things in your program happen so maybe you want to record every time the run function is run well in that case you could decorate it with that log and if we run this we can see that inside our logs dot txt file it says called function with 1 3 at and then in this case the time that it was called at so again a very basic example of a way in which you can use a decorator so that has been how to use decorators in Python a fairly advanced topic if you guys understood this you're definitely well on your way to becoming an expert in Python you may have noticed that throughout this video I've been using the autocomplete engine called kite now kite works as a plugin for your IDE or text editor and is available for the most popular editors like vs code pycharm subline adam and fin you can give it a try by downloading it from the link in the description it's definitely saved me a ton of time by providing better more relevant suggestions that help me cut down on the amount of keystrokes I need to use while I'm coding so with that being said I hope you all enjoyed the video and you learned something new and I'd love to hear your thoughts on it in the comments down below
Info
Channel: Kite
Views: 429,906
Rating: undefined out of 5
Keywords: Decorators, Python Decorators, Decorators Tutorial Python, How to Use Decorators Python, Python Decorators Tutorial, What is a Decorator Python, Kite, Kite.com, python decorators
Id: r7Dtus7N4pI
Channel Id: undefined
Length: 15min 14sec (914 seconds)
Published: Wed Oct 30 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.