Alright, this is pretty fun.
Code will illustrate best what I’m thinking about:
class Restorable(object):
def __init__(self, a=1, b=1):
self.a = a
self.b = b
def restore(self, serialized_object):
# I'm aware this is local, just illustrating
self = pickle.loads(serialized_object)
r = Restorable()
r.a = 1000
r.b = 2000
saved_state = pickle.dumps(r)
r.a = -1
r.b = -1
r.restore(pickle.dumps(saved_state)
# r.a should again be 1000
# r.b should again be 2000
The idea is: would be possible to, say, pickle.dumps() an object, store it somewhere, modify the real object and later on restore it to its previous state through what I’ve safely stored?
I’ve tried the code I’ve shown above, it does temporarily set self to the previous state, but only locally – well, no surprise here.
This is a curiosity question.
EDIT: To formulate the question in a clear way:
Is it possible to write an object that would restore its state using a serialized object of the same type?
Actually, I see this can be done by creating an instance of the serialized object inside restore() and copying values one by one. But this could be tedious for large objects.
As you said in your edit, create a new object (don’t assign to
self, obviously), but instead of copying the attributes one by one you canand update all your attributes at once. Here’s your complete (reworked) example: