Skip to content

Improve example of pickle "Handling Stateful Objects" #136641

Open
@Serge3leo

Description

@Serge3leo

Documentation

In the example section "pickle — Python object serialization" / "Pickling Class Instances" / "Handling Stateful Objects", the TextReader class code is correct only if it will never be used as one of the base classes of multiple inheritance. In addition, this limitation is not described anywhere, which can cause errors during Cut-and-Paste.

Correct code for the general case:

class TextReader:
    ...
    def __getstate__(self):
        ...
        state = super().__getstate__().copy()
        # Remove the unpicklable entries.
        del state['file']
        return state

    def __setstate__(self, state):
        # Restore instance attributes (i.e., filename and lineno).
        getattr(super(), '__setstate__', self.__dict__.update)(state)
        ...

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsDocumentation in the Doc dirpendingThe issue will be closed if no feedback is provided

    Projects

    Status

    No status

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions