A decorator is a design pattern in Python that allows you to modify or extend the behavior of a function or method. It takes a function as an argument, adds some functionality to it, and returns a new function with the extended behavior.
Fig ;)
Syntax
Define the Decorator Function:
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func() # Call the original function
print("Something is happening after the function is called.")
return wrapper
Apply the Decorator: You can apply a decorator using the @ symbol above the function you want to decorate.
@my_decorator
def say_hello():
print("Hello!")
# When you call the decorated function:
say_hello()
Output
When you call say_hello(), the output will be:
Something is happening before the function is called. Hello! Something is happening after the function is called.
Log execution time of a function using a decorator
Use Case:
You want to track how long a function (like a report generation or data fetch) takes to run.
import time
def log_execution_time(func):
def wrapper():
start = time.time()
print('start function',func.__name__)
res = func()
end = time.time()
print(f'finished function {func.__name__} in {end-start:.4f} seconds\n')
return res
return wrapper
@log_execution_time
def generate_report():
print('start generating report')
time.sleep(2)
print('report generated')
generate_report()
@log_execution_time
def calculate_sum(n):
print(f"Calculating sum from 1 to {n}...")
return sum(range(1,n+1))
generate_report()
total = calculate_sum(1000)
print('total ',total)
Output:
start function generate_report
start generating report
report generated
finished function generate_report in 2.00017762 seconds
start function calculate_sum
Calculating sum from 1 to 1000...
finished function calculate_sum in 0.00008488 seconds
total 500500