DEV Community

Cover image for Understanding Python Decorators with Real-Life Examples ✨
Chimezie Nwankwo
Chimezie Nwankwo

Posted on

Understanding Python Decorators with Real-Life Examples ✨

If you’ve been learning Python for a while, you’ve probably come across the term decorators. At first, they can seem confusing, but don’t worry — in this post, we’ll break them down into simple terms and walk through real-life examples that will make them click.

🔹 What is a Decorator?

A decorator in Python is simply a function that wraps another function to add extra functionality without modifying its original code.

Think of it like adding extra toppings to your pizza 🍕 — the base pizza is still the same, but the toppings add more flavor.

🔹 A Simple Example


python
def my_decorator(func):
    def wrapper():
        print("Before the function runs")
        func()
        print("After the function runs")
    return wrapper

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

say_hello()

Output:    
Before the function runs
Hello, world!
After the function runs
---

🔹 Real-Life Example 1: Logging
Imagine you want to log every time a function runs.

def log_decorator(func):
    def wrapper(*args, **kwargs):
        print(f"Function '{func.__name__}' is being called...")
        return func(*args, **kwargs)
    return wrapper

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

print(add(5, 3))
---
🔹 Real-Life Example 2: Timing a Function

Want to check how long a function takes to run? Use a decorator!

import time

def timer_decorator(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"Function '{func.__name__}' ran in {end - start:.4f} seconds")
        return result
    return wrapper

@timer_decorator
def slow_function():
    time.sleep(2)
    print("Finished slow function!")

slow_function()
---
🔹 Why Use Decorators?

Cleaner and reusable code ✅
Helps separate logic (e.g., logging, authentication, timing) ✅
Keeps your functions focused on their main job ✅
---
🔹 Key Takeaway

Decorators may seem tricky at first, but they’re just a powerful way to extend functions without changing them directly. Start small, and you’ll quickly see how useful they are in real projects!
---

💡 What’s your favorite use case for decorators in Python? Share it in the comments! 🚀
Enter fullscreen mode Exit fullscreen mode

Top comments (0)