Section 3 Overview
Decorators in Python follow a similar pattern that you’ve learned:
import functools
def decorator(func):
@functools.wraps(func)
def wrapper_decorator(*args, **kwargs):
# Do something before
value = func(*args, **kwargs)
# Do something after
return value
return wrapper_decorator
This lesson will show you how to use the code snippet above as a template or boilerplate to write your decorators.
00:00 Welcome to Section 3, where I’ll show you a few real-world examples. I’ll start off by talking about a template that you can reuse for building your decorators, then I’ll show you how to use the decorator for timing functions; debugging code; if you needed to, how to slow down code; and then a decorator example about registering your functions like they’re a plugin. Okay.
00:25
Let me show you this template. Open up your decorators.py
file. Make sure, again, that at the top that you have the import of functools
.
00:39
Then, to define this other decorator, just generically decorator()
. You’ll take a func
function into it,
00:50
then use the @functools.wraps()
and put a function into it. Then, I’ll have you define the wrapper.
01:01
It’ll be called wrapper_decorator()
. It’ll accept *args
—positional arguments—and **kwargs
—keyword arguments. Add a quick comment about “This is the spot to do something before running your function.” In order to return arguments from your function, you’re going to create a variable named value
.
01:28
The value
will be assigned to calling the function with its *args
and **kwargs
.
01:35
And then, very importantly, it will need to return the value
in order to pass it back. And very last, you’ll return the wrapper_decorator
.
01:47
So there it is. There’s our template. Again, if you don’t have do_twice()
already created inside your decorators
module, just make sure that import functools
is at the top, and then this will be the model that you will continue to use throughout the rest of these examples. Consider it boilerplate. Okay!
Become a Member to join the conversation.