1

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.

2
  • 1
    The method_descriptor type exists as types.MethodDescriptorType. It is common for all builtin types to be stored in types as CamelCaseType. Commented May 24 at 10:50
  • Ahh great. Feel free to write the answer. Looks like the developers as well also just used type(str.join) for it to get a hold on it. Commented May 25 at 14:14

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.