Last Updated : 21 Mar, 2025
Function wrappers, also known as decorators, are a powerful and useful feature in Python that allows programmers to modify the behavior of a function or class without changing its actual code. Decorators enable wrapping another function to extend or alter its behavior dynamically at runtime.
Example:
Python
# Simple decorator
def deco(f):
def wrap():
print("Before execution") # Pre-function execution
f()
print("After execution") # Post-function execution
return wrap
# Function to be decorated
def func():
print("Inside function!")
func = deco(func) # Apply decorator
func() # Call decorated function
Before execution Inside function! After execution
Explanation: deco function wraps another function f inside wrap, which prints messages before and after calling f. Applying deco to func modifies its behavior dynamically.
Understanding decoratorsA decorator in Python is a function that takes another function as an argument and returns a modified version of that function. It is typically used for logging, enforcing access control, instrumentation, caching and more.
Syntax :There are two common ways to apply decorators.
Using @decorator_name syntaxUsing manual function assignment syntax@wrapper
def function(n):
statements(s)
Examples Example 1: Using @ syntax Pythondef function(n):
statement(s)
function = wrapper(function)
# Simple decorator
def deco(f):
def wrap():
print("Before") # Pre-execution message
f()
print("After") # Post-execution message
return wrap
# Applying decorator
@deco
def func():
print("Running...") # Main function execution
func() # Call decorated function
Before Running... After
Explanation: Instead of manually assigning func = deco(func), the @deco syntax is a cleaner way to apply decorators.
Example 2: Measuring Execution time Python
import time
def timeit(f):
"""Measures execution time."""
def wrap(*args, **kwargs):
t1 = time.time()
res = f(*args, **kwargs)
print(f"{f.__name__} ran in {time.time() - t1:.6f}s")
return res
return wrap
@timeit
def countdown(n):
"""Counts down from n."""
while n:
n -= 1
countdown(5)
countdown(1000)
countdown ran in 0.000003s countdown ran in 0.000036s
Explanation: timeit decorator records the start time, executes the function, calculates the elapsed time and prints the duration. *args and **kwargs ensure compatibility with any function signature.
Example 3: Authorization check Python
def admin_only(f):
"""Restricts access to admin users."""
def wrap(user):
if user != "admin":
return print("Access Denied!")
return f(user)
return wrap
@admin_only
def access_data(user):
print(f"Welcome {user}, access granted.")
# Test cases
access_data("guest")
access_data("admin")
Access Denied! Welcome admin, access granted.
Explanation: admin_only decorator allows function execution only for admin users, restricting access with a message otherwise. It helps enforce security controls.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4