Skip to content

Commit 7bc25ec

Browse files
authored
bpo-20503: Show how isinstance() works with ABC registered classes. (GH-25175)
1 parent 7522067 commit 7bc25ec

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Doc/faq/programming.rst

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1420,6 +1420,41 @@ single class, e.g. ``isinstance(obj, (class1, class2, ...))``, and can also
14201420
check whether an object is one of Python's built-in types, e.g.
14211421
``isinstance(obj, str)`` or ``isinstance(obj, (int, float, complex))``.
14221422

1423+
Note that :func:`isinstance` also checks for virtual inheritance from an
1424+
:term:`abstract base class`. So, the test will return ``True`` for a
1425+
registered class even if hasn't directly or indirectly inherited from it. To
1426+
test for "true inheritance", scan the :term:`MRO` of the class:
1427+
1428+
.. testcode::
1429+
1430+
from collections.abc import Mapping
1431+
1432+
class P:
1433+
pass
1434+
1435+
class C(P):
1436+
pass
1437+
1438+
Mapping.register(P)
1439+
1440+
.. doctest::
1441+
1442+
>>> c = C()
1443+
>>> isinstance(c, C) # direct
1444+
True
1445+
>>> isinstance(c, P) # indirect
1446+
True
1447+
>>> isinstance(c, Mapping) # virtual
1448+
True
1449+
1450+
# Actual inheritance chain
1451+
>>> type(c).__mro__
1452+
(<class 'C'>, <class 'P'>, <class 'object'>)
1453+
1454+
# Test for "true inheritance"
1455+
>>> Mapping in type(c).__mro__
1456+
False
1457+
14231458
Note that most programs do not use :func:`isinstance` on user-defined classes
14241459
very often. If you are developing the classes yourself, a more proper
14251460
object-oriented style is to define methods on the classes that encapsulate a

0 commit comments

Comments
 (0)