Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monkey patch a python instance method using the original method from the class

I want to monkey patch a method of a library class to define a different default for a param. This fails:

from functools import partial

class A(object):
    def meth(self, foo=1):
        print(foo)

A.meth = partial(A.meth, foo=2)

a = A()
a.meth()

with:

Traceback (most recent call last):
  File "...", line 10, in <module>
    a.meth()
TypeError: meth() missing 1 required positional argument: 'self'

what is the correct way of doing this?

(Original code is using getattr on the method names in a loop)

The answers in the question linked involve defining a new module-level function - I would like to avoid a new function definition

like image 953
Mr_and_Mrs_D Avatar asked Jun 19 '26 05:06

Mr_and_Mrs_D


1 Answers

Use partialmethod:

In [32]: from functools import partialmethod

In [33]: A.meth = partialmethod(A.meth, foo=2)

In [34]: a = A()

In [35]: a.meth()
2
like image 103
tayfun Avatar answered Jun 21 '26 21:06

tayfun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!