[New-bugs-announce] [issue35083] Fix documentation for __instancecheck__

Joy Diamond report at bugs.python.org
Sat Oct 27 16:14:41 EDT 2018


New submission from Joy Diamond <python.gem at gmail.com>:

This is a request to fix the documentation for __instancecheck__.

Please add the following:

"""
(Note that any object `x` is always considered to be an instance of
`type(x)`, and this cannot be overridden.)
"""

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()
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:

https://github.com/python/cpython/blob/master/Objects/abstract.c#L2397-L2405

Which reads:

int
PyObject_IsInstance(PyObject *inst, PyObject *cls)
{
_Py_IDENTIFIER(__instancecheck__);
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:

https://docs.python.org/2/reference/datamodel.html
https://docs.python.org/3/reference/datamodel.html
https://www.python.org/dev/peps/pep-3119/

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.

----------
assignee: docs at python
components: Documentation
messages: 328658
nosy: docs at python, joydiamond
priority: normal
severity: normal
status: open
title: Fix documentation for __instancecheck__
type: enhancement
versions: Python 2.7, Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue35083>
_______________________________________


More information about the New-bugs-announce mailing list