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

Asked

Viewed 883 times

3

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

Is there any 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.

  • The answers to these questions will address all methods of the class. It was not my intention, I really wanted to know if a specific method exists or not, in the same way as in PHP with method_exists('Class', 'method').

  • @Virgilionovic sees my answer and maybe he’ll change his mind when the duplicate.

  • @Virgilionovic no, return True for both. I kept it as solution 2 in my answer.

  • @Virgilionovic for attributes normal, works! The problem is when there is class composition and the attribute is an instance of a class callable. The test goes on to return True for this attribute without being a method.

2 answers

6

Problem:

Let us consider the following context:

class Call:
    def __call__(self):
        pass

class Foo:
    def __init__(self):
        self.var = Call()

    def method(self):
        pass

foo = Foo()

I mean, we have an object foo which is an instance of Foo, possessing a method method and an attribute var, who’s kind Call (that is callable). By checking whether a method exists, we hope that only method is returned as valid and var nay.

Solution 1:

Spolier Alert: Do not use! :(

Proposed by Wallace in his reply (adapted):

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 on Ideone

That is, the solution failed in the second test.

Solution 2:

Spolier Alert: Do not use! :(

Proposed by me in a version prior to this reply:

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 on Ideone

That is, the solution too failed in the second test.

Solution 3:

Spolier Alert: It works! You can use :D

Also proposed by Wallace in his reply (adapted):

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 on Ideone

So you passed both tests.

Solution 3 required the inclusion of the getattr for checking whether it is a method.

0

You can use the call function 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 this 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 library inspect to be able to check whether a class attribute is a method.

 from inspect import ismethod

 if hasattr(Test, 'x') and ismethod(Test.x):
     print ("Tem 'x'")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.