Python Decorators

4 min read ·

A decorator is a function that modifies the behavior of another function without changing its source code.
In simple words:
Decorators wrap a function and add extra functionality before or after it runs.
Decorators are heavily used in:
  • Logging
  • Authentication
  • Performance monitoring
  • Access control
  • Frameworks (Flask, Django)

Functions are First-Class Objects

In Python, functions can be:
  • Assigned to variables
  • Passed as arguments
  • Returned from other functions

Function Inside a Function

This concept is the foundation of decorators.

Returning a Function


Basic Decorator Structure

  • func → original function
  • wrapper → adds extra behavior

Simple Decorator Example

Using the decorator:

Decorator Without @ Syntax


Decorator with Arguments


Example: Decorator for Logging


Authentication Decorator

Problem

Allow function execution only if user is logged in.

Execution Time Decorator

Problem

Measure how long a function takes to execute.

Retry Decorator

Problem

Retry a function 3 times if it fails.

Input Validation Decorator

Problem

Allow function execution only if input is positive.

Role-Based Access Control

Problem

Only allow admin users to access a function.

Stacking Multiple Decorators


Common Mistakes with Decorators

Forgetting *args, **kwargs

Fails for functions with parameters.

Not Returning Function Result ❌

Caution

Always return the result if the original function returns something.


Real World Example

Real World Scenario

API request logging using decorator


Exercise

Practice Task
  1. Create a decorator to check password before function call
  2. Write a decorator to count function calls
  3. Create a decorator to convert output to uppercase
  4. Implement retry decorator with custom retry count
  5. Stack two decorators and observe execution order