Ubuntu Pastebin

Paste from smoser at Wed, 13 Dec 2017 15:05:36 +0000

Download as text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/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))
Download as text