VOOZH about

URL: https://www.geeksforgeeks.org/python/function-wrappers-in-python/

⇱ Function Wrappers in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Function Wrappers in Python

Last Updated : 15 Jul, 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:


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


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


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


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.

Comment
Article Tags: