I have a float subclass defined as follows:
class NewFloat(float):
def __new__(cls, value, value2):
r = super().__new__(cls, value)
r.value = value2
return r
When I create an instance of this class, all works well -- a = NewFloat(1, 2)
gives an object a
such that a.value
returns 2
. However, when I pickle the object (pickle.dump(a, open('file.p', 'wb'))
) and try to load it (pickle.load(open('file.p', 'rb'))
), it throws the following error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-75-ff08f7f793b8> in <module>
----> 1 b = pickle.load(open('test_pickle.p', 'rb'))
TypeError: __new__() missing 1 required positional argument: 'value2'
What is going on during the pickling process that causes this error? Is __new__
called again, and why?
I've found that adding the attribute in a function definition works fine, but I can't see why this should be any different:
class NewFloat2(float):
def save_value(self, value):
r.value = value
A NewFloat2
instance can be pickled and loaded, no problem. Any insight would be greatly appreciated!