-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpickle_fun.py
66 lines (46 loc) · 1.41 KB
/
pickle_fun.py
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import pickle
class OldStyle:
def __init__(self):
print 'OldStyle.__init__'
def __getinitargs__(self):
print 'OldStyle.__getinitargs__'
return ()
def __getnewargs__(self):
raise RuntimeError() # Never called.
def __getstate__(self):
print 'OldStyle.__getstate__'
return ('state',)
def __setstate__(self, state):
print 'OldStyle.__setstate__'
class NewStyle(object):
def __init__(self):
print 'NewStyle.__init__'
def __getinitargs__(self):
raise RuntimeError() # Never called.
def __getnewargs__(self):
print 'NewStyle.__getnewargs__'
return ()
def NewStyle__getstate__(self):
print 'NewStyle.__getstate__'
return ('state',)
def NewStyle__setstate__(self, state):
print 'NewStyle.__setstate__'
# You can use "injection" to add the getstate/setstate methods
# to Python C API objects. Works for old and new style objects.
NewStyle.__getstate__ = NewStyle__getstate__
NewStyle.__setstate__ = NewStyle__setstate__
def HaveFun():
for style in (OldStyle, NewStyle):
obj = style()
print 'Have obj'
for protocol in range(pickle.HIGHEST_PROTOCOL):
print 'protocol', protocol
print 'new calling dumps'
serialized = pickle.dumps(obj, protocol=protocol)
print 'Have serialized'
print 'new calling loads'
restored = pickle.loads(serialized)
print 'Have restored'
print
if __name__ == '__main__':
HaveFun()