Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it\'s bound to?
A solution that works for both Python 2 and 3 is tricky.
Using the package six, one solution could be:
def is_bound_method(f):
"""Whether f is a bound method"""
try:
return six.get_method_self(f) is not None
except AttributeError:
return False
In Python 2:
im_self
attribute so six.get_method_self()
will raise an AttributeError
and this will return False
im_self
attribute set to None
so this will return False
im_self
attribute set to non-None
so this will return True
In Python 3:
__self__
attribute so six.get_method_self()
will raise an AttributeError
and this will return False
False
__self__
attribute set (to non-None
) so this will return True