Problem:
Consider the following context:
class Call:
def __call__(self):
pass
class Foo:
def __init__(self):
self.var = Call()
def method(self):
pass
foo = Foo()
That is, we have a foo
object which is an instance of Foo
, having a method
method and a var
attribute, which is Call
(which is callable in>). When checking if a method exists, we expect only method
to be returned as valid and var
not.
Solution 1:
Spolier alert: Do not use! :
Proposed by Wallace in his (adapted) response:
def method_exists(instance, method):
return hasattr(instance, method) and callable(instance.method)
Testing for the problem:
>>> print(method_exists(foo, "method"))
True
>>> print(method_exists(foo, "var"))
True
See working at Ideone
That is, the solution failed in the second test.
Solution 2:
Spolier alert: Do not use! :
Proposed by me in an earlier version of this answer:
def method_exists(instance, method):
return method in dir(instance) and callable(instance.method)
Testing for the problem:
>>> print(method_exists(foo, "method"))
True
>>> print(method_exists(foo, "var"))
True
See working at Ideone
That is, the solution also failed in the second test.
Solution 3:
Spolier alert: It works! You can use: D
Also proposed by Wallace in his (adapted) answer:
from inspect import ismethod
def method_exists(instance, method):
return hasattr(instance, method) and ismethod(getattr(instance, method))
Testing for the problem:
>>> print(method_exists(foo, "method"))
True
>>> print(method_exists(foo, "var"))
False
See working at Ideone
So you passed the two tests.
In solution 3, we required the inclusion of the getattr
function for the verification if it is a method.