[Python-ideas] Fix documentation for __instancecheck__

Joy Diamond python.gem at gmail.com
Sat Oct 27 14:02:53 EDT 2018


This is a request to fix the documentation for __instancecheck__.

Please add the following (please rewrite better than I can -- I am not good
at explaining concepts in short sentences):

NOTE:  As an optimization, isinstance(*object*, *classinfo*) does NOT call
classinfo.__instancecheck__(instance) when type(object) == classinfo.

Consider the following program:

class M(type):
    def __instancecheck__(m, t):
        print('instancecheck(%s, %s)' % (m, t))
        return False                                    #   LIE!

Test = M('Test', ((object,)), {})

something = Test()

print('Does *NOT* call __instancecheck__:')
print('isinstance(something, Test): %s' % isinstance(something, Test))

print('Does call __instancecheck__:')
print('isinstance(0, Test):         %s' % isinstance(0,         Test))

Under python 2, python 3, and pypy, in all cases, the first examples does
*NOT* call __instancecheck__.

You can see the optimization here:


Which reads:

PyObject_IsInstance(PyObject *inst, PyObject *cls)
PyObject *checker;

/* Quick test for an exact match */
if (Py_TYPE(inst) == (PyTypeObject *)cls)
return 1;

I'm fine with the optimization -- I am not suggesting to get rid of it.

I just want the documentation to match the actual implementation.

The following documentation needs to be fixed:


It took me half an hour to figure out why my version of __instancecheck__
was not working, as I tried to test it using the super simple code above ...

One of the best things about python is how accurate and consistent the
documentation is.

This request is to keep these high standards.


Joy Diamond.

NOTE: I'm not sure where to post this, so posting to python-ideas, in case
people want to discuss getting rid of the optimization in
PyObject_IsInstance ... which I am not suggesting.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20181027/720a8b33/attachment.html>

More information about the Python-ideas mailing list