Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Frozen dataclasses with slots cannot override __getstate__ or __setstate__ #104035

Copy link
Copy link
Closed
@drhagen

Description

@drhagen
Issue body actions

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 dirPython modules in the Lib dirtype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.