I pickled an instance of a class derived from ndarray, but lose the attributes during pickling/unpickling. Below is simplified code to illustrate the problem. I don't understand:
- Why isn't "attrib" included in pickle dump/load? What do I have to do so that it is included?
- Why isn't __getstate__() called during dump so that I can add the missing "atrrib"? __setstate__() was called. How was the state gotten to be set? My thought was that I would add "attrib" to the gotten state so that I could later set it.
import numpy as np
import pickle
class Xndarray(np.ndarray):
def __new__(cls, **kwargs):
return super().__new__(cls, (5, 3), **kwargs)
def __init__(self, **kwargs):
self[...] = -1
self.attrib = 0
def add2getstate(self):
print("add2getstate()", self.__dict__)
def __getstate__(self): # This never gets called
print("__getstate__()")
return super().__getstate__()
def __setstate__(self, data):
print("__setstate__()")
super().__setstate__(data)
if __name__ == "__main__":
fname = "fname.pkl"
x = Xndarray()
x[0] = 0
x.attrib += 2
print(x)
x.add2getstate()
print(x.attrib)
with open(fname, "wb") as fh:
pickle.dump(x, fh)
print("---------------")
with open(fname, "rb") as fh:
y = pickle.load(fh)
print(y)
y.add2getstate()
print(y.attrib)
Here is the output:
[[ 0. 0. 0.]
[-1. -1. -1.]
[-1. -1. -1.]
[-1. -1. -1.]
[-1. -1. -1.]]
add2getstate() {'attrib': 2}
2
---------------
__setstate__()
[[ 0. 0. 0.]
[-1. -1. -1.]
[-1. -1. -1.]
[-1. -1. -1.]
[-1. -1. -1.]]
add2getstate() {}
Traceback (most recent call last):
File "./t.py", line 48, in <module>
print(y.attrib)
AttributeError: 'Xndarray' object has no attribute 'attrib'