Python Decorators

1. What is a Decorator

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

def my_decorator(func):
    def wrapper():
        print("Before function execution")
        func()
        print("After function execution")
    return wrapper

@my_decorator
def say_hello():
    print("Hello")

say_hello()

Decorators wrap additional logic around an existing function.


2. Decorator Without @ Syntax

def greet():
    print("Welcome")

greet = my_decorator(greet)
greet()

This demonstrates manual application of a decorator.


3. Decorator with Arguments

Handles flexible function signatures.


4. Chaining Multiple Decorators

Decorators execute from bottom to top order.


5. Decorator with Return Value

Wraps and transforms return values.


6. Decorator Preserving Function Metadata

@wraps preserves function name, docstring, and metadata.


7. Decorator for Timing Execution

Used for performance profiling.


8. Decorator with Parameters

Supports configurable decorator logic.


9. Class-Based Decorator

Implements decorators using classes.


10. Real-World Decorator Example (Authentication)

Encapsulates cross-cutting concerns like security and validation.


Last updated