[Python-ideas] Fix documentation for __instancecheck__

Chris Angelico rosuav at gmail.com
Sat Oct 27 14:24:43 EDT 2018

On Sun, Oct 28, 2018 at 5:03 AM Joy Diamond <python.gem at gmail.com> wrote:
> Greetings,
> 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))

Here's the passage in question, for reference:

The following methods are used to override the default behavior of the
isinstance() and issubclass() built-in functions.

In particular, the metaclass abc.ABCMeta implements these methods in
order to allow the addition of Abstract Base Classes (ABCs) as
“virtual base classes” to any class or type (including built-in
types), including other ABCs.

Since it uses the word "override", I agree that it's not entirely
correct. The implication of "override" is that you can completely
replace the normal behaviour. In this case, you can change the
behaviour of subclass testing (for instance, you can "disown" a
subclass by denying that instances of it are instances of yourself),
and of course, you can claim an object as an instance of a class it
didn't directly inherit from (the way ABCs work), but you cannot fib
about direct instances. I think the behaviour is close enough to
accurate that it doesn't need major rewording; how about adding this

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

Would that work?


More information about the Python-ideas mailing list