pythonpython-descriptorspython-builtins

How to check if an object is a method_descriptor


Given an object, how can I make a check if it is a method_descriptor?

is_method_descriptor = isinstance(obj, method_descriptor) # does not work

The problem: method_descriptor is a builtin but not an accessible variable. I neither found it in builtins or types.


I use Python 3.10 here if relevant.

I am looking for a proof of concept out of curiosity how to get hold of the class for an isinstance check if I actually wanted to, or alternative checks that satisfy it.
For my Sphinx related problem where I encountered them unexpectedly I (hopefully) found a workaround already, but still need to test it if it is sufficient or if I should replace it with a more explicit check that I am here looking for.


Solution

  • The class is available as types.MethodDescriptorType which is an alias. Credit to Dunes in the comments for pointing it out.


    There is also inspect.ismethoddescriptor(obj), which performs multiple checks to verify if obj satisfies the necessary interface conditions, i.e. explicit inheritance from method_descriptor is not necessary.

    However until 3.13 it has a bug:

    Changed in version 3.13: This function no longer incorrectly reports objects with __get__() and __delete__(), but not __set__(), as being method descriptors (such objects are data descriptors, not method descriptors).

    So for a 3.10 usage additional checks need to be performed if necessary for the problem.


    The way to get actually hold of the method_descriptor class is to return it via type of an instance of it, one example to get it like this:

    method_descriptor = type(tuple.count)
    
    if isinstance(obj, method_descriptor):
       ...
    

    This is also the trick the python developers use in the types module when they assign MethodDescriptorType = = type(str.join)