Home  >  Article  >  Backend Development  >  A brief discussion on the problem of overloading isinstance inheritance relationship in Python

A brief discussion on the problem of overloading isinstance inheritance relationship in Python

不言
不言Original
2018-05-04 14:21:241403browse

This article mainly introduces the issue of overloading isinstance inheritance relationship in Python. It has certain reference value. Now I share it with you. Friends in need can refer to it

for judgment. Inheritance relationship

You can determine whether an object is an instance of a certain class through the built-in method isinstance(object, classinfo). This relationship can be direct, indirect or abstract.

Instance checks are allowed to be overloaded, see the document customizing-instance-and-subclass-checks. According to the description of 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.

The meaning of this passage is that when calling isinstance(x , C) When performing detection, it will first check whether C.__instancecheck__ exists. If it exists, C.__instancecheck__(x) will be called. The returned result is the result of instance detection, and there is no default judgment method.

This method helps us check duck types. I tested it with code.

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

Only False is printed, and __instancecheck__ is not called. How is this going.

Not running __instancecheck__

It can be seen that the document is not clearly written. In order to find out the problem, we start tracing from the isinstance source code.

[abstract.c]
int
PyObject_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 This is a fast matching method, equivalent to type(inst) is cls, which If the match is successful in this fast way, __instancecheck__ will not be checked. So the priority check in the document for the existence of C.__instancecheck__ is wrong. Continue to look down at the source code:

  /* We know what type's __instancecheck__ does. */
  if (PyType_CheckExact(cls)) {
    return recursive_isinstance(inst, cls);
  }

Expand the macro PyType_CheckExact:

[object.h]
#define PyType_CheckExact(op) (Py_TYPE(op) == &PyType_Type)

That is If cls is a class directly constructed from type, then the judgment language is established. Except for the metaclass specified in the class declaration, it is basically constructed directly by type. Knowing from the test code that the judgment is established, enter recursive_isinstance. But I didn't find the code about __instancecheck__ in this function. The judgment logic of recursive_isinstance is roughly:

def recursive_isinstance(inst, cls):
  return pyType_IsSubtype(inst, cls)

def pyType_IsSubtype(a, b):
  for mro in a.__mro__:
    if mro is b:
      return True
  return False

is judged from the __mro__ inheritance sequence. Go back to the PyObject_IsInstance function and look down:

if (PyTuple_Check(cls)) {
  ...
}

This is the case when the second parameter of instance(x, C) is a tuple, and the processing method inside It is a recursive call to PyObject_IsInstance(inst, item). Continue reading:

checker = _PyObject_LookupSpecial(cls, &PyId___instancecheck__);
if (checker != NULL) {
  res = PyObject_CallFunctionObjArgs(checker, inst, NULL);
  ok = PyObject_IsTrue(res);
  return ok;
}

Obviously, this is where __instancecheck__ is obtained. In order to get the check process to this point, the defined class must specify metaclass . All that's left is to track _PyObject_LookupSpecial:

[typeobject.c]
PyObject *
_PyObject_LookupSpecial(PyObject *self, _Py_Identifier *attrid)
{
  PyObject *res;

  res = _PyType_LookupId(Py_TYPE(self), attrid);
  // 有回调的话处理回调
  // ...
  return res;
}

takes Py_TYPE(self), which means that __instancecheck__ needs to be defined in the specified metaclass.

Summary

So far, summarize the conditions for overloading the isinstance(x, C) behavior:

  1. x objects cannot be directly instantiated by C;

  2. C class specifies metaclass;

  3. specifies __instancecheck__ in the metaclass class.

Test code:

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: False
print(isinstance([], Sizeable)) # output: True

The documentation may be a bit old. The environment for this test is Python3.6.

Related recommendations:

Detailed explanation of read_excel in Python 2.7 pandas

The above is the detailed content of A brief discussion on the problem of overloading isinstance inheritance relationship in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn