Is there a way to add an argument to class __init__ method with monkey patching?

1.9k views Asked by At

If there's a class

Class A:
    def __init__(arg1, kwarg1=...):
        ...something happens here with args and kwargs

is there a way to add another argument by monkey patching this class? How to keep everything that happens in it's __init__ in place, without repeating it anywhere?

3

There are 3 answers

3
Bob On BEST ANSWER

this worked:

from package import module

class ChangedInitClass(module.SomeClass):
    def __init__(self, arg1, another_arg, kwarg1=...):
        super().__init__(arg1, kwarg1=kwarg1)
        # does something with another_arg

module.SomeClass = ChangedInitClass
0
Alex G Rice On

You could probably do the same thing by subclassing, and no need to monkey patch. You could add new positional args, or just throw more items into kwargs. Something like this:

Class A:
    """same class A as before"""
    def __init__(self, arg1, kwarg1=...):
        ...something happens here with args and kwargs

Class B(A):
    def __init__(self, another_arg, arg, **kwargs):
        A.__init__(self, arg, **kwargs)
        # B does something with another_arg here
0
Karolius On

It affects also classes that are subclasses of A:

old_init = A.__init__

def new_init(self, foo, *args, *kwargs):
    old_init(self, *args, *kwargs)
    self.foo = foo

A.__init__ = new_init