12. Python Decorators Flashcards
What does a decorator do?
Decorators can be thought of as functions which modify the functionality of another function. They help to make your code shorter and more “Pythonic”.
What is the basic format of a decorator?
def new_decorator(func):
def wrap_func(): print("Code would be here, before executing the func")
func() print("Code here will execute after the func()") return wrap_func
def func_needs_decorator(): print("This function is in need of a Decorator")
# Reassign func_needs_decorator func_needs_decorator = new_decorator(func_needs_decorator)
func_needs_decorator()
Code would be here, before executing the func
This function is in need of a Decorator
Code here will execute after the func()
So what just happened here? A decorator simply wrapped the function and modified its behavior. Now let’s understand how we can rewrite this code using the @ symbol, which is what Python uses for Decorators:
What is the shortcut symbol to use a decorator?
@
How do you use a decorator using the shortcut symbol?
@new_decorator def func_needs_decorator(): print("This function is in need of a Decorator")