Skip to content Skip to sidebar Skip to footer

Why Is There A Difference Between Inspect.ismethod And Inspect.isfunction From Python 2 -> 3?

So this code: from inspect import * class X(object): def y(self): pass methods = getmembers(X, predicate=ismethod) functions = getmembers(X, predicate=isfunction) print('%

Solution 1:

Not specifically a difference with inspect but Python 3 in general see here

The concept of “unbound methods” has been removed from the language. When referencing a method as a class attribute, you now get a plain function object.

My suggestion for cross-platform would be:

getmembers(X, predicate=lambda x: isfunction(x) or ismethod(x))

Solution 2:

Because essentialy there is no difference between a function and an unbound method. This idea of unbound methods exists in Python 2 mostly for historical reasons and was removed in Python 3.

This email by the BDFL himself goes into some details.


Answering your updated question. I think its best to use inspect.isroutine as it matches both unbound methods and functions with an additional benefit of also matching methods/functions implemented in C.

Start with inspect.getmembers and filter its output as you need. It also takes an optional predicate parameter.

Post a Comment for "Why Is There A Difference Between Inspect.ismethod And Inspect.isfunction From Python 2 -> 3?"