Python Mastery – From Basics to Brilliance / Advanced Python Topics

Decorators

πŸŽ€ Decorators

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

It uses the @ symbol.


πŸ”Ή Basic Example

def decorator(func):
    def wrapper():
        print("Before function")
        func()
        print("After function")

    return wrapper

@decorator
def greet():
    print("Hello!")

greet()
Before function
Hello!
After function

πŸ”„ How It Works

This:

@decorator
def greet():
    print("Hello!")

is equivalent to:

def greet():
    print("Hello!")
greet = decorator(greet)

So Python passes greet to the decorator.


🧩 Decorator with Arguments

If the original function accepts arguments, the wrapper can use *args and **kwargs.

def decorator(func):
    def wrapper(*args, **kwargs):
        print("Function called")
        return func(*args, **kwargs)

    return wrapper

@decorator
def add(a, b):
    return a + b

print(add(10, 5))
Function called
15

⭐ Common Uses

Decorators are commonly used for:

  • πŸ” Authentication

  • ⏱️ Timing functions

  • πŸ“ Logging

  • βœ… Validation

  • πŸ”’ Access control

Decorators rely on two concepts you've already learned: first-class functions and closures.