Advantages of Using MethodType in Python

In fact the difference between adding methods dynamically at run time and your example is huge:

  • in your case, you just attach a function to an object, you can call it of course but it is unbound, it has no relation with the object itself (ie. you cannot use self inside the function)
  • when added with MethodType, you create a bound method and it behaves like a normal Python method for the object, you have to take the object it belongs to as first argument (it is normally called self) and you can access it inside the function

This example shows the difference:

def func(obj):
  print 'I am called from', obj
class A:
  pass
a=A()
a.func=func
a.func()

This fails with a TypeError: func() takes exactly 1 argument (0 given), whereas this code works as expected:

import types
a.func = types.MethodType(func, a) # or types.MethodType(func, a, A) for PY2
a.func()

shows I am called from <__main__.A instance at xxx>.


A common use of types.MethodType is checking whether some object is a method. For example:

>>> import types
>>> class A(object):
...     def method(self):
...         pass
...
>>> isinstance(A().method, types.MethodType)
True
>>> def nonmethod():
...     pass
...
>>> isinstance(nonmethod, types.MethodType)
False

Note that in your example isinstance(obj.func, types.MethodType) returns False. Imagine you have defined a method meth in class A. isinstance(obj.meth, types.MethodType) would return True.