how to make a decorator function python 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: examples of function decorators in Python
from functools import wraps
def logit(logfile='out.log'):
def logging_decorator(func):
@wraps(func)
def wrapped_function(*args, **kwargs):
log_string = func.__name__ + " was called"
print(log_string)
with open(logfile, 'a') as opened_file:
opened_file.write(log_string + '\n')
return func(*args, **kwargs)
return wrapped_function
return logging_decorator
@logit()
def myfunc1():
pass
myfunc1()
@logit(logfile='func2.log')
def myfunc2():
pass
myfunc2()