Search code examples
pythonpicklepython-dataclasses

Pickle ignores __getstate__ on frozen dataclasses with slots


You are supposed to be able to override how pickle pickles an object with __getstate__ and __setstate__. However, these methods are ignored when a dataclass specifies both frozen=True and slots=True.

import pickle
from dataclasses import dataclass


@dataclass(frozen=True, slots=True)
class Foo:
    bar: int

    def __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 above script should print "getstate" and then "setstate". However, it prints nothing. It prints what I expect if I remove either frozen or slots or both. It is only the combination that fails.

I am on Python 3.11.3.


Solution

  • This was considered a bug and was fixed starting in Python 3.11.4.