How to check if a method exists in a class in Python?

3

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'd like to check through a condition if a given method exists to call it if it exists.

    
asked by anonymous 07.04.2017 / 01:59

2 answers

6

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.

    
07.04.2017 / 02:21
0

You can use the function called hasattr to know if a property exists in the class and then use callable if the property exists to know if it is something "invokable" (in this case 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 be able 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'")
    
07.04.2017 / 02:22