Skip to content

Frozen dataclasses with slots cannot override __getstate__ or __setstate__ #104035

@drhagen

Description

@drhagen

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

See this example:

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 expected "getstate" and "setstate" lines are never printed because the supplied methods are never called. If either frozen or slots is removed, the expected lines are printed.

From the source code, it is pretty clear why this is happening. If frozen and slots are both True, 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.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy