what is a python decorator code example
Example 1: python function 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 2: decorators in python
'pass function which we want to decorate in decorator callable object'
def our_decorator(func):
def wrapper(x):
if x%2==0:
return func(x)
else:
raise Exception("number should be even")
return wrapper
@ our_decorator
def func(x):
print(x,"is even")
func(2)
func(1)
' if you do not want to use @'
func=our_decorator(func)
func(2)
Example 3: 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}'