Function Wrappers in Python (original) (raw)

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

`

Output

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 decorators

A 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 syntax

@wrapper
def function(n):
statements(s)

Using manual function assignment syntax

def function(n):
statement(s)
function = wrapper(function)

Examples

**Example 1: Using @ syntax

Python `

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

`

Output

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)

`

Output

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")

`

Output

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.