How to make a custom exception class with multiple init args pickleable

前端 未结 4 1405
醉梦人生
醉梦人生 2021-01-31 02:46

Why does my custom Exception class below not serialize/unserialize correctly using the pickle module?

import pickle

class MyException(Exception):
    def __ini         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-31 03:47

    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'
    

提交回复
热议问题