The syntax for decorators with arguments is a bit different - the decorator with arguments should return a function that will take a function and return another function. So it should really return a normal decorator. A bit confusing, right? What I mean is:

def decorator_factory(argument):
    def decorator(function):
        def wrapper(*args, **kwargs):
            funny_stuff()
            something_with_argument(argument)
            result = function(*args, **kwargs)
            more_funny_stuff()
            return result
        return wrapper
    return decorator

Here you can read more on the subject - it's also possible to implement this using callable objects and that is also explained there.

Usage:

@decorator_factory("Some argument")
def function_to_be_decorated(args):
    print(f"Do something with '{args}'.")

decorator_factory("Some argument") uses the given argument to create a standard, argumentless decorator. So the following block is functionally identical to the one above:

created_decorator = decorator_factory("Some argument")

@created_decorator
def function_to_be_decorated(args):
    print(f"Do something with '{args}'.")
Answer from t.dubrownik on Stack Overflow
Top answer
1 of 16
1289

The syntax for decorators with arguments is a bit different - the decorator with arguments should return a function that will take a function and return another function. So it should really return a normal decorator. A bit confusing, right? What I mean is:

def decorator_factory(argument):
    def decorator(function):
        def wrapper(*args, **kwargs):
            funny_stuff()
            something_with_argument(argument)
            result = function(*args, **kwargs)
            more_funny_stuff()
            return result
        return wrapper
    return decorator

Here you can read more on the subject - it's also possible to implement this using callable objects and that is also explained there.

Usage:

@decorator_factory("Some argument")
def function_to_be_decorated(args):
    print(f"Do something with '{args}'.")

decorator_factory("Some argument") uses the given argument to create a standard, argumentless decorator. So the following block is functionally identical to the one above:

created_decorator = decorator_factory("Some argument")

@created_decorator
def function_to_be_decorated(args):
    print(f"Do something with '{args}'.")
2 of 16
559

Edit : for an in-depth understanding of the mental model of decorators, take a look at this awesome Pycon Talk. well worth the 30 minutes.

One way of thinking about decorators with arguments is

@decorator
def foo(*args, **kwargs):
    pass

translates to

foo = decorator(foo)

So if the decorator had arguments,

@decorator_with_args(arg)
def foo(*args, **kwargs):
    pass

translates to

foo = decorator_with_args(arg)(foo)

decorator_with_args is a function which accepts a custom argument and which returns the actual decorator (that will be applied to the decorated function).

I use a simple trick with partials to make my decorators easy

from functools import partial

def _pseudo_decor(fun, argument):
    def ret_fun(*args, **kwargs):
        #do stuff here, for eg.
        print ("decorator arg is %s" % str(argument))
        return fun(*args, **kwargs)
    return ret_fun

real_decorator = partial(_pseudo_decor, argument=arg)

@real_decorator
def foo(*args, **kwargs):
    pass

Update:

Above, foo becomes real_decorator(foo)

One effect of decorating a function is that the name foo is overridden upon decorator declaration. foo is "overridden" by whatever is returned by real_decorator. In this case, a new function object.

All of foo's metadata is overridden, notably docstring and function name.

>>> print(foo)
<function _pseudo_decor.<locals>.ret_fun at 0x10666a2f0>

functools.wraps gives us a convenient method to "lift" the docstring and name to the returned function.

from functools import partial, wraps

def _pseudo_decor(fun, argument):
    # magic sauce to lift the name and doc of the function
    @wraps(fun)
    def ret_fun(*args, **kwargs):
        # pre function execution stuff here, for eg.
        print("decorator argument is %s" % str(argument))
        returned_value =  fun(*args, **kwargs)
        # post execution stuff here, for eg.
        print("returned value is %s" % returned_value)
        return returned_value

    return ret_fun

real_decorator1 = partial(_pseudo_decor, argument="some_arg")
real_decorator2 = partial(_pseudo_decor, argument="some_other_arg")

@real_decorator1
def bar(*args, **kwargs):
    pass

>>> print(bar)
<function __main__.bar(*args, **kwargs)>

>>> bar(1,2,3, k="v", x="z")
decorator argument is some_arg
returned value is None
🌐
Miguel Grinberg
blog.miguelgrinberg.com › post › the-ultimate-guide-to-python-decorators-part-iii-decorators-with-arguments
The Ultimate Guide to Python Decorators, Part III: Decorators with Arguments - miguelgrinberg.com
You may expect that decorator arguments are somehow passed into the function along with this f argument, but sadly Python always passes the decorated function as a single argument to the decorator function.
Discussions

