OILS / demo / cpython / pickle_instance.py View on Github | oilshell.org

77 lines, 40 significant
1#!/usr/bin/env python3
2from __future__ import print_function
3
4import pickle
5import sys
6
7
8class Base(object):
9 def __init__(self, n):
10 # IMPORTANT: The pickle has instructions to make
11 # self.__dict__ = {'n': # 10042}.
12 # It doesn't call the constructor or redo this computation.
13 self.n = n + 43
14
15# Note: There are no runtime instructions for inheritance in pickle.
16class Foo(Base):
17
18 def __init__(self, n):
19 Base.__init__(self, n)
20 # look what happens when there are nested objects
21 # the graph is walked
22 self.m1 = Base(99)
23 #self.m2 = Base(99)
24
25 def __repr__(self):
26 return '<Foo %d>' % self.n
27
28
29def PickleInstance(protocol, out_f):
30 f = Foo(10000)
31 print(f)
32
33 i = pickle.dumps(f, protocol=protocol)
34 c = pickle.dumps(Foo, protocol=protocol)
35
36 print(len(i)) # 101 in protocol 0, 36 in protocol 2
37 print(len(c)) # 18 bytes in portocl 0, 19 in protocol 2
38
39 print(repr(i))
40 print(repr(c))
41
42
43 out_f.write(i)
44
45
46def PickleData(protocol, out_f):
47 d = {'key': 'str', 'k2': ['value1', 42, False], 'bool': True, 'float': 0.1}
48
49 # Test out GRAPH
50 d['self'] = d
51
52 i = pickle.dumps(d, protocol=protocol)
53
54 out_f.write(i)
55
56
57
58def main(argv):
59
60 action = argv[1]
61 protocol = int(argv[2])
62 out_path = argv[3]
63
64 if action == 'instance':
65 with open(out_path, 'wb') as f:
66 PickleInstance(protocol, f)
67
68 elif action == 'pure-data':
69 with open(out_path, 'wb') as f:
70 PickleData(protocol, f)
71
72 else:
73 raise RuntimeError(action)
74
75
76main(sys.argv)
77