Mr_and_Mrs_D
Mr_and_Mrs_D

Reputation: 34086

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

Upvotes: 3

Views: 1446

Answers (1)

tayfun
tayfun

Reputation: 3135

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

Upvotes: 4

Related Questions