Equivalent to im_func for __new__?

I have a piece of code for automating monkey patches that caches a link to the im_func function, and then replaces this function when attaching the original im_func as an attribute ._unmonkeyed, for example:

class MonkeyPatch(object):
    '''A callable object to implement the monkey patch.  Stores the previous version in
       attribute _unmonkeyed and new version in _monkeyed.'''
    def __init__(self,source,target,attr):
        self._monkeyPatchSource=source
        self._monkeyPatchTarget=target
        self._monkeyPatchAttr=attr
        self._monkeyed=getattr(source,attr).im_func
        self._unmonkeyed=getattr(target,attr,None)
        setattr(target,attr,self)

    ###a few more methods here

    def __get__(self,inst,cls=None):  #(self,*args,**kwds):
        tmp=lambda *args,**kwds: self._monkeyed(inst,*args,**kwds)
        tmp._unmonkeyed=lambda *args,**kwds: self._unmonkeyed(inst,*args,**kwds)
        return tmp

I don't really like Pythonista, so I'm sure thousands of reasons are a dumb way to do something, but it worked for me. Now I am in a place where I would like to fix the class method __new__to add some logic before invoking the existing one __new__. __new__does not have an attribute im_func, and this probably indicates that there are other methods that do not.

Is there a way to do the same job in a generic way (preferably without having to store a list of special cases) for methods without im_func?

- , , . , .

+4

Source: https://habr.com/ru/post/1568412/


All Articles