Is it possible monkey patch like this?

Peter Otten __peter__ at
Tue Dec 18 13:35:54 CET 2012

Marc Aymerich wrote:

> Dear all,
> I want to monkey patch a method that has lots of code so I want to avoid
> copying all the original method for changing just two lines. The thing is
> that I don't know how to do this kind of monkey patching.
> Consider the following code:
> class OringinalClass(object):
>     def origina_method(self, *args, **kwargs):
>         ...
>         if some_condition(): # This condition should be changed
>             raise SomeException
>         ...
>         if some_condition():
>             ...
>             #if some_condition(local_variable): # This condition should be
>             #added
>             #    raise SomeException
>         ...
> Is it possible to tell Python to run the original method without stopping
> when an exception is raised? 


> so I can catch them on a wrapper method and
> apply my conditional there.
> Any other idea on how to monkey patch those two conditionals ?

One of the cleanest alternatives is to factor out the condition in the 
original class and then use a subclass:

class Original:
    def method(self, *args, **kw):
    def check_condition(self, ...):
        if condition:
            raise SomeException

class Sub(Original):
    def check_condition(self, ...):

If you insist on monkey-patching possible solutions depend on the actual 
conditions. If some_condition() is a function, replace that function. If it 
is actually an expression tweak the arguments. E. g:

>>> class Original:
...     def method(self, x):
...             if x < 0: raise ValueError
...             print x * x
>>> Original().method(-2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in method
>>> class Int(int):
...     def __lt__(self, other): return False # a blunt lie
>>> Original().method(Int(-2))

This tends to get complex quickly, so in the long run you will not be happy 
with that approach...

More information about the Python-list mailing list