Python Decorators

Decorator Definition

A decorator in Python is a function that modifies the behavior of another function, without changing its code.

Think of a decorator as adding a layer of functionality before and/or after the original function runs.


Why Use Decorators?

PurposeExample Use Case
Add functionality without editing original codeLogging, Authorization
Reuse common logicValidation
Track performanceExecution time calculator
Restrict accessAdmin/user roles

Basic Decorator Structure


Applying a Decorator

The @decorator_function applies extra behavior to the display() function.


Basic Example

Output:


Decorator With Arguments


Decorator Returning a Value


Real-World Example – Logging



Authentication / Access Control


Decorators with Parameters (Advanced)

Sometimes we need the decorator to accept its own argument:

Output


Nesting Multiple Decorators

Leave a Comment