Why __instancecheck__ is not always called depending on argument?

python, python-3.x

Solution

`PyObject_IsInstance` does a quick test for exact match.

`Objects/abstract.c`:

int
PyObject_IsInstance(PyObject *inst, PyObject *cls)
{
    static PyObject *name = NULL;

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

don't like the fast path? you can try this (at your own risk):

>>> import __builtin__
>>> def isinstance(a, b):
...     class tmp(type(a)):
...          pass
...     return __builtin__.isinstance(tmp(), b)
... 
>>> __builtin__.isinstance(a, A)
True
>>> isinstance(a, A)
__instancecheck__
True

Problem

There is this code: ``` class Meta(type): def __instancecheck__(self, instance): print("__instancecheck__") return True class A(metaclass=Meta): pass a = A() isinstance(a, A) # __instancecheck__ not called isinstance([], A) # __instancecheck__ called ``` Why `__instancecheck__` is called for `[]` argument but not for `a` argument?

Original source

Related problems