Propagating arguments to decorator which combines other decorators
<p>I have a scenario like:</p>

<pre><code>@decorator_one(1)
@foo
@bar
def my_decorated_func():
    pass
</code></pre>

<p>I am trying to condense this into something like:</p>

<pre><code>@my_custom_decorator(1)
def my_decorated_func():
    pass
</code></pre>

<p>This is straightforward if I have decorators that do not have <code>(1)</code> option:</p>

<pre><code>def my_custom_decorator(f):
    @decorator_one
    @foo
    @bar
    def wrapped():
        pass
    return wrapped
</code></pre>

<p>However I am uncertain how to properly propagate the argument to the first wrapper. </p>

<p>In this case, I am comfortable assuming that if I pass 1 to my_custom_decorator that it will always and only be the arg for decorator_one.</p>

<p><code>@decorator_one(1)</code> means that there is a callable that returns a decorator; call it a decorator <em>factory</em>. <code>decorator_one(1)</code> returns the decorator that is then applied to the function.</p>

<p>Just pass on the arguments from your own decorator factory:</p>

<pre><code>def my_custom_decorator(*args, **kwargs):  # the factory
    def decorator(f):                      # the decorator
        @decorator_one(*args, **kwargs)
        @foo
        @bar
        def wrapped():
            pass
        return wrapped
    return decorator
</code></pre>

<p>I used <code>*args, **kwargs</code> to pass on arbitrary arguments to the wrapped decorator factory <code>decorator_one()</code>, but you could also use explicitly named paramaters.</p>

python decorator python-decorators