💡 Understanding Python Decorators
Decorators are a powerful feature in Python that allow you to add functionality to an existing function without modifying its source code. A decorator is essentially a function that takes another function as an argument, wraps it in an inner function (the "wrapper"), and returns the wrapper. This is useful for tasks like logging, timing, or access control.
Code explanation: The
#Python #Decorators #Programming #CodeTips #PythonTutorial
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
Decorators are a powerful feature in Python that allow you to add functionality to an existing function without modifying its source code. A decorator is essentially a function that takes another function as an argument, wraps it in an inner function (the "wrapper"), and returns the wrapper. This is useful for tasks like logging, timing, or access control.
import time
def timer_decorator(func):
"""A decorator that prints the execution time of a function."""
def wrapper(*args, **kwargs):
start_time = time.perf_counter()
result = func(*args, **kwargs)
end_time = time.perf_counter()
run_time = end_time - start_time
print(f"Finished {func.__name__!r} in {run_time:.4f} secs")
return result
return wrapper
@timer_decorator
def process_heavy_data(n):
"""A sample function that simulates a time-consuming task."""
sum = 0
for i in range(n):
sum += i
return sum
process_heavy_data(10000000)
Code explanation: The
timer_decorator function takes process_heavy_data as its argument. The @timer_decorator syntax is shorthand for process_heavy_data = timer_decorator(process_heavy_data). When the decorated function is called, the wrapper inside the decorator executes, recording the start time, running the original function, recording the end time, and printing the duration.#Python #Decorators #Programming #CodeTips #PythonTutorial
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