Pre process arguments passed to all instance methods in Python

647 views Asked by At
class SimpleClass(object):
     def A(self, *args):
          ...
     def B(self, *args):
          ...
     def C(self, *args):
          ...

Is there anyway to catch the arguments passed to A, B, C, modify those arguments and pass the modified arguments onto A, B, C without having to modify the existing code ?

Edit:

Answer: use a class decorator, that decorates all methods of the class with another decorator.

The method decorator performs the pre-processing.

1

There are 1 answers

0
Yevhen Kuzmovych On

Try this:

from types import FunctionType

class SimpleClass(object):
    def A(self, *args):
        pass
    def B(self, *args):
        pass
    def C(self, *args):
        pass


def methods(cls):
    """List of all method in class."""
    return [x for x, y in cls.__dict__.items() if type(y) == FunctionType]

def args_decorator(method):
    """Decorator for SimpleClass methods"""
    def wrapper(self, *args):
        new_args = list(args)
        # change new_args here
        return method(self, *new_args)
    return wrapper


for method in methods(SimpleClass):
    setattr(SimpleClass, method, args_decorator(SimpleClass.__dict__[method]))

Though if you can change your SimpleClass I'd suggest using decorator like so:

def args_decorator(method):
    def wrapper(self, *args):
        new_args = list(args)
        # change new_args here
        return method(self, *new_args)
    return wrapper

class SimpleClass(object):
    @args_decorator
    def A(self, *args):
        pass
    @args_decorator
    def B(self, *args):
        pass
    @args_decorator
    def C(self, *args):
        pass