Skip to content

Decorators

A decorator is a function that extends the functionality of another function without explicitly modifying it. It takes a function as an argument, adds extra behavior within a nested “wrapper” function, and then returns the wrapper. This pattern is commonly used for tasks like logging, timing, or authentication.

The @ syntax is a shortcut for applying a decorator. For example, @timer is equivalent to calling slow_function = timer(slow_function). The nested wrapper function ensures that the original function is called with its arguments (*args, **kwargs) while being wrapped in the new logic.

Basic Example:

def decorators(func):
def wrapper():
print("This is about to execute a function...")
func()
print("Finished Executing Function!!")
return wrapper
def say_hello():
print("Hello User!")
f = decorators(say_hello)
f()
'''
f will look something like this
def f():
print("This is about to execute a function...")
print("Hello User!")
print("Finished Executing Function!!")
'''
# Better Syntax:
@decorators
def say_hello():
print("Hello User!")
say_hello()

Another Useful Example

import time
def timer(func):
"""A decorator that measures a function's execution time."""
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Time taken: {end - start:.4f}s")
return result
return wrapper
@timer
def slow_function():
time.sleep(2)
print("Done!")
slow_function()
# Output:
# Done!
# Time taken: 2.0002s