0

I am aware there was a post related to this question. But that post was not what I have in mind. So I am wondering if there is only one way to approach it? Or there exists multiple ways.

I am not sure if the title of this post makes sense. But I encountered a problem that I wanted to create many decorator functions with the build-in method. What is meant is as follows:

@some_decorator_fcn
def function_1(data):
    return data.method_1()

@some_decorator_fcn
def function_2(data):
    return data.method_2()

@some_decorator_fcn
def function_3(data):
    return data.method_3()

......
......

So basically, I need as many methods as possible. I know we can use dir(data) to find all relevant methods, but is there a way to automate this process without explicitly writing all of the methods out? Thank you.

RyanKao
  • 321
  • 1
  • 5
  • 14
  • Thanks martineau for pointing out, but the post was not what I have in mind. I want to ask whether there is a different way to achieve my goal. – RyanKao Aug 05 '18 at 03:48

1 Answers1

0

You can wrap your functions into the class and write another decorator which will decorate all your functions. So this decorator looks like (maybe you need to exclude magic methods like __init__, do it if you need):

def wrap_all_methods(decorator):
    def wrapper(cls):
        for attr in cls.__dict__: # iterate over all attributes
            if callable(getattr(cls, attr)): # if attribute is a function
                setattr(cls, attr, decorator(getattr(cls, attr))) # decorate this function
        return cls
    return wrapper

Then create class with your functions:

@wrap_all_methods(some_decorator_fcn)
class Functions:
    def function_1(data):
        return data.method_1()
    def function_2(data):
        return data.method_2()
    ...
Lev Zakharov
  • 2,409
  • 1
  • 10
  • 24
  • Hi Lev, is there a different way to do this? I mean, it looks like I did not have to use @some_decorator_fcn every time. But still need manually write all functions down. What I have in mind (did not know if this works) is that, to create a list of [method_1, method_2, method_3, ...], do something (pass as arguments?), and use only one wrapper function? – RyanKao Aug 05 '18 at 03:43