Decorators are an advanced application of Closures. They allow you to dynamically modify or wrap the behavior of a function without permanently modifying the function's source code. You pass the target function into the decorator, the decorator wraps it in extra logic (like logging, authentication, or timing), and returns the enhanced function. The @ symbol is just elegant syntactic sugar that applies the decorator instantly.
import time
# 1. The Decorator Definition
def timer_decorator(func):
def wrapper(*args, **kwargs):
start = time.time()
# Execute the original function
result = func(*args, **kwargs)
end = time.time()
print(f"[{func.__name__}] executed in {end - start:.4f}s")
return result
return wrapper
# 2. Applying the Decorator
@timer_decorator
def heavy_computation():
return sum(i**2 for i in range(1_000_000))
# The timer logic wraps the computation seamlessly
heavy_computation()*args, **kwargs in the inner wrapper function. If omitted, the decorated function will crash if it tries to accept any arguments.@functools.wraps(func) on the wrapper to preserve the original function's identity.What does the @decorator syntax actually do under the hood?
It is pure syntactic sugar. Writing @my_decorator above def my_func(): is exactly equivalent to writing my_func = my_decorator(my_func) after the function is defined.
Authentication checking in web frameworks like Flask or Django.
import functools
def require_admin(func):
@functools.wraps(func)
def wrapper(user, *args, **kwargs):
if user.role != "admin":
raise PermissionError("Access Denied: Admins Only")
# Proceed if authorized
return func(user, *args, **kwargs)
return wrapper
@require_admin
def delete_database(user):
print("Database deleted.")Test your understanding of Decorators with these quick questions.
Question 1
Why is `@functools.wraps(func)` highly recommended when writing custom decorators?
Decorators are an advanced application of Closures. They allow you to dynamically modify or wrap the behavior of a function without permanently modifying the function's source code. You pass the target function into the decorator, the decorator wraps it in extra logic (like logging, authentication, or timing), and returns the enhanced function. The @ symbol is just elegant syntactic sugar that applies the decorator instantly.
import time
# 1. The Decorator Definition
def timer_decorator(func):
def wrapper(*args, **kwargs):
start = time.time()
# Execute the original function
result = func(*args, **kwargs)
end = time.time()
print(f"[{func.__name__}] executed in {end - start:.4f}s")
return result
return wrapper
# 2. Applying the Decorator
@timer_decorator
def heavy_computation():
return sum(i**2 for i in range(1_000_000))
# The timer logic wraps the computation seamlessly
heavy_computation()*args, **kwargs in the inner wrapper function. If omitted, the decorated function will crash if it tries to accept any arguments.@functools.wraps(func) on the wrapper to preserve the original function's identity.What does the @decorator syntax actually do under the hood?
It is pure syntactic sugar. Writing @my_decorator above def my_func(): is exactly equivalent to writing my_func = my_decorator(my_func) after the function is defined.
Authentication checking in web frameworks like Flask or Django.
import functools
def require_admin(func):
@functools.wraps(func)
def wrapper(user, *args, **kwargs):
if user.role != "admin":
raise PermissionError("Access Denied: Admins Only")
# Proceed if authorized
return func(user, *args, **kwargs)
return wrapper
@require_admin
def delete_database(user):
print("Database deleted.")Test your understanding of Decorators with these quick questions.
Question 1
Why is `@functools.wraps(func)` highly recommended when writing custom decorators?