pythonpickleinitgetstate

Is it OK to call __init__ from __setstate__


I'm enhancing an existing class that does some calculations in the __init__ function to determine the instance state. Is it ok to call __init__() from __getstate__() in order to reuse those calculations?


Solution

  • To summarize reactions from Kroltan and jonsrharpe:

    Technically it is OK

    Technically it will work and if you do it properly, it can be considered OK.

    Practically it is tricky, avoid that

    If you edit the code in future and touch __init__, then it is easy (even for you) to forget about use in __setstate__ and then you enter into difficult to debug situation (asking yourself, where it comes from).

    class Calculator():
        def __init__(self):
            # some calculation stuff here
        def __setstate__(self, state)
            self.__init__()
    

    The calculation stuff is better to get isolated into another shared method:

    class Calculator():
        def __init__(self):
            self._shared_calculation()   
    
        def __setstate__(self, state)
            self._shared_calculation()
    
        def _shared_calculation(self):
            #some calculation stuff here
    

    This way you shall notice.

    Note: use of "_" as prefix for the shared method is arbitrary, you do not have to do that.