-1

Let's say I have a function that is decorated by multiple decorators.

# file.py

@deco1
@deco2('param')
@deco3(
    'multiple',
    'long',
    'params'
)
@deco4('multiple', 'params')
def foo():
    """Function foo
    """
    pass

Let's just say it looks very dirty. VERY dirty.

I want to be able to do something like this.

# another_file.py

@deco1
@deco2('param')
@deco3(
    'multiple',
    'long',
    'params'
)
@deco4('multiple', 'params')
def all_decorators_for_foo():
    ...
# file.py

from another_file import all_decorators_for_foo

@all_decorators_for_foo
def foo():
    """Yay!
    """
    ...

Just for the sake of context, the multiple decorators are swagger documentation decorators for sanic framework.

Is it possible in python to achieve something similar to this?

This question does not in any way answer my question. Decorators can anyway be stacked together and used. I want some sort of decorator that can be used in place of all the stacked decorators.

Diptangsu Goswami
  • 5,554
  • 3
  • 25
  • 36
  • 1
    Does this answer your question? [How to make a chain of function decorators?](https://stackoverflow.com/questions/739654/how-to-make-a-chain-of-function-decorators) – bigbounty Aug 02 '20 at 11:10
  • 1
    @bigbounty no it absolutely doesn't. Please read the question before marking it as a duplicate. – Diptangsu Goswami Aug 02 '20 at 11:18
  • Do you insist on that style of *applying* those decorators to `all_decorators_for_foo`, or could you *pass* them to it as arguments? – superb rain Aug 02 '20 at 11:26
  • @superbrain Anything that works. I just want my code to look pretty lol. But I also want to have the independence to add more decorators to `foo`. Like I want `@deco1` to be with `foo` and all the others grouped together. – Diptangsu Goswami Aug 02 '20 at 11:41
  • @DiptangsuGoswami Did you go through the answers in the attached link? If not see this - https://stackoverflow.com/a/29163633/6849682. The answer attached to your question uses the same concept - `decor1(decor2(func))(*args, **kwargs)`. So, it's a possible duplicate – bigbounty Aug 02 '20 at 12:04

1 Answers1

4

Yes you could. You can make another decorator that returns the decorated function like so:
all_decorators_for_foo.py

def all_decorators_for_foo(func):
    return deco1()(
        deco2('param')(
            deco3(
                'multiple',
                'long',
                'params'
            )(
                deco4('multiple', 'params')(
                    func
                )
            )
        )
    )

and then in file.py

from another_file import all_decorators_for_foo

@all_decorators_for_foo
def foo():
    pass
Diptangsu Goswami
  • 5,554
  • 3
  • 25
  • 36
Minion3665
  • 879
  • 11
  • 25