Why does my custom Exception class below not serialize/unserialize correctly using the pickle module?
import pickle
class MyException(Exception):
def __ini
Make arg2
optional:
class MyException(Exception):
def __init__(self, arg1, arg2=None):
self.arg1 = arg1
self.arg2 = arg2
super(MyException, self).__init__(arg1)
The base Exception
class defines a .__reduce__() method to make the extension (C-based) type picklable and that method only expects one argument (which is .args
); see the BaseException_reduce() function in the C source.
The easiest work-around is making extra arguments optional. The __reduce__
method also includes any additional object attributes beyond .args
and .message
and your instances are recreated properly:
>>> e = MyException('foo', 'bar')
>>> e.__reduce__()
(, ('foo',), {'arg1': 'foo', 'arg2': 'bar'})
>>> pickle.loads(pickle.dumps(e))
MyException('foo',)
>>> e2 = pickle.loads(pickle.dumps(e))
>>> e2.arg1
'foo'
>>> e2.arg2
'bar'