Python Decorators Explained with Examples
programming

Python Decorators Explained with Examples

Master Python decorators - understand how they work, when to use them, and see practical examples you can use today.

Author

Md Mim Shifat

Full Stack Developer

2024-01-10 6 min read

Python Decorators Explained

Decorators are one of Python's most powerful features. They allow you to modify the behavior of functions or classes without changing their source code.

What is a Decorator?

A decorator is a function that takes another function and extends its behavior without explicitly modifying it.

Basic Syntax

Python
@decorator
def function():
    pass

# This is equivalent to:
def function():
    pass
function = decorator(function)

Creating Your First Decorator

Python
def my_decorator(func):
    def wrapper():
        print("Something before the function.")
        func()
        print("Something after the function.")
    return wrapper

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

say_hello()
# Output:
# Something before the function.
# Hello!
# Something after the function.

Decorators with Arguments

Python
def repeat(times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(3)
def greet(name):
    print(f"Hello, {name}!")

greet("World")
# Prints "Hello, World!" three times

Practical Use Cases

### 1. Timing Functions

Python
import time

def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} took {end - start:.2f} seconds")
        return result
    return wrapper

### 2. Authentication

Python
def require_auth(func):
    def wrapper(user, *args, **kwargs):
        if not user.is_authenticated:
            raise PermissionError("Authentication required")
        return func(user, *args, **kwargs)
    return wrapper

Conclusion

Decorators are essential for writing clean, maintainable Python code. They follow the DRY principle and make your code more readable.

Python
Decorators
Functions
Best Practices