Why can't I pickle my custom exception in Python

Viewed 74

I am using Python 3.6. I defined a custom exception following this page: https://docs.python.org/3.6/tutorial/errors.html

class MyException(Exception):
    def __init__(self, a):
        self.a = a

Now, if I try to pickle + unpickle this exception, I get the following error:

>> e = MyException(a=1); pickle.loads(pickle.dumps(e))

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-44-413e2ac6234d> in <module>
----> 1 e = MyException(a=1); pickle.loads(pickle.dumps(e))

TypeError: __init__() missing 1 required positional argument: 'a'

Does anyone know why?

1 Answers

Seems to be that the Exception baseclass has special treatment for named arguments (likely in its implementation of __new__)

you can fix this by properly calling the base class in your __init__ method:

>>> class MyException(Exception):
...     def __init__(self, a):
...         super().__init__(a)
...         self.a = a
... 
>>> pickle.loads(pickle.dumps(MyException(a=1)))
MyException(1,)
Related