From the course: Python: Decorators

Decorators with *args and **kwargs - Python Tutorial

From the course: Python: Decorators

Start my 1-month free trial

Decorators with *args and **kwargs

- [Instructor] Very quick review of star args and double star kwargs in the previous video. Pfib with star args and double star kwargs. And you want to just print out the values of these arguments, so print args and print kwargs. Now you can also create a wrapper function that serves as pass through. So let's define our wrapper, which takes in these arguments, star args and double star kwargs. And so what we'll do in this wrapper function is to unpack the arguments for args. And then we'll call the pfib function. So let's just print out a note, so that we know that we're in the wrapper function, and let's unpack the arguments for args. So, print star args. And then we want to call pfib, which will print out all of the arguments. So we pass through the arguments from the wrapper function across to pfib. So pfib, star args, and double star kwargs. So we've got both our pfib function defined at the top, and then our wrapper function below that. So let's go ahead and call this wrapper with a mix of single star and double star arguments. So wrapper, and then we'll pass in the Fibonacci numbers, so one, one, and then the third number is two. Then you can see that the first line stays that way in the wrapper function. The second line unpacks the arguments in the wrapper function. Lines three and four are when we print out those values in pfib and the arguments are separated out into tuples and dictionaries. So let's go ahead and update our decorator template to include args and kwargs. So we use the wraps from functools to preserve the doc string and the name of the functions. The decorator accepts a function as an argument. And this time, the wrapper function now accepts args and kwargs. These are then passed through to the function and we return the wrapper at the end of the decorator as before.

Contents