Decorators
Decorators
- A decorator is a function that wraps another function to enhance or modify its behavior.
- Decorators are only possible because of the ability of functions to act like variables
- A decorator supercharges the function.
- Its a func that wraps another func and enhances or changes it.
Creating a Decorator
def my_decorator(func):
def wrap_func(): #inner function, with parameter x
print('**********') #extra functionality
func() #calling the original function
print('**********') #extra functionality
return wrap_func #returning the inner function
@my_decorator
def bye(): # We are decorating bye function
print() # We've super boosted our bye.
bye() # we are actually calling wrap_func inside my_decorator
what it does: variable = my_decorator(func) func()
my_decorator(bye)() # same as above
DECORATOR PATTERN
- Decorators can accept any number of arguments using args and *kwargs.
def decorator(func):
def wrap_func(*args, **kwargs): #can add infinite parameters
func(*args, **kwargs)
return wrap_func
@decorator
def hey(greeting, emoji=':)'):
print(greeting, emoji)
hey('yoooo')
Performance Example
- Measure execution time using a decorator of a program.
from time import time
def performance(fn):
def wrapper(*args, **kwargs):
st = time()
fn(*args, **kwargs)
ed = time()
print(f'took {ed-st} ms')
return wrapper
@performance
def long_time():
print(1)
for i in range(500):
return i*5
long_time()