'Why can't I pickle dataclass with defined __dict__ property?
I have simple dataclass which has __dict__ defined, using asdict, but pickle refuses to serialize it
import pickle
from dataclasses import dataclass, asdict
@dataclass
class Point:
x: int
y: int
@property
def __dict__(self):
return asdict(self)
p = Point(10, 20)
assert p.__dict__ == {'x': 10, 'y': 20}
print(p.__dict__)
b = pickle.dumps(p)
p2 = pickle.loads(b)
print(p2)
outputs
{'x': 10, 'y': 20}
Traceback (most recent call last):
File "C:\Projects\others\pythonPlayground\data_class.py", line 18, in <module>
p2 = pickle.loads(b)
File "C:\Projects\others\pythonPlayground\data_class.py", line 11, in __dict__
return asdict(self)
File "C:\ProgramData\Anaconda3\envs\pythonPlayground\lib\dataclasses.py", line 1075, in asdict
return _asdict_inner(obj, dict_factory)
File "C:\ProgramData\Anaconda3\envs\pythonPlayground\lib\dataclasses.py", line 1082, in _asdict_inner
value = _asdict_inner(getattr(obj, f.name), dict_factory)
AttributeError: 'Point' object has no attribute 'x'
why is that and how to bypass this problem? Or is there any other generic serialization library which can take almost anything, and serialize it to bytes, and it would work?
In the end I tried 2 different packages: dill and cloudpickle and dill works, while cloudpickle not.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
