Last modified: Nov 19, 2026

Python Decorator with Arguments

Decorators are one of Python's most powerful features. They let you wrap a function to change its behavior without editing its code.

But plain decorators have a limit. They take no options. Sometimes you want to pass a setting to the decorator itself.

That is where decorators with arguments come in. They look similar but need an extra layer of functions. This guide explains the pattern step by step.

What Is a Decorator?

A decorator is a function that takes another function and returns a new one. You apply it with the @ symbol above a function definition.

Here is a simple example without arguments.


def shout(func):
    def wrapper():
        return func().upper()
    return wrapper

@shout
def greet():
    return "hello"

print(greet())

HELLO

The shout decorator wraps greet and uppercases its result. No arguments are needed here.

Why Add Arguments to a Decorator?

Imagine you want to repeat a function a set number of times. The count should be flexible.

You could hardcode the number inside the decorator. But then every wrapped function repeats the same way.

Arguments make the decorator reusable. You write it once and configure it per function. This is the same idea behind the property decorator explained in other built-in tools.

The Three-Layer Pattern

A decorator with arguments needs three nested functions. Each layer has a clear job.

The outer function receives the decorator arguments. The middle function receives the target function. The inner function runs the actual wrapper code.


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(times=3)
def say_hi(name):
    print(f"Hi, {name}!")
    return name

say_hi("Anna")

Hi, Anna!
Hi, Anna!
Hi, Anna!

Notice the call order. repeat(times=3) runs first and returns decorator. Then decorator receives say_hi and returns wrapper.

When you call say_hi("Anna"), you are really calling wrapper("Anna"). The wrapper loops and calls the original function.

Step-by-Step Breakdown

Let's trace what happens at each stage. This makes the pattern easier to remember.

Step 1: Python sees @repeat(times=3). It calls repeat with times=3.

Step 2:repeat returns decorator. That function is then applied to say_hi.

Step 3:decorator returns wrapper. The name say_hi now points to wrapper.

Step 4: Calling say_hi runs the wrapper, which uses the captured times value.

The key idea is closures. Each nested function remembers the variables from the scope around it.

Preserving Function Metadata

Wrapping a function hides its original name and docstring. That can confuse debugging tools.

The standard fix is functools.wraps. It copies metadata from the original function to the wrapper.


from functools import wraps

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

@repeat(times=2)
def add(a, b):
    """Add two numbers."""
    return a + b

print(add(2, 3))
print(add.__name__)
print(add.__doc__)

5
add
Add two numbers.

Without wraps, the name would print as wrapper. Always use it in production code.

If you need to inspect wrapped functions further, this guide on inspecting a Python function signature shows how to read parameters safely.

Decorators with Positional Arguments

Arguments do not have to be keyword only. You can define the outer function with any parameters you like.


def prefix(text):
    def decorator(func):
        def wrapper(*args, **kwargs):
            return text + func(*args, **kwargs)
        return wrapper
    return decorator

@prefix("LOG: ")
def message():
    return "server started"

print(message())

LOG: server started

This pattern is handy for logging, tagging, or building formatted output strings.

Combining Decorators with Arguments and Caching

Decorators with arguments pair well with memoization. A cache decorator can accept a size limit or a key function.

For ready-made caching, Python ships with tools covered in Python caching with functools. You can also build your own version to learn the pattern.


def memoize(max_size):
    cache = {}
    def decorator(func):
        def wrapper(n):
            if n in cache:
                return cache[n]
            if len(cache) >= max_size:
                cache.clear()
            result = func(n)
            cache[n] = result
            return result
        return wrapper
    return decorator

@memoize(max_size=100)
def slow_square(n):
    return n * n

print(slow_square(4))
print(slow_square(4))

16
16

The second call returns instantly because the value is already stored. The max_size argument controls how much the cache can hold.

Common Mistakes to Avoid

Forgetting the extra layer. If you write def decorator(func, times), it will fail. The target function must be the only parameter of the middle function.

Missing wraps. Debugging gets harder when names and docstrings disappear.

Mutating shared state. Be careful with lists or dicts defined in the outer function. They persist across calls, which is sometimes useful and sometimes a bug.

Ignoring *args and **kwargs. A wrapper that only takes fixed parameters will break for other functions.

When Should You Use This Pattern?

Use decorators with arguments when behavior must be configurable. Good examples include retry counts, timeouts, log levels, and feature flags.

Keep them small and focused. A decorator that does too much becomes hard to test.

Also remember that decorators only run at definition time. The outer function runs once, not on every call.

Testing Decorators with Arguments

Testing is straightforward. Call the decorated function and check the output.

You can also test the decorator directly by applying it to a dummy function. This isolates the logic from real code.


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

calls = []
@repeat(times=2)
def track(x):
    calls.append(x)

track("a")
print(calls)

['a', 'a']

The list shows the wrapper ran twice. This confirms the argument was captured correctly.

For deeper debugging, tools that fetch a function name at runtime help, as shown in getting a Python function name at runtime.

Decorators in Real Projects

Frameworks use this pattern everywhere. Web frameworks apply route decorators with URL arguments. Task queues use decorators with retry settings.

Once you understand the three-layer structure, these libraries stop feeling like magic. They are just closures applied in a fixed order.

Practice by writing your own timing decorator. Then add an argument for how many runs to average.

Conclusion

Python decorators with arguments add one extra layer to the basic decorator pattern. The outer function takes the settings, the middle function takes the target, and the inner function does the work.

Use functools.wraps to keep metadata intact. Accept *args and **kwargs so your wrapper works with any function. Keep the logic small and testable.

With a little practice, this pattern becomes a natural tool in your Python toolkit.