python - pickling dict inherited class is missing internal values -
i've played around bit code , reason failure when setting 'wham'
value instance of class testdict
works fine long don't try pickle , unpickle it.
because if self.test
missing.
traceback:
traceback (most recent call last): file "test.py", line 30, in <module> loads_a = loads(dumps_a) file "test.py", line 15, in __setitem__ if self.test == false: attributeerror: 'testdict' object has no attribute 'test'
the code:
from pickle import dumps, loads class testdict(dict): def __init__(self, test=false, data={}): super().__init__(data) self.test = test def __getitem__(self, k): if self.test == false: pass return dict.__getitem__(self, k) def __setitem__(self, k, v): if self.test == false: pass if type(v) == dict: super().__setitem__(k, testdict(false, v)) else: super().__setitem__(k, v) if __name__ == '__main__': = testdict() a['wham'] = {'bam' : 1} b = testdict(true) b['wham'] = {'bam' : 2} dumps_a = dumps(a) dumps_b = dumps(b) loads_a = loads(dumps_a) loads_b = loads(dumps_b) print(loads_a) print(loads_b)
the code works if not replacing __setitem__
, __getitem__
want add functionality 2 specific functions.
i've tried:
class testdict(dict): __module__ = os.path.splitext(os.path.basename(__file__))[0]
which sort of worked, long don't nest testdict
within testdict
meaning won't replace __setitem__
, __getitem__
in sub-parts of dictionary.
define __reduce__
method:
class testdict(dict): ... def __reduce__(self): return type(self), (self.test, dict(self))
Comments
Post a Comment