Bob
Bob

Reputation: 6173

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?

Upvotes: 4

Views: 1980

Answers (3)

Karolius
Karolius

Reputation: 581

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

Upvotes: 2

Bob
Bob

Reputation: 6173

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

Upvotes: 3

Alex G Rice
Alex G Rice

Reputation: 1579

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

Upvotes: 0

Related Questions