Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pre process arguments passed to all instance methods in Python

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.

like image 569
Quan Vuong Avatar asked Jun 28 '26 13:06

Quan Vuong


1 Answers

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
like image 85
Yevhen Kuzmovych Avatar answered Jul 01 '26 11:07

Yevhen Kuzmovych



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!