Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 298
avishorp Avatar asked May 04 '14 20:05

avishorp


2 Answers

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.

like image 121
Jan Vlcinsky Avatar answered Nov 03 '22 11:11

Jan Vlcinsky


It's usually preferable to write a method called __getnewargs__ instead. That way, the Pickling mechanism will call __init__ for you automatically.

like image 23
Kevin Avatar answered Nov 03 '22 12:11

Kevin