Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 691
Bob Avatar asked Sep 06 '25 03:09

Bob


2 Answers

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
like image 89
Bob Avatar answered Sep 07 '25 17:09

Bob


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
like image 41
Karolius Avatar answered Sep 07 '25 16:09

Karolius