使iInstance失败(以可定制的方式)

2024-09-30 06:34:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为一个pythonc扩展编写一个回归测试,该扩展“忘记”检查PyObject_IsInstance的失败。但我唯一能想到的是重写__instancecheck__的元类,例如:

import six

class InstanceCheckGoneWrong(type):
    def __instancecheck__(self, other):
        raise TypeError('isinstance failed')

@six.add_metaclass(InstanceCheckGoneWrong)
class FailingIsinstanceClass():
    pass

它的工作原理是:

>>> isinstance(1, FailingIsinstanceClass)
TypeError: isinstance failed

但看起来很复杂。有没有更简单的方法(python2和python3兼容)让PyObject_IsInstanceisinstance)失败?一个可定制的异常是最好的,但是一个内置的也可以


Tags: importselfdeftypeclassisinstancepyobjectfailed

热门问题