summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorƁukasz Langa <lukasz@langa.pl>2021-10-20 16:54:31 (GMT)
committerGitHub <noreply@github.com>2021-10-20 16:54:31 (GMT)
commitdff0b713436e286bb1afdd7c6f3093c8e8db16dd (patch)
tree24aeb481bb94830fb24931713784a39f3cbca6bd
parent1dfac27dffbe771f9d88bd1726f7362ce0341437 (diff)
downloadcpython-dff0b713436e286bb1afdd7c6f3093c8e8db16dd.zip
cpython-dff0b713436e286bb1afdd7c6f3093c8e8db16dd.tar.gz
cpython-dff0b713436e286bb1afdd7c6f3093c8e8db16dd.tar.bz2
bpo-45464: [doc] Explain that subclassing multiple exceptions is fragile (GH-29094)
Co-authored-by: Pablo Galindo Salgado <Pablogsal@gmail.com>
-rw-r--r--Doc/library/exceptions.rst23
-rw-r--r--Misc/NEWS.d/next/Documentation/2021-10-20-16-26-53.bpo-45464.mOISBs.rst4
2 files changed, 27 insertions, 0 deletions
diff --git a/Doc/library/exceptions.rst b/Doc/library/exceptions.rst
index b665c60..8fa82a9 100644
--- a/Doc/library/exceptions.rst
+++ b/Doc/library/exceptions.rst
@@ -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
@@ -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
------------
diff --git a/Misc/NEWS.d/next/Documentation/2021-10-20-16-26-53.bpo-45464.mOISBs.rst b/Misc/NEWS.d/next/Documentation/2021-10-20-16-26-53.bpo-45464.mOISBs.rst
new file mode 100644
index 0000000..1721aa2
--- /dev/null
+++ b/Misc/NEWS.d/next/Documentation/2021-10-20-16-26-53.bpo-45464.mOISBs.rst
@@ -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.