Python中文社区 全球Python中文开发者的 精神部落
.jpg")
起步
通过内建方法 isinstance(object, classinfo) 可以判断一个对象是否是某个类的实例。但你是否想过关于鸭子协议的对象是如何进行判断的呢? 比如 list 类的父类是继 object 类的,但通过 isinstance([], typing.Iterable) 返回的却是真,难道 list 是可迭代的子类?
根据 PEP 3119 的描述中得知实例的检查是允许重载的:
The primary mechanism proposed here is to allow overloading the built-in functions isinstance() and issubclass(). The overloading works as follows: The call isinstance(x, C) first checks whether C.__instancecheck__ exists, and if so, calls C.__instancecheck__(x) instead of its normal implementation.
这段话的意思是,当调用 isinstance(x, C) 进行检测时,会优先检查是否存在 C.instancecheck,如果存在则调用 C.instancecheck(x) ,返回的结果便是实例检测的结果,默认的判断方式就没有了。
这种方式有助于我们来检查鸭子类型,我用代码测了一下。
class Sizeable(object):def __instancecheck__(cls, instance):print("__instancecheck__ call")return hasattr(instance, "__len__")- ``
class B(object):pass- ``
b = B()print(isinstance(b, Sizeable)) # output:False
只打印了 False,并且 instancecheck 没有调用。 这是怎么回事。可见文档描述并不清楚。打破砂锅问到底的原则我从源码中观察 isinstance 的检测过程。
从源码来看 isinstance 的检测过程
这部分的内容可能比较难,如果读者觉得阅读有难度可以跳过,直接看结论。isinstance 的源码在 abstract.c 文件中:
[abstract.c]intPyObject_IsInstance(PyObject *inst, PyObject *cls){_Py_IDENTIFIER(__instancecheck__);PyObject *checker;- ``
/* Quick test for an exact match */if (Py_TYPE(inst) == (PyTypeObject *)cls)return 1;....}
Py_TYPE(inst) == (PyTypeObject *)cls 这是一种快速匹配的方式,等价于 type(inst) is cls ,这种快速的方式仅当 inst = cls() 匹配成功,并不会去优先检查 instancecheck ,所以文档中有误。继续向下看源码:
/* We know what type's __instancecheck__ does. */if (PyType_CheckExact(cls)) {return recursive_isinstance(inst, cls);}
展开宏 PyType_CheckExact :
[object.h]#define PyType_CheckExact(op) (Py_TYPE(op) == &PyType_Type)
也就是说 cls 是由 type 直接构造出来的类,则判断语言成立。除了类声明里指定 metaclass 外基本都是由 type 直接构造的。从测试代码中得知判断成立,进入 recursiveisinstance。但是这个函数里面我却没找到有关 instancecheck 的代码,recursiveisinstance 的判断逻辑大致是:
def recursive_isinstance(inst, cls):return pyType_IsSubtype(inst, cls)- ``
def pyType_IsSubtype(a, b):for mro in a.__class__.__mro__:if mro is b:return Truereturn False
是从 mro 继承顺序来判断的,mro 是一个元组,它表示类的继承顺序,这个元组的中类的顺序也决定了属性查找顺序。回到 PyObject_IsInstance 函数往下看:
if (PyTuple_Check(cls)) {...}
这是当 instance(x, C) 第二个参数是元组的情况,里面的处理方式是递归调用 PyObject_IsInstance(inst, item) 。继续往下看:
checker = _PyObject_LookupSpecial(cls, &PyId___instancecheck__);if (checker != NULL) {res = PyObject_CallFunctionObjArgs(checker, inst, NULL);ok = PyObject_IsTrue(res);return ok;}
显然,这边才是获得 instancecheck 的地方,为了让检查流程走到这里,定义的类要指明 metaclass 。剩下就是跟踪下 PyObjectLookupSpecial 就可以了:
[typeobject.c]PyObject *_PyObject_LookupSpecial(PyObject *self, _Py_Identifier *attrid){PyObject *res;- ``
res = _PyType_LookupId(Py_TYPE(self), attrid);// 有回调的话处理回调// ...return res;}
取的是 PyTYPE(self) ,也就是说指定的 metaclass 里面需要定义 instancecheck ,获得该属性后,通过 PyObjectCallFunctionObjArgs 调用,调用的内容才是用户自定义的重载方法。
检查机制总结
至此,isinstance 的检测过程基本清晰了,为了便于理解,也得益于python很强的自解释能力,我用python代码来简化 isinstance 的过程:
def _isinstance(x, C):# 快速匹配if type(x) is C:return True- ``
# 如果是由元类 type 直接构造的类if type(C) is type:return C in x.__class__.__mro__- ``
# 如果第二个参数是元组, 则递归调用if type(C) is tuple:for item in C:r = _isinstance(x, item)if r:return r- ``
# 用户自定义检测规则if hasattr(C, "__instancecheck__"):return C.__instancecheck__(x)- ``
# 默认行为return C in x.__class__.__mro__
判断的过程中有5个步骤,而用户自定义的 instancecheck 则比较靠后,这个检测过程主要还是以默认的行为来进行的,用户行为并不优先。
重载 isinstance(x, C)
因此,要想重载 isinstance(x, C) ,让用户能自定义判断结果,就需要满足以下条件:
x 对象不能是由 C 直接实例化;
C 类指定 metaclass ;
指定的 metaclass 类中定义了 instancecheck 。
满足这些条件后,比如对鸭子协议如何判断就比较清楚了:
class MetaSizeable(type):def __instancecheck__(cls, instance):print("__instancecheck__ call")return hasattr(instance, "__len__")- ``
class Sizeable(metaclass=MetaSizeable):pass- ``
class B(object):pass- ``
b = B()print(isinstance(b, Sizeable)) # output: Falseprint(isinstance([], Sizeable)) # output: True
本次测试环境 Python3.6.0
❈
作者:weapon,不会写程序的浴室麦霸不是好的神经科医生
❈
\
赞赏作者
最近热门文章
▼ 点击下方****阅读原文 , 免费成为****社区会员