Skip to content

Instantly share code, notes, and snippets.

#Passing Arguments to the wrapper function
def decor_func(fn):
def wrapper(*args, **kwargs):
return fn(*args, **kwargs)
return wrapper
from functools import lru_cache
@lru_cache()
def factor(n):
print('Factor{0}!'.format(n))
return 1 if n < 2 else n * factor(n-1)
factor(5)
def factor(n):
print('Factor{0}!'.format(n))
return 1 if n < 2 else n * factor(n-1)
factor(5)
@logged
@time
def product(a,b,c):
print('The product of a*b*c:', a*b*c)
product(3,5,6)
def time(fn):
from functools import wraps
from time import perf_counter
@wraps(fn)
def wrapper(*args, **kwargs):
start = perf_counter()
res = fn(*args, **kwargs)
end = perf_counter()
print('{0} ran for {1:.6f}s'.format(fn.__name__, end-start))
def logged(fn):
from functools import wraps
from datetime import datetime, timezone
@wraps(fn)
def wrapper(*args, **kwargs):
run = datetime.now(timezone.utc)
res = fn(*args, **kwargs)
print('{0}: called {1}'.format(fn.__name__, run))
return res
# passing the argument:
def passing_arguments(fn):
def wrapper_arguments(arg1, arg2):
print ('Arguments are passed:', arg1,",", arg2)
fn(arg1, arg2)
return wrapper_arguments
@passing_arguments
def orig_function(city, state):
print ('My city is', city)
# This the first decorator
def decon_first(fn):
# The new function the decorator returns
def wrapper():
# Insertion of some code before and after
print('This is the first decorator')
return fn()
return wrapper
# This the second decorator
def decor_func(fn):
@wraps(fn)
def wrapper_func(*args,**kwargs):
"""
This is the wrapper function
"""
print('Execute this code before the main function is executed')
return fn(*args, **kwargs)
return wrapper_func
import functools
def decor_func(fn):
@functools.wraps(fn)
def wrapper():
# Write some code before the funtion or after the function
return fn()
return wrapper