Locked learning resources

You must own this product to watch this lesson.

Locked learning resources

You must own this product to watch this lesson.

Reusing Decorators

This lesson is from the Real Python video course by Christopher Bailey.

00:00 So, how can you reuse decorators? For this tutorial, I’ll show you how you can save decorators in a file and then import them whenever you want to reuse them.

00:12 Remember that a decorator is a Python function, and just like any other function, you can reuse them. Let’s move the decorator to its own module so that it can be used with as many functions as you like.

00:24 I’ve already created a folder and I’ve entered into that directory inside of my terminal. Next, make a new file. I’ll have you name it decorators.py

00:38 Inside of decorators.py, define your decorator. For this one, give it the name do_twice(). It’ll take a function as an argument.

00:52 Before, you were just naming the function inside wrapper(), but when you have multiple decorators—in this case, you have used the plural decoratorsit’s a good habit to identify those internal functions.

01:06 And the name wrapper() is just a convention. It can be whatever name. In this case, name it wrapper_do_twice(), echoing the name of the function. Inside of it, let’s call our function that is the argument coming in—twice.

01:23 Then, return the wrapper

01:29 and save. Great! I’m going to adjust my window a bit, and step into my Python REPL. How would you use it? Well, like any other import. You will import from decorators, which is now available, do_twice. Great.

01:49 If that’s successful, you’re ready to go. So now, define a new function with the decorator at the front of it. So @do_twice define—oh, for old time’s sake, we’ll define our good friend say_whee(). Okay.

02:05 So in this circumstance, calling say_whee() will do it twice. And if you inspect the function by typing the name, you’ll see the same layout as before: do_twice, which again, you imported and has a wrapper_do_twice inside of it, wrapping around your code.

02:25 Nice! As you continue on, you’ll keep adding other decorator functions to this file. Next, what about passing arguments into decorators?

You must own this product to join the conversation.