← Back to Blog
    TutorialFebruary 26, 20247 min read

    Python Decorators Explained with Simple Examples

    Understand Python decorators step by step. Learn how functions wrap other functions, pass arguments, and add reusable behavior with clean examples.

    Python Decorators Explained

    Decorators look intimidating at first, but the idea behind them is simple. A decorator is a function that adds behavior to another function without changing its code. Once the concept clicks, you will see decorators everywhere in Python.

    Functions Are Objects

    The key idea is that functions in Python are values. You can pass them around, store them in variables, and return them from other functions.

    def greet():
        return "hello"
    
    say = greet
    print(say())

    A Function That Wraps Another

    A decorator takes a function, wraps it in extra logic, and returns the new version. Here a wrapper makes any greeting uppercase.

    def shout(func):
        def wrapper():
            return func().upper()
        return wrapper
    
    def greet():
        return "hello"
    
    loud = shout(greet)
    print(loud())

    The @ Syntax

    Python offers a shortcut. Placing the decorator name with an at sign above a function applies it automatically. The result is identical to the manual version above.

    def shout(func):
        def wrapper():
            return func().upper()
        return wrapper
    
    @shout
    def greet():
        return "hello"
    
    print(greet())

    Handling Any Arguments

    Real functions take arguments, so a flexible wrapper uses args and kwargs to pass everything through untouched.

    def logged(func):
        def wrapper(*args, **kwargs):
            print("Calling", func.__name__)
            return func(*args, **kwargs)
        return wrapper
    
    @logged
    def add(a, b):
        return a + b
    
    print(add(2, 3))

    Decorators That Take Arguments

    Sometimes you want to configure a decorator, such as repeating a call a set number of times. This needs one more layer of functions.

    def repeat(n):
        def decorator(func):
            def wrapper():
                for _ in range(n):
                    func()
            return wrapper
        return decorator
    
    @repeat(3)
    def hi():
        print("hi")
    
    hi()

    Where You Will See Them

    Web frameworks use decorators to connect routes, testing tools use them to mark tests, and caching libraries use them to store results. Learning the pattern once unlocks all of these tools.

    Try It Yourself

    Open the playground and write a decorator that prints the word done after a function runs. Building one from scratch is the fastest way to truly understand decorators.

    By PythonExecutor Team

    Related Articles