[PYTHON] A special case where pickle causes an error

pickle is a standard library for serializing Python objects into bytes for saving to files etc.

What kind of object can be pickled is [pickle reference] There is a description in (https://docs.python.org/3/library/pickle.html#what-can-be-pickled-and-unpickled), but the phenomenon that objects that refer to each other cannot be unpickled well I checked it, and it seems that there is an unresolved problem as described in This Object Tracker.

When I run the following script, when I unpickle with pickle.loads, I get ```AttributeError:'Node' object has no attribute'i'` ``.

python


# modified from https://bugs.python.org/file2428/circle.py

import pickle

class Node(object):
    def __init__(self, i):
        self.i = i

    def __cmp__(self, other):
        return cmp(self.i, other.i)

    def __hash__(self):
        return hash(self.i)

n = Node(12)
n.next_nodes = set((n,))

byteobj = pickle.dumps(n)
unpickled = pickle.loads(byteobj)

This error occurs because the n of the Node object meets the following conditions, and it is possible that objects that meet these conditions cannot be pickle / unpickle.

This bug was reported in 2007, but in Ichute Tracker, it is a rare case and it is difficult to fix it, so it has been reopened unless it is fixed, and it is still fixed. It doesn't seem to be.

Recommended Posts

A special case where pickle causes an error
[Note] The solution for Python on MacOSX where import hashlib causes an error
A memorandum when an error occurs with pip install