[Python-checkins] bpo-20503: Show how isinstance() works with ABC registered classes. (GH-25175) (GH-25202)

rhettinger webhook-mailer at python.org
Mon Apr 5 16:11:58 EDT 2021


https://github.com/python/cpython/commit/028d5286d4255195ba6715e1aeb4bffed6b0279e
commit: 028d5286d4255195ba6715e1aeb4bffed6b0279e
branch: 3.9
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: rhettinger <rhettinger at users.noreply.github.com>
date: 2021-04-05T13:11:50-07:00
summary:

bpo-20503: Show how isinstance() works with ABC registered classes. (GH-25175) (GH-25202)

files:
M Doc/faq/programming.rst

diff --git a/Doc/faq/programming.rst b/Doc/faq/programming.rst
index fd59f68034776..3c8aa14fad10a 100644
--- a/Doc/faq/programming.rst
+++ b/Doc/faq/programming.rst
@@ -1420,6 +1420,41 @@ single class, e.g. ``isinstance(obj, (class1, class2, ...))``, and can also
 check whether an object is one of Python's built-in types, e.g.
 ``isinstance(obj, str)`` or ``isinstance(obj, (int, float, complex))``.
 
+Note that :func:`isinstance` also checks for virtual inheritance from an
+:term:`abstract base class`.  So, the test will return ``True`` for a
+registered class even if hasn't directly or indirectly inherited from it.  To
+test for "true inheritance", scan the :term:`MRO` of the class:
+
+.. testcode::
+
+    from collections.abc import Mapping
+
+    class P:
+         pass
+
+    class C(P):
+        pass
+
+    Mapping.register(P)
+
+.. doctest::
+
+    >>> c = C()
+    >>> isinstance(c, C)        # direct
+    True
+    >>> isinstance(c, P)        # indirect
+    True
+    >>> isinstance(c, Mapping)  # virtual
+    True
+
+    # Actual inheritance chain
+    >>> type(c).__mro__
+    (<class 'C'>, <class 'P'>, <class 'object'>)
+
+    # Test for "true inheritance"
+    >>> Mapping in type(c).__mro__
+    False
+
 Note that most programs do not use :func:`isinstance` on user-defined classes
 very often.  If you are developing the classes yourself, a more proper
 object-oriented style is to define methods on the classes that encapsulate a



More information about the Python-checkins mailing list