0

In our code base we used to define an 'action' to any method that was decorated with a custom decorator function.

The definition of 'action' kept growing, so more decorators were added. Nowadays, we define an 'action' to any method that is decorated with 4 (sometimes 5) custom decorator functions (order is relevant as you may expect)

@decorator1
@decorator2
@decorator3
@decorator4
def foo(arg):
  pass

We've ended up with several (+50) methods that are repeating this design across our codebase:

@decorator1
@decorator2
@decorator3
@decorator4
def fn1(arg):
  pass

...

@decorator1
@decorator2
@decorator3
@decorator4
@decorator5
def fn50(arg):
  pass

I'd like to clean this duplication (when @decorator4 was added to the definition, we needed to update 50+ places)

I've thought 2 possible solutions here (note that both solutions are equivalent, only changing the syntax):

1.- 'Decorator of Decorators' Solution

Briefly:

@decorator1
@decorator2
@decorator3
@decorator4
@master_decorator(enable_optional_decorator=False)
def fn1(arg)

This decorator would need to accept (at least) one argument for enabling/disabling optional decorators

2.- 'Wrapping Class' Solution

class MasterDecorator:

  def __init__(self, raw_method, enable_optional_decorator=False):
     pass

  def __call__(self)

...

# no decorators here
def fn1(arg):
  pass


# when calling fn1
MasterDecorator(fn_1)(args)

Which solution would be better? which would be more pythonist? is there any better design to remove duplication here?

==EDIT==

Suggested duplication: not asking How to create a master decorator but rather which would be a pythonist design for cleaning this duplication

Manu Artero
  • 9,238
  • 6
  • 58
  • 73

0 Answers0