Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork33.3k
Description
You are supposed to be able to override howpickle pickles an object with__getstate__ and__setstate__. However, these methodsare ignored in a dataclass when specifying bothfrozen=True andslots=True.
See this example:
importpicklefromdataclassesimportdataclass@dataclass(frozen=True,slots=True)classFoo:bar:intdef__getstate__(self):print("getstate")return {"bar":self.bar}def__setstate__(self,state):print("setstate")object.__setattr__(self,"bar",state["bar"])b=pickle.dumps(Foo(1))foo=pickle.loads(b)
The expected "getstate" and "setstate" lines are never printed because the supplied methods are never called. If eitherfrozen orslots is removed, the expected lines are printed.
Fromthe source code, it is pretty clear why this is happening. Iffrozen andslots are bothTrue, then special versions of__getstate__ and__setstate__ are unconditionally attached to the dataclass. The dataclass decorator should probably treat this way that it does other methods—only add a method if it is not already present.