6

What is the "optimal" way to list all class methods of a given class using inspect? It works if I use the inspect.isfunction as predicate in getmembers like so

class MyClass(object):
    def __init(self, a=1):
        pass
    def somemethod(self, b=1):
        pass

inspect.getmembers(MyClass, predicate=inspect.isfunction)

returns

[('_MyClass__init', <function __main__.MyClass.__init>),
 ('somemethod', <function __main__.MyClass.somemethod>)]

But isn't it supposed to work via ismethod?

 inspect.getmembers(MyClass, predicate=inspect.ismethod)

which returns an empty list in this case. Would be nice if someone could clarify what's going on. I was running this in Python 3.5.

1 Answers1

10

As described in the documentation, inspect.ismethod will show bound methods. This means you have to create an instance of the class if you want to inspect its methods. Since you are trying to inspect methods on the un-instantiated class you are getting an empty list.

If you do:

x = MyClass()
inspect.getmembers(x, predicate=inspect.ismethod)

you would get the methods.

Cristian Ciupitu
  • 20,270
  • 7
  • 50
  • 76
Jerome Anthony
  • 7,823
  • 2
  • 40
  • 31