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

前端 未结 4 1437
醉梦人生
醉梦人生 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:39

    I like Martijn's answer, but I think a better way is to pass all arguments to the Exception base class:

    class MyException(Exception):
        def __init__(self, arg1, arg2):
            super(MyException, self).__init__(arg1, arg2)        
            self.arg1 = arg1
            self.arg2 = arg2
    

    The base Exception class' __reduce__ method will include all the args. By not making all of the extra arguments optional, you can ensure that the exception is constructed correctly.

提交回复
热议问题