#!/usr/bin/python3
##
## Playing around with pickle and restore with new attributes in class.
##
## $ rm -f my.pickle ; ./test-me.py; echo == ; ./test-me.py
## initialized 1.
## stored to my.pickle: version is 1 hasattr(newattr)=False
## ==
## restored from my.pickle: version is 2 hasattr(newattr)=True version=abcd
import os
import pickle
import sys
pickle_file = "my.pickle" if len(sys.argv) < 2 else sys.argv[1]
is_reload = os.path.exists(pickle_file)
class MyBase(object):
version = None
def __init__(self):
print("initialized %s." % self.version)
def __repr__(self):
return 'version is %s hasattr(newattr)=%s' % (
self.version, hasattr(self, 'newattr'))
if is_reload:
class MyClass(MyBase):
version = 2
newattr = "abcd"
def __repr__(self):
return MyBase.__repr__(self) + " version=%s" % self.newattr
else:
class MyClass(MyBase):
version = 1
if is_reload:
with open(pickle_file, "rb") as fp:
myclass = pickle.loads(fp.read())
print("restored from %s: %s" % (pickle_file, myclass))
else:
myclass = MyClass()
with open(pickle_file, "wb") as fp:
fp.write(pickle.dumps(myclass))
print("stored to %s: %s" % (pickle_file, myclass))