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?
To summarize reactions from Kroltan and jonsrharpe:
Technically it will work and if you do it properly, it can be considered OK.
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.
It's usually preferable to write a method called __getnewargs__
instead. That way, the Pickling mechanism will call __init__
for you automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With