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: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.
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.
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.
Become a Member to join the conversation.