How does a decorator with arguments work behind the screen?
It doesn't "know", it basically just does tmp = do_sth_if_true(True), then yeah = tmp(yeah). To make this work, you want do_sth_if_true to be a function that returns a decorator. More on reddit.com
🌐 r/learnpython
7
35
October 19, 2022
Passing arguments to a decorator in a class
I’m using argparse to instantiate a class, the class itself has a decorator I’m using that accept arguments, the problem is that I can’t use arguments from the __init__() method, because I get a NameError. Class level arguments work. Is there any way I can pass arguments to a decorator? More on discuss.python.org
🌐 discuss.python.org
11
0
April 30, 2024
How to use self with decorator?
The decorator is binding to an unbound method of your class. Ie. it's basically the function unassociated with any self object. As such, unless the event explicitly passes it, there's no-where for the self object to come from - no self exists at the time you bound the method, and the event dispatcher doesn't even have a reference to an object of this class. If you want to bind the event to a particular object's method, you need to do it to a bound method, for which you need an actual instance. Eg. you could do this on __init__: def __init__(self): self.active = True window.event('on_key_press')(self.binding) (Though there may be other ways of binding like this more natural than reusing the decorator - this'll depend on what library you're using) More on reddit.com
🌐 r/learnpython
2
2
July 17, 2021
Why does Python @property decorator take 4 arguments if we only pass it 1?
On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: Limiting your involvement with Reddit, or Temporarily refraining from using Reddit Cancelling your subscription of Reddit Premium as a way to voice your protest. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnprogramming
5
1
September 17, 2023
🌐
Real Python
realpython.com › primer-on-python-decorators
Primer on Python Decorators – Real Python
September 1, 2026 - If you want your decorator to also take arguments, then you need to nest the wrapper function inside another function. In this case, you usually end up with three return statements.
🌐
GeeksforGeeks
geeksforgeeks.org › python › decorators-with-parameters-in-python
Decorators with parameters in Python - GeeksforGeeks
July 11, 2025 - Parameter: expected_type specifies the type that all arguments should be. Inner Function decorator: Takes the function func to be decorated.
🌐
Reddit
reddit.com › r/learnpython › how does a decorator with arguments work behind the screen?
r/learnpython on Reddit: How does a decorator with arguments work behind the screen?
October 19, 2022 -

I am learning python decorators and having some doubts with decorators with arguments. I will try to make my point clear (Or my doubts, better say) with examples:

If I execute the following piece of code:

def do_function_twice(func):
	print("Inside decorator")
	@functools.wraps(func)
	def wrapper(*arg):
		print("Inside wrapper")
		func(*arg)
		return func(*arg)
	return wrapper

@do_function_twice
def print_msg(msg):
	print(msg)
	return f"What is up buddy"

I receive Inside decorator as I was expecting, because behind the scenes python did print_msg = do_function_twice(print_msg)

What if I try creating a decorator with an argument like the following?

def do_sth_if_true(bool_):
	print("Inside do_sth_if_true")
	def repeat_func(func):
		print("Inside repeat_func")
		func()
		return func()
	return repeat_func

@do_sth_if_true(True)
def yeah():
	print("Yeah")

If I execute the script I receive:

Inside do_sth_if_true
Inside repeat_func
Yeah
Yeah

