Skip to content

Add support for pickle protocol special methods #139

@warsaw

Description

@warsaw

It might be kind of cool for @attr.s to optionally support __getstate__() and __setstate__(). I'm using the following and it seems to work well:

    def __getstate__(self):
        state = super().__getstate__()
        # Don't recurse when getting a pickle-able dictionary in case any of
        # our attributes is also an @attr.s and we want to retain its
        # object nature, instead of turning it into a dictionary which
        # can't be unpickled correctly.
        state.update(attr.asdict(self, recurse=False))
        return state

    def __setstate__(self, state):
        super().__setstate__(state)
        for field in attr.fields(self.__class__):
            setattr(self, field.name, state.get(field.name, field.default))

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions