I'm trying to write a regression test for a Python C extension that "forgot" to check for failures for PyObject_IsInstance
. But the only thing I could come up with was a metaclass that overrides __instancecheck__
, for example:
import six
class InstanceCheckGoneWrong(type):
def __instancecheck__(self, other):
raise TypeError('isinstance failed')
@six.add_metaclass(InstanceCheckGoneWrong)
class FailingIsinstanceClass():
pass
It works:
>>> isinstance(1, FailingIsinstanceClass)
TypeError: isinstance failed
But it seems very complicated. Is there an easier way (python2 and python3 compatible) to let PyObject_IsInstance
(isinstance
) fail? A customizable exception would be best, but a builtin would also do.