I can imagine it is doing yeah = do_sth_if_true(True)(yeah) behind the scenes (So it is calling the wrapping function, in this example called repeat_func. My question would be: How does python know which way to apply the decorator?

Top answer
1 of 4
8
It doesn't "know", it basically just does tmp = do_sth_if_true(True), then yeah = tmp(yeah). To make this work, you want do_sth_if_true to be a function that returns a decorator.
2 of 4
5
So under the hood all a decorator is is a function that returns a function. The handy syntax basically says "give the function I'm about to define to this other function and store the result of that as the name of the original function" Decorators with arguments are just a little special though. Under the hood what happens is the decorator siphons off the arguments first then the underlying function. Or in code this is happening: @some_decorator def my_func(arg1, arg2): pass Is turning into: def my_func(arg1, arg2): pass my_func = some_decorator(my_func) And with arguments: @some_decorator(arg1) def my_func(arg2, arg3): pass Turns into: def my_func(arg2, arg3): pass my_func = some_decorator(arg1)(my_func) The practical application of the above means that for decorators with arguments they no longer turn the modified function, but return a function that then returns a function that does the modification. In other words they curry (aka partial argument application) the arguments passed to the decorator and then pass the function to the result. Remember that a decorator is a function that returns a function, which is still true here. Just instead of literally wrapping the function you're making a call to get the thing to use to wrap it first (hence parenthesis). >>> def dec(f): ... def w(): ... print("wrapped!") ... return f() ... return w ... >>> @dec ... def my_func(): ... print("hi") ... >>> my_func() wrapped! hi >>> def dec_factory(arg): ... def dec(f): ... def w(): ... print(f"wrapped with {arg}!") ... return f() ... return w ... return dec ... >>> @dec_factory("arguments") ... def my_func(): ... print("hi") ... >>> my_func() wrapped with arguments! hi
🌐
Python Tutorial
pythontutorial.net › home › advanced python › python decorator with arguments
Python Decorator with Arguments
March 27, 2025 - from functools import wraps def repeat(fn): @wraps(fn) def wrapper(*args, **kwargs): for _ in range(5): result = fn(*args, **kwargs) return result return wrapper @repeat def say(message): ''' print the message Arguments message: the message to show ''' print(message) say('Hello')Code language: Python (python) ... What if you want to execute the say() function repeatedly ten times. In this case, you need to change the hard-coded value 5 in the repeat decorator.
🌐
OneUptime
oneuptime.com › home › blog › how to create custom decorators with arguments in python
How to Create Custom Decorators with Arguments in Python
January 30, 2026 - Learn how to create Python decorators that accept arguments using nested functions and functools.wraps for flexible behavior.
Find elsewhere
🌐
CodingNomads
codingnomads.com › python-decorators-with-arguments
Python Decorators With Arguments
To be able to handle arguments that you pass to your decorator, you need to go deeper to yet another level by adding another function wrapper to your decorator construct. Instead of the conceptually descriptive but clunky name decorator_func_with_argument(), you'll name this decorator function add_message_from():
🌐
W3Schools
w3schools.com › python › python_decorators.asp
Python Decorators
Sometimes the decorator function ... function, this way the wrapper function can accept any number, and any type of arguments, and pass them to the decorated function. Secure the function with *args and **kwargs arguments:...
🌐
Python.org
discuss.python.org › python help
Passing arguments to a decorator in a class - Python Help - Discussions on Python.org
April 30, 2024 - I’m using argparse to instantiate a class, the class itself has a decorator I’m using that accept arguments, the problem is that I can’t use arguments from the __init__() method, because I get a NameError. Class level ar…
🌐
DEV Community
dev.to › apcelent › python-decorator-tutorial-with-example-529f
Python Decorator with Arguments: Python Decorator Tutorial with Example - DEV Community
July 30, 2018 - def inner_function(function): @wraps(function) def wrapper(*args, **kwargs): print "Arguements passed to decorator %s and %s" % (arg1, arg2) function(*args, **kwargs) return wrapper return inner_function ... Author of Web Development with Django Cookbook. ... Looks like a useful article. But can you please correct the indentation of the Python code?
🌐
Medium
medium.com › @rahulkp220 › even-more-python-decorators-6f283e276770
Python Decorators with arguments! | by Rahul Lakhanpal | Medium
June 27, 2016 - You must be seeing that the syntax is very complex in the first look but as you dig deeper , its just reveals itself very clearly. What we have done here is that we have added another set of function on top of the original decorator function and passed our arguments to that high level outer function.
🌐
J-O Eriksson's blog
joeriksson.io › blog › Decorator-with-arguments
J-O Eriksson's blog – Pieces of Py #1: Decorator with arguments
July 9, 2019 - This post is a simple example which explains how to create a decorator function that accepts and uses argument(s). A decorator that would accept an argument could look like this: @mydecorator(my_argument) def my_decorated_function(input): return input A simple scenario could be that you would like to print something …
🌐
Medium
medium.com › @pouyahallaj › python-decorators-with-arguments-enhancing-functionality-with-elegance-85f63fce1fde
Python Decorators with Arguments: Enhancing Functionality with Elegance
November 4, 2024 - Before diving into decorators with ... In Python, a decorator is a function that takes another function as an argument and extends or modifies its behavior without changing its source code....
🌐
Flexiple
flexiple.com › python › decorators-parameters-python
Decorators With Parameters In Python - Flexiple - Flexiple
March 12, 2024 - Implementing a decorator with parameters in Python involves creating a wrapper function around the original decorator, enabling it to accept arguments.
🌐
The Python Coding Stack
thepythoncodingstack.com › the python coding stack › demystifying decorators • they don't need to be cryptic
Demystifying Decorators • They Don't Need to be Cryptic
July 15, 2025 - Finally, since the purpose of store_arguments()—we'll call this a decorator soon—is to store the arguments within the list data, you also replace the argument in data.append(). I chose to use a tuple that contains args and kwargs—args is itself a tuple, and kwargs is a dictionary. I'll be publishing a series on functions soon that will discuss *args and **kwargs in more detail. Here's the output from this code—I reformatted the output of the final list for clarity: I love Python 42 99 256 10:20:30 [ (('I love Python',), {}), ((42, 99, 256), {}), ((10, 20, 30), {'sep': ':'}), ]
🌐
GitHub
gist.github.com › 9860941
Python decorator with arguments · GitHub
decorator_with_args = lambda d: lambda *args, **kwargs: lambda func: wraps(func)(d(func, *args, **kwargs))
🌐
LabEx
labex.io › tutorials › python-how-to-create-a-decorator-that-accepts-arguments-in-python-415775
How to create a decorator that accepts arguments in Python | LabEx
While the basic decorator syntax is straightforward, Python also allows you to create decorators that accept arguments. This can be useful when you want to customize the behavior of your decorator or make it more flexible. The syntax for a decorator with arguments is as follows:
🌐
Python Morsels
pythonmorsels.com › decorators-with-optional-arguments
Decorators with optional arguments - Python Morsels
July 1, 2025 - Some decorators in Python accept optional arguments. Python's dataclass decorator works with arguments:
🌐
Python Morsels
pythonmorsels.com › making-decorator-accepts-arguments
Making a decorator that accepts arguments - Python Morsels
April 19, 2026 - Our first_arg_is_not_none decorator caused our greet function to raise an exception whenever None was given as the first argument. Let's modify our decorator so that it accepts the value that shouldn't be allowed. We'll also rename our decorator to first_arg_is_not (since we'll be able to use it with values besides None).