Skip to content
4 changes: 4 additions & 0 deletions Doc/library/exceptions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,10 @@ The following exceptions are used mostly as base classes for other exceptions.
assign a special meaning to the elements of this tuple, while others are
usually called only with a single string giving an error message.

.. attribute:: kwargs

The dictionnary of keyword arguments given to the exception constructor.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typo: dictionnary -> dictionary


.. method:: with_traceback(tb)

This method sets *tb* as the new traceback for the exception and returns
Expand Down
2 changes: 1 addition & 1 deletion Include/cpython/pyerrors.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ extern "C" {

/* PyException_HEAD defines the initial segment of every exception class. */
#define PyException_HEAD PyObject_HEAD PyObject *dict;\
PyObject *args; PyObject *traceback;\
PyObject *args; PyObject *kwargs; PyObject *traceback;\
PyObject *context; PyObject *cause;\
char suppress_context;

Expand Down
69 changes: 59 additions & 10 deletions Lib/test/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -439,16 +439,15 @@ def testAttributes(self):
value, expected[checkArgName]))

# test for pickling support
for p in [pickle]:
for protocol in range(p.HIGHEST_PROTOCOL + 1):
s = p.dumps(e, protocol)
new = p.loads(s)
for checkArgName in expected:
got = repr(getattr(new, checkArgName))
want = repr(expected[checkArgName])
self.assertEqual(got, want,
'pickled "%r", attribute "%s' %
(e, checkArgName))
for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
s = pickle.dumps(e, protocol)
new = pickle.loads(s)
for checkArgName in expected:
got = repr(getattr(new, checkArgName))
want = repr(expected[checkArgName])
self.assertEqual(got, want,
'pickled "%r", attribute "%s"' %
(e, checkArgName))

def testWithTraceback(self):
try:
Expand Down Expand Up @@ -1299,6 +1298,43 @@ def g():
next(i)
next(i)

def test_get_kwargs(self):
self.assertEqual(BaseException().kwargs, {})
Comment thread
remilapeyre marked this conversation as resolved.
Resolved
self.assertEqual(NaiveException(x=1).kwargs, {'x': 1})

def test_set_kwargs(self):
b = BaseException()
b.kwargs = {'x': 1}
self.assertEqual(b.kwargs, {'x': 1})

b = NaiveException(x=1)
b.kwargs = {'x': 2}
self.assertEqual(b.kwargs, {'x': 2})

def test_del_args_kwargs(self):
b = BaseException()

with self.assertRaisesRegex(TypeError, "args may not be deleted"):
del b.args

with self.assertRaisesRegex(TypeError, "kwargs may not be deleted"):
del b.kwargs

def test_repr(self):
class MixedArgsKwargs(Exception):
def __init__(*args, **kwargs):
pass

self.assertEqual(repr(BaseException()), "BaseException()")
self.assertEqual(repr(BaseException(1)), "BaseException(1)")
self.assertEqual(repr(NaiveException(1)), "NaiveException(1)")
self.assertEqual(repr(NaiveException(x=1)), "NaiveException(x=1)")
self.assertEqual(repr(MixedArgsKwargs(1, b=2)), "MixedArgsKwargs(1, b=2)")

class NoKwargs(Exception):
def __init__(self, foo,):
self.args = (foo,)


class ImportErrorTests(unittest.TestCase):

Expand Down Expand Up @@ -1376,6 +1412,19 @@ def test_copy_pickle(self):
self.assertEqual(exc.name, orig.name)
self.assertEqual(exc.path, orig.path)

def test_pickle_overriden_init(self):
# Issue #27015
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
orig = NaiveException(x='foo')
if proto in (0, 1):
# Pickling excpetions keyword arguments is not supported for
# protocol 0 and 1
with self.assertRaises(TypeError):
pickle.loads(pickle.dumps(orig, proto))
else:
exc = pickle.loads(pickle.dumps(orig, proto))
self.assertEqual(orig.x, exc.x)


if __name__ == '__main__':
unittest.main()
9 changes: 9 additions & 0 deletions Lib/test/test_subprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import threading
import gc
import textwrap
import pickle
from test.support import FakePath

try:
Expand Down Expand Up @@ -1690,6 +1691,14 @@ def test_CalledProcessError_str_non_zero(self):
error_string = str(err)
self.assertIn("non-zero exit status 2.", error_string)

def test_CalledProcessError_picklable(self):
# Issue #27015
err = subprocess.CalledProcessError(returncode=2, cmd='foo')
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
new = pickle.loads(pickle.dumps(err, proto))
self.assertEqual(err.returncode, new.returncode)
self.assertEqual(err.cmd, new.cmd)

def test_preexec(self):
# DISCLAIMER: Setting environment variables is *not* a good use
# of a preexec_fn. This is merely a test.
Expand Down
8 changes: 4 additions & 4 deletions Lib/test/test_sys.py
Original file line number Diff line number Diff line change
Expand Up @@ -1004,13 +1004,13 @@ def inner():
class C(object): pass
check(C.__dict__, size('P'))
# BaseException
check(BaseException(), size('5Pb'))
check(BaseException(), size('6Pb'))
# UnicodeEncodeError
check(UnicodeEncodeError("", "", 0, 0, ""), size('5Pb 2P2nP'))
check(UnicodeEncodeError("", "", 0, 0, ""), size('6Pb 2P2nP'))
# UnicodeDecodeError
check(UnicodeDecodeError("", b"", 0, 0, ""), size('5Pb 2P2nP'))
check(UnicodeDecodeError("", b"", 0, 0, ""), size('6Pb 2P2nP'))
# UnicodeTranslateError
check(UnicodeTranslateError("", 0, 1, ""), size('5Pb 2P2nP'))
check(UnicodeTranslateError("", 0, 1, ""), size('6Pb 2P2nP'))
# ellipses
check(Ellipsis, size(''))
# EncodingMap
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Exceptions now save the keyword arguments given to their constructor in their
``kwargs`` attribute. Exceptions with overridden ``__init__`` and using keyword
arguments are now picklable. Contributed by Rémi Lapeyre.
Loading