I want to pickle an object to be able to store/restore my session. The object holds several references to other objects.
I know that the referred objects get pickled with it, but when unpickling the references change. I also know that pickling the objects together maintains the reference, although this would prove complicated for me to do, as I would need to pickle a whole complex structure of objects.
Example
p1 = Point()
p2 = Point()
p1.nearest_point = p2
p2.nearest_point = p1
line = Line(p1, Point())
with open("pickled", "wb") as file:
pickler = pickle.Pickler(file)
pickler.dump(p1)
pickler.dump(p2)
with open("pickled", "rb") as file:
pickler = pickle.Unpickler(file)
p1 = pickler.load()
p2 = pickler.load()
# True: Reference between the two pickled objects is maintained
assert p1.nearest_point == p2
# False: Reference between not-pickled and pickled objects is broken, leading to a duplicate object (original, unpickled)
assert line.pointA == p1
In this case the solution could be to also pickle the Line object, but in my real-life case I am handling a much more complex structure, where pickling/unpickling every part of the structure would surely lead to oversights and bugs.
How can I correctly handle this?