How to check if a method exists in a class in Python?
How to check if a method exists in a class in Python?
Is there a function that does this?
class Test(object):
def method(self):
pass
For example, I would like to check through a condition if a certain method exists to call it if it exists.
2 answers
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 an object foo
which is an instance of Foo
, having a method method
and an attribute var
, which is of type Call
(which is callable). 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 response (adapted):
def method_exists(instance, method):
return hasattr(instance, method) and callable(instance.method)
Doing the tests for the problem:
>>> print(method_exists(foo, "method"))
True
>>> print(method_exists(foo, "var"))
True
see working on Ideone
I.e. solution failed in the second Test.
Solution 2:
Spolier alert: do not use! :(
Proposed by me, in a version prior to this answer:
def method_exists(instance, method):
return method in dir(instance) and callable(instance.method)
Doing the tests for the problem:
>>> print(method_exists(foo, "method"))
True
>>> print(method_exists(foo, "var"))
True
see working on Ideone
That is, the solution also failed in the second Test.
Solution 3:
Spolier alert: works! Can use: D
Also proposed by Wallace in his answer (adapted):
from inspect import ismethod
def method_exists(instance, method):
return hasattr(instance, method) and ismethod(getattr(instance, method))
Doing the tests for the problem:
>>> print(method_exists(foo, "method"))
True
>>> print(method_exists(foo, "var"))
False
see working on Ideone
Therefore passed both Tests.
In Solution 3, the include function
getattr
for checking if it is a method.
You can use the function called hasattr
to know if a certain property exists in the class and then use callable
if the property exists to know if it is something "invocable" (in the case the method):
class Test(object):
def x(self):
pass
if hasattr(Test, 'x') and callable(Test.x):
print ("Método 'x' existe")
You can also use the inspect
library to check if a particular attribute of a class is a method.
from inspect import ismethod
if hasattr(Test, 'x') and ismethod(Test.x):
print ("Tem 'x'")