Skip to content

Commit 8dbf4cf

Browse files
authored
gh-159580: Improve performance of isinstance() for misses and improve documentation (#159581)
1 parent 6f34060 commit 8dbf4cf

3 files changed

Lines changed: 31 additions & 0 deletions

File tree

‎Doc/builtins/functions.rst‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1181,6 +1181,11 @@ are always available. They are listed here in alphabetical order.
11811181
a :exc:`TypeError` exception is raised. :exc:`TypeError` may not be
11821182
raised for an invalid type if an earlier check succeeds.
11831183

1184+
If *object* has a ``__class__`` attribute that differs from
1185+
:func:`type(object) <type>` (for example a proxy, or a :mod:`unittest.mock`
1186+
object created with a *spec*), ``True`` is also returned when that class
1187+
is a subclass of *classinfo*.
1188+
11841189
.. versionchanged:: 3.10
11851190
*classinfo* can be a :ref:`types-union`.
11861191

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Improve performance of :func:`isinstance` when the check fails.

‎Objects/abstract.c‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2600,6 +2600,28 @@ check_class(PyObject *cls, const char *error)
26002600
return -1;
26012601
}
26022602

2603+
/* Return 1 if inst.__class__ would resolve to object's own getset descriptor,
2604+
i.e. evaluate to Py_TYPE(inst). Types with a custom tp_getattro or an
2605+
overridden __class__ return 0 and take the generic lookup. */
2606+
static inline int
2607+
class_attr_is_type(PyObject *inst)
2608+
{
2609+
PyTypeObject *tp = Py_TYPE(inst);
2610+
if (tp->tp_getattro != PyObject_GenericGetAttr) {
2611+
return 0;
2612+
}
2613+
_PyStackRef cref;
2614+
_PyType_LookupStackRefAndVersion(tp, &_Py_ID(__class__), &cref);
2615+
if (PyStackRef_IsNull(cref)) {
2616+
return 0;
2617+
}
2618+
PyObject *descr = PyStackRef_AsPyObjectBorrow(cref);
2619+
int res = (Py_IS_TYPE(descr, &PyGetSetDescr_Type)
2620+
&& PyDescr_TYPE(descr) == &PyBaseObject_Type);
2621+
PyStackRef_CLOSE(cref);
2622+
return res;
2623+
}
2624+
26032625
static int
26042626
object_isinstance(PyObject *inst, PyObject *cls)
26052627
{
@@ -2608,6 +2630,9 @@ object_isinstance(PyObject *inst, PyObject *cls)
26082630
if (PyType_Check(cls)) {
26092631
retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
26102632
if (retval == 0) {
2633+
if (class_attr_is_type(inst)) {
2634+
return 0;
2635+
}
26112636
retval = PyObject_GetOptionalAttr(inst, &_Py_ID(__class__), &icls);
26122637
if (icls != NULL) {
26132638
if (icls != (PyObject *)(Py_TYPE(inst)) && PyType_Check(icls)) {

0 commit comments

Comments
 (0)