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.
It’ll be called
wrapper_decorator(). It’ll accept
**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
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.