Skip to content

Decorator

In one line

A decorator is a function that takes another function and returns a modified version, applied with the @ syntax.

In simple words

A decorator is a function that wraps another function, adding behavior before or after the original function runs. You apply it with the @decorator_name syntax above a function definition.

Decorators are useful for cross-cutting concerns: logging, timing, caching, access control, input validation. Instead of repeating this code in every function, you write it once as a decorator and apply it where needed.

A decorator takes a function as input and returns a new function (the wrapper). The wrapper calls the original function and adds extra behavior. Decorators can also accept arguments by using a decorator factory.

Example

python
def log_calls(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

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

add(3, 5)
# Prints: Calling add
# Prints: add returned 8

Decorators wrap functions to add behavior. The @ syntax applies them. The wrapper calls the original and adds extra logic.

Common confusions

  • Confused with: closure

    The difference: A decorator is a function that modifies another function. A closure is a function that captures variables from its enclosing scope. Decorators often use closures (the wrapper is a closure), but they are different concepts.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary