TypeCheck vs IsInstance in C API

random832 at fastmail.us random832 at fastmail.us
Tue Aug 25 16:32:33 CEST 2015

On Mon, Aug 24, 2015, at 22:12, Andrew Wang wrote:
> Hi.
> I know this thread is ancient, but I would like to know the answer
> as well
> ( https://mail.python.org/pipermail/python-list/2006-May/413542.html).

Of course, the answer in 2015 is actually very different from the
answer in 2006, since we didn't have either Python 3 or abstract
classes back then.

The IsInstance (and IsSubclass) function documentation mentions that
they use the methods __instancecheck__ [and __subclasscheck__],
presumably to support abstract classes.

The actual implementation of TypeCheck is a macro:
PyAPI_FUNC(int) PyType_IsSubtype(PyTypeObject *, PyTypeObject *);
#define PyObject_TypeCheck(ob, tp) \
    (Py_TYPE(ob) == (tp) || PyType_IsSubtype(Py_TYPE(ob), (tp)))

PyType_IsSubtype (in typeobject.c) only appears to deal with the
real types, not any abstract class methods.

So it looks like PyObject_TypeCheck/PyType_IsSubtype was originally
introduced to check for real types (and not old style classes), and
continued in that niche as IsInstance/IsSubclass were repurposed to
deal with PEP 3119 ABC logic.

Incidentally, this made me wonder what was done before
PyObject_IsInstance was added in 2.1. In 2.0, substantially the same
code exists inside builtin_isinstance.

Stuff I found researching this:

And, now, your moment of zen:
> def isa(ob, cl):
>   try:
>       raise ob
>   except cl:
>       return 1
>   else: return 0

More information about the Python-list mailing list