Movatterモバイル変換


[0]ホーム

URL:


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

Sign up
Appearance settings

Frozen dataclasses with slots cannot override __getstate__ or __setstate__ #104035

Closed
Labels
stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error
@drhagen

Description

@drhagen

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.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


      [8]ページ先頭

      ©2009-2025 Movatter.jp