68

Is there a way to combine two decorators into one new decorator in python?

I realize I can just apply multiple decorators to a function, but I was curious as to whether there's some simple way to combine two into a new one.

1

7 Answers 7

77

A bit more general:

def composed(*decs):
    def deco(f):
        for dec in reversed(decs):
            f = dec(f)
        return f
    return deco

Then

@composed(dec1, dec2)
def some(f):
    pass

is equivalent to

@dec1
@dec2
def some(f):
    pass
4
  • 4
    return lambda x: reduce(lambda y, f: f(y), decs, x)... well, after typing this I see the advantage of your code :) Commented Mar 23, 2011 at 18:13
  • 1
    Really useful, thank you. I used this to create a new decorator: @new_decorator = composed(dec1(some_params), dec2) Which I'm using to have the decorator logic in one place (it's for user authorisation of a django view). Your code will be a useful addition to the toolbox. Cheers.
    – Ludo
    Commented Mar 24, 2011 at 10:40
  • 1
    The order of execution of the decorators in the last example is dec2 then dec1, i.e. dec1(dec2(some(f))). dec2 gets executed first. Commented Nov 24, 2020 at 12:14
  • 1
    @How to do the same for decorators that taking an args and kwargs? Commented Oct 28, 2021 at 10:09
38

Yes. See the definition of a decorator, here.

Something like this should work:

def multiple_decorators(func):
   return decorator1(decorator2(func))

@multiple_decorators
def foo(): pass
3
  • Thanks, and also a useful link. I've opted for the answer with the more general solution. Cheers.
    – Ludo
    Commented Mar 24, 2011 at 10:41
  • I like how concise this solution is and have found it helpful in my project. Commented Apr 14, 2014 at 20:02
  • Ditto. Although the accepted answer is admittedly awesome for the general case, this answer concisely exhibits one decorator deferring to multiple other decorators whose names are statically known at interpretation time. Since this is the usual case, this is great too! Upvotes for all ensue. Commented Aug 20, 2016 at 3:58
17

Decorators are just functions that take a function as input and return a new function. This:

@deco
def foo():
    ...

Is equivalent to this:

def foo():
    ...

foo = deco(foo)

In other words, the decorated function (foo) is passed as an argument to the decorator, and then foo is replaced with the return value of the decorator. Equipped with this knowledge, it's easy to write a decorator that combines two other decorators:

def merged_decorator(func):
    return decorator2(decorator1(func))

# now both of these function definitions are equivalent:

@decorator2
@decorator1
def foo():
    ...

@merged_decorator
def foo():
    ...

It gets a little trickier if the decorators accept arguments, like these two:

@deco_with_args2(bar='bar')
@deco_with_args1('baz')
def foo():
    ...

You might wonder how these decorators are even implemented. It's actually pretty simple: deco_with_args1 and deco_with_args2 are functions that return another function decorator. Decorators with arguments are essentially decorator factories. The equivalent of this:

@deco_with_args('baz')
def foo():
    ...

Is this:

def foo():
    ...

real_decorator = deco_with_args('baz')
foo = real_decorator(foo)

In order to make a decorator that accepts arguments and then applies two other decorators, we have to implement our own decorator factory:

def merged_decorator_with_args(bar, baz):
    # pass the arguments to the decorator factories and
    # obtain the actual decorators
    deco2 = deco_with_args2(bar=bar)
    deco1 = deco_with_args1(baz)

    # create a function decorator that applies the two
    # decorators we just created
    def real_decorator(func):
        return deco2(deco1(func))

    return real_decorator

This decorator can then be used like this:

@merged_decorator_with_args('bar', 'baz')
def foo():
    ...
7

If you don't want to repeat yourself too much in a test suite, you could do like this::

def apply_patches(func):
    @functools.wraps(func)
    @mock.patch('foo.settings.USE_FAKE_CONNECTION', False)
    @mock.patch('foo.settings.DATABASE_URI', 'li://foo')
    @mock.patch('foo.connection.api.Session.post', autospec=True)
    def _(*args, **kwargs):
        return func(*args, **kwargs)

    return _

now you can use that in your test suite instead of a crazy amount of decorators above each function::

def ChuckNorrisCase(unittest.TestCase):
    @apply_patches
    def test_chuck_pwns_none(self):
        self.assertTrue(None)
0
5

If the decorators don't take additional arguments, you could use

def compose(f, g):
    return lambda x: f(g(x))

combined_decorator = compose(decorator1, decorator2)

Now

@combined_decorator
def f():
    pass

will be equivalent to

@decorator1
@decorator2
def f():
    pass
3
  • Isn't that "apply multiple decorators to a function"?
    – user395760
    Commented Mar 23, 2011 at 17:54
  • @delnan: Isn't that "some simple way to combine two [decorators] into a new one"? :) Commented Mar 23, 2011 at 17:57
  • Thank you. One of the decorators takes params though so have gone with the other answer.
    – Ludo
    Commented Mar 24, 2011 at 10:41
4

And to extend @Jochen's answer:

import click


def composed(*decs):
    def deco(f):
        for dec in reversed(decs):
            f = dec(f)
        return f
    return deco


def click_multi(func):
    return composed(
        click.option('--xxx', is_flag=True, help='Some X help'),
        click.option('--zzz', is_flag=True, help='Some Z help')
    )(func)


@click_multi
def some_command(**args):
    pass

In this example you can compose a new decorator that contains multiple decorators.

1
  • or also click_multi = composed(click.option('--xxx', is_flag=True, help='Some X help'),click.option('--zzz', is_flag=True, help='Some Z help')) Commented Nov 10, 2022 at 9:45
0

Python 3.9 we can use lambda expression as decorator. Combine using lambdas in a single line

example:

@lambda func: (lambda func: (lambda *variable: func(*variable).upper()))  (lambda *variable: func(*variable) + ' World')
def say():
    return "Hello"

print(say())

The above function has two decorators.

(lambda *variable: func(*variable) + ' World') -- this decoration concatenates " World".

lambda *variable: func(*variable).upper() -- this decoration converts to upper case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.