The Python Oracle

How to test if a class attribute is an instance method

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Dream Voyager Looping

--

Chapters
00:00 How To Test If A Class Attribute Is An Instance Method
00:34 Answer 1 Score 7
00:40 Accepted Answer Score 22
00:47 Answer 3 Score 9
01:00 Answer 4 Score 5
01:16 Thank you

--

Full question
https://stackoverflow.com/questions/1091...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #methods #attributes #instance

#avk47



ACCEPTED ANSWER

Score 22


def hasmethod(obj, name):
    return hasattr(obj, name) and type(getattr(obj, name)) == types.MethodType



ANSWER 2

Score 9


You can use the inspect module:

class A(object):
    def method_name(self):
        pass


import inspect

print inspect.ismethod(getattr(A, 'method_name')) # prints True
a = A()
print inspect.ismethod(getattr(a, 'method_name')) # prints True



ANSWER 3

Score 7


import types

print isinstance(getattr(your_object, "your_attribute"), types.MethodType)



ANSWER 4

Score 5


This function checks if the attribute exists and then checks if the attribute is a method using the inspect module.

import inspect

def ismethod(obj, name):
    if hasattr(obj, name):
        if inspect.ismethod(getattr(obj, name)):
            return True
    return False

class Foo:
    x = 0
    def bar(self):
        pass

foo = Foo()
print ismethod(foo, "spam")
print ismethod(foo, "x")
print ismethod(foo, "bar")