[issue37489] pickling instance which inherited from Exception with keyword only parameter

Irit Katriel report at bugs.python.org
Thu Jan 6 07:59:34 EST 2022


Irit Katriel <iritkatriel at gmail.com> added the comment:

> I want to known why it is

It's because Exception implements __reduce__ and that takes precedence over __getnewargs_ex__. You can see that with this example:

""""
import pickle

class MyException():
    def __init__(self, desc, item):
        super().__init__()
        self.desc = desc
        self.item = item

    def __getnewargs_ex__(self):
        print('called in {}.__getnewargs_ex__'.format(self.__class__.__name__))
        return (self.desc,), self.__dict__

    def __reduce__(self):
        print('called in {}.__reduce__'.format(self.__class__.__name__))
        return MyException, (self.desc, self.item),

e = MyException('testing', item='cpu')
s = pickle.dumps(e, protocol=-1)

x = pickle.loads(s)
""""

Output: called in MyException.__reduce__

----------
nosy: +iritkatriel

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue37489>
_______________________________________


More information about the Python-bugs-list mailing list