Skip to content

[3.10] bpo-45464: [doc] Explain that subclassing multiple exceptions is fragile (GH-29094) #29104

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 20, 2021
Merged
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
23 changes: 23 additions & 0 deletions Doc/library/exceptions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ class or one of its subclasses, and not from :exc:`BaseException`. More
information on defining exceptions is available in the Python Tutorial under
:ref:`tut-userexceptions`.


Exception context
-----------------

When raising (or re-raising) an exception in an :keyword:`except` or
:keyword:`finally` clause
:attr:`__context__` is automatically set to the last exception caught; if the
Expand Down Expand Up @@ -67,6 +71,25 @@ exceptions so that the final line of the traceback always shows the last
exception that was raised.


Inheriting from built-in exceptions
-----------------------------------

User code can create subclasses that inherit from an exception type.
It's recommended to only subclass one exception type at a time to avoid
any possible conflicts between how the bases handle the ``args``
attribute, as well as due to possible memory layout incompatibilities.

.. impl-detail::

Most built-in exceptions are implemented in C for efficiency, see:
:source:`Objects/exceptions.c`. Some have custom memory layouts
which makes it impossible to create a subclass that inherits from
multiple exception types. The memory layout of a type is an implementation
detail and might change between Python versions, leading to new
conflicts in the future. Therefore, it's recommended to avoid
subclassing multiple exception types altogether.


Base classes
------------

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Mention in the documentation of :ref:`Built-in Exceptions
<bltin-exceptions>` that inheriting from multiple exception types in a
single subclass is not recommended due to possible memory layout
incompatibility.