Skip to content

Commit 427ab12

Browse files
miss-islingtonambv
andauthored
bpo-45464: [doc] Explain that subclassing multiple exceptions is fragile (GH-29094) (GH-29105)
Co-authored-by: Pablo Galindo Salgado <Pablogsal@gmail.com> (cherry picked from commit dff0b71) Co-authored-by: Łukasz Langa <lukasz@langa.pl>
1 parent 1249ce7 commit 427ab12

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

Doc/library/exceptions.rst

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,10 @@ class or one of its subclasses, and not from :exc:`BaseException`. More
3434
information on defining exceptions is available in the Python Tutorial under
3535
:ref:`tut-userexceptions`.
3636

37+
38+
Exception context
39+
-----------------
40+
3741
When raising (or re-raising) an exception in an :keyword:`except` or
3842
:keyword:`finally` clause
3943
:attr:`__context__` is automatically set to the last exception caught; if the
@@ -67,6 +71,25 @@ exceptions so that the final line of the traceback always shows the last
6771
exception that was raised.
6872

6973

74+
Inheriting from built-in exceptions
75+
-----------------------------------
76+
77+
User code can create subclasses that inherit from an exception type.
78+
It's recommended to only subclass one exception type at a time to avoid
79+
any possible conflicts between how the bases handle the ``args``
80+
attribute, as well as due to possible memory layout incompatibilities.
81+
82+
.. impl-detail::
83+
84+
Most built-in exceptions are implemented in C for efficiency, see:
85+
:source:`Objects/exceptions.c`. Some have custom memory layouts
86+
which makes it impossible to create a subclass that inherits from
87+
multiple exception types. The memory layout of a type is an implementation
88+
detail and might change between Python versions, leading to new
89+
conflicts in the future. Therefore, it's recommended to avoid
90+
subclassing multiple exception types altogether.
91+
92+
7093
Base classes
7194
------------
7295

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Mention in the documentation of :ref:`Built-in Exceptions
2+
<bltin-exceptions>` that inheriting from multiple exception types in a
3+
single subclass is not recommended due to possible memory layout
4+
incompatibility.

0 commit comments

Comments
 (0)