Reusing Decorators
Decorators are regular python functions that can be saved in modules and reused in many other functions. This lesson will show you how to do that. You’ll see how to create a module containing decorators as well as how to import the module into other Python files.
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 decorators—it’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?
marktripney on April 6, 2020
I was working through a tutorial on OOP, and decorators were mentioned. Not being very confident that I knew what they were, I found myself here, and I’ve learned a huge amount already. Excellent course, Christopher - thank you.
eshivaprasad on May 5, 2020
It is very clear Christopher Bailey. I really enjoyed it. Continue your great work
Become a Member to join the conversation.
Abby Jones on July 18, 2019
Decorators are awesome!