First of all, here is my (pseudo) code:
somemodule.py:
class parentclass(object):
def __init__(self):
if(not prevent_infinite_reursion) #Just to make shure this is not a problem ;)
self.somefunction()
def somefunction():
# ... deep down in a function ...
# I want to "monkey patch" to call constructor of childclass,
# not parentclass
parentclass()
othermodule.py
from somemodule import parentclass
class childclass(parentclass):
def __init__(self):
# ... some preprocessing ...
super(childclass, self).__init__()
The problem is, i want to monkey patch parent class, so it would call constructor of childclass, without changing code of somemodule.py. It doesn't matter if it's patched only in class instance(that's shure better) or globally.
I know i can override somefunction, but it contains too many lines of code, for this being sane.
Thanks!
asked May 13, 2013 at 7:56
offlinehacker
9421 gold badge9 silver badges14 bronze badges
1 Answer 1
You could use mock.patch for this:
class childclass(parentclass):
def somefunction(self):
with patch('somemodule.parentclass', childclass):
super(childclass, self).somefunction()
answered May 13, 2013 at 8:36
Lauritz V. Thaulow
51.3k13 gold badges76 silver badges94 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
abarnert
A nice clean way to do my "horribly hacky thing (1)".
offlinehacker
Hm it doesn't work in my case, because parentclass is eventually a children of some other class and parent of parentclass new method gets called and it creates parentclass instead of supposedly patched child class, will try to find how to manage that.
Lauritz V. Thaulow
@offlinehacker You can patch the
__new__ method as well. Also it might help to read where to patch.offlinehacker
@LauritzV.Thaulow eventually it worked like a charm with patching
__new__ of a top class. This one was hard. Thanks!Explore related questions
See similar questions with these tags.
lang-py
parentclassto instead construct achildclass, or only attempts withinparentclass, or only this specific attempt withinparentclass.somefunction, or one of the latter two but only whenselfis achildclass?parentclass().parentclasswith a wrapper that patches out__new__, calls the original, and restores__new__. (2) Replace each method ofparentclasswith a wrapper that runs the original inside a modifiedglobalswhereparentclasshas been replaced bychildclass. But I don't think either of these is a good enough idea to be worth coding.