Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion Lib/_py_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,12 @@ def _abc_caches_clear(cls):
def __instancecheck__(cls, instance):
"""Override for isinstance(instance, cls)."""
# Inline the cache checking
subclass = instance.__class__
try:
subclass = instance.__class__
except AttributeError:
# Fall back to the type when the instance has no __class__,
# matching the behaviour of the built-in isinstance() (gh-153772).
subclass = type(instance)
if subclass in cls._abc_cache:
return True
subtype = type(instance)
Expand Down
19 changes: 19 additions & 0 deletions Lib/test/test_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,25 @@ class C(str): pass
self.assertIsSubclass(C, A)
self.assertIsSubclass(C, (A,))

def test_instancecheck_no_class(self):
# gh-153772: __instancecheck__ must fall back to type(instance)
# when the instance has no __class__, matching isinstance().
class NoClass:
def __getattribute__(self, name):
if name == "__class__":
raise AttributeError(name)
return super().__getattribute__(name)

class A(metaclass=abc_ABCMeta):
pass

obj = NoClass()
# Must return False rather than propagating the AttributeError.
self.assertNotIsInstance(obj, A)
# Registering the actual type makes the fallback report a match.
A.register(NoClass)
self.assertIsInstance(obj, A)

def test_registration_edge_cases(self):
class A(metaclass=abc_ABCMeta):
pass
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
:func:`isinstance` checks against :mod:`collections.abc` classes such as
:class:`~collections.abc.Mapping` no longer raise :exc:`AttributeError`
when the instance has no ``__class__``. The abstract base class machinery
now falls back to the object's type in that case, matching the behaviour of
the built-in :func:`isinstance`.
8 changes: 6 additions & 2 deletions Modules/_abc.c
Original file line number Diff line number Diff line change
Expand Up @@ -629,11 +629,15 @@ _abc__abc_instancecheck_impl(PyObject *module, PyObject *self,
return NULL;
}

subclass = PyObject_GetAttr(instance, &_Py_ID(__class__));
if (subclass == NULL) {
if (PyObject_GetOptionalAttr(instance, &_Py_ID(__class__), &subclass) < 0) {
Py_DECREF(impl);
return NULL;
}
if (subclass == NULL) {
/* Fall back to the type when the instance has no __class__, matching
the behaviour of the built-in isinstance() (gh-153772). */
subclass = Py_NewRef((PyObject *)Py_TYPE(instance));
}
/* Inline the cache checking. */
int incache = _in_weak_set(impl, &impl->_abc_cache, subclass);
if (incache < 0) {
Expand Down
Loading