Search code examples
pythonfunctionmethodsintrospection

Detecting bound method in classes (not instances) in Python 3


Given a class C with a function or method f, I use inspect.ismethod(obj.f) (where obj is an instance of C) to find out if f is bound method or not. Is there a way to do the same directly at the class level (without creating an object)?

inspect.ismethod does not work as this:

class C(object):

    @staticmethod
    def st(x):
        pass

    def me(self):
        pass

obj = C()

results in this (in Python 3):

>>> inspect.ismethod(C.st) 
False
>>> inspect.ismethod(C.me)
False
>>> inspect.ismethod(obj.st) 
False
>>> inspect.ismethod(obj.me)
True

I guess I need to check if the function/method is member of a class and not static but I was not able to do it easily. I guess it could be done using classify_class_attrs as shown here How would you determine where each property and method of a Python class is defined? but I was hoping there was another more direct way.


Solution

  • There are no unbound methods in Python 3, so you cannot detect them either. All you have is regular functions. At most you can see if they have a qualified name with a dot, indicating that they are nested, and their first argument name is self:

    if '.' in method.__qualname__ and inspect.getargspec(method).args[0] == 'self':
        # regular method. *Probably*
    

    This of course fails entirely for static methods and nested functions that happen to have self as a first argument, as well as regular methods that do not use self as a first argument (flying in the face of convention).

    For static methods and class methods, you'd have to look at the class dictionary instead:

    >>> isinstance(vars(C)['st'], staticmethod)
    True
    

    That's because C.__dict__['st'] is the actual staticmethod instance, before binding to the class.