The Python Oracle

How to test if a class attribute is an instance method

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: The Builders

--

Chapters
00:00 How To Test If A Class Attribute Is An Instance Method
00:38 Accepted Answer Score 21
00:51 Answer 2 Score 8
01:08 Answer 3 Score 7
01:20 Answer 4 Score 5
01:44 Answer 5 Score 1
02:50 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")