python functions decorators code example
Example 1: decorator python
def our_decorator(func):
def function_wrapper(x):
print("Before calling " + func.__name__)
func(x)
print("After calling " + func.__name__)
return function_wrapper
@our_decorator
def foo(x):
print("Hi, foo has been called with " + str(x))
foo("Hi")
Example 2: python decorator
def logging(f):
def decorator_function(*args, **kwargs):
print('executing '+f.__name__)
return f(*args, **kwargs)
return decorator_function
@logging
def hello_world():
print('Hello World')
Example 3: examples of function decorators in Python
from functools import wraps
def logit(func):
@wraps(func)
def with_logging(*args, **kwargs):
print(func.__name__ + " was called")
return func(*args, **kwargs)
return with_logging
@logit
def addition_func(x):
"""Do some math."""
return x + x
result = addition_func(4)
Example 4: python decorator
import functools
def with_logging(level=logging.DEBUG, msg = None):
def _with_logging(fn):
@functools.wraps(fn)
def decorated_fn(*args, **kwargs):
res = fn(*args, **kwargs)
print("\n***************", f"\n{msg}", "\nExecuting with Args: ", *args, **kwargs)
logging.log(level, res)
return res
return decorated_fn
return _with_logging
@with_logging(level=logging.DEBUG, msg="Some awesome comment")
def hello_world(name):
return f'Hello World {name}'