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.
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, define your decorator. For this one, give it the name
do_twice(). It’ll take a function as an argument.
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.
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
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,
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
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?
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.
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!