Python Decorator Pattern
Diversify your Python functions by decorating them
The decorator pattern consists of a decorator function that contains a wrapper function that wraps the subject function(function to be decorated). The wrapper is written as an inner function of the decorator. The wrapper is returned as the decorated version of the subject function.
If all this sounds daunting, watch this video and see for yourself how easy it is to implement your own decorator.
Code example
# Structure of a decorator
def my_decorator(func2decorate):
def wrapper_aka_decorated_func(*args,**kwargs):
# Code before function to decorate
func2decorate(*args,**kwargs)
# Code after function to decorate
return wrapper_aka_decorated_func
# Decorator in action
# The '$' decorator
def dollar_deco(func):
def wrapper(*args,**kwargs):
return(f'${round(func(*args,**kwargs),2)}')
wrapper._undecorated = func
return wrapper
@dollar_deco
def calc_amount(p,r,n):
return(p*(1+r)**n)
print("Decorated output: ",calc_amount(10_000,0.03,5))
print("Original Output: ",calc_amount._undecorated(10_000,0.03,5))
Takeaway
The decorator pattern suggests how we can implement a most generic version of our function and leave it to a decorator to specialize it later for a specific purpose. This lends flexibility to our code and encourages code reuse.