blob: fda4bd7caa4068efe4dafd3d53b3d698d746279d [file] [log] [blame]
Guido van Rossume467be61997-12-05 19:42:42 +00001"""create portable serialized representations of Python objects.
Guido van Rossuma48061a1995-01-10 00:31:14 +00002
Guido van Rossume467be61997-12-05 19:42:42 +00003See module cPickle for a (much) faster implementation.
4See module copy_reg for a mechanism for registering custom picklers.
Guido van Rossuma48061a1995-01-10 00:31:14 +00005
Guido van Rossume467be61997-12-05 19:42:42 +00006Classes:
Guido van Rossuma48061a1995-01-10 00:31:14 +00007
Guido van Rossume467be61997-12-05 19:42:42 +00008 Pickler
9 Unpickler
Guido van Rossuma48061a1995-01-10 00:31:14 +000010
Guido van Rossume467be61997-12-05 19:42:42 +000011Functions:
Guido van Rossuma48061a1995-01-10 00:31:14 +000012
Guido van Rossume467be61997-12-05 19:42:42 +000013 dump(object, file)
14 dumps(object) -> string
15 load(file) -> object
16 loads(string) -> object
Guido van Rossuma48061a1995-01-10 00:31:14 +000017
Guido van Rossume467be61997-12-05 19:42:42 +000018Misc variables:
Guido van Rossuma48061a1995-01-10 00:31:14 +000019
Fred Drakefe82acc1998-02-13 03:24:48 +000020 __version__
Guido van Rossume467be61997-12-05 19:42:42 +000021 format_version
22 compatible_formats
Guido van Rossuma48061a1995-01-10 00:31:14 +000023
Guido van Rossuma48061a1995-01-10 00:31:14 +000024"""
25
Guido van Rossum743d17e1998-09-15 20:25:57 +000026__version__ = "$Revision$" # Code version
Guido van Rossuma48061a1995-01-10 00:31:14 +000027
28from types import *
Guido van Rossum4fb5b281997-09-12 20:07:24 +000029from copy_reg import dispatch_table, safe_constructors
Guido van Rossumd3703791998-10-22 20:15:36 +000030import string
31import marshal
32import sys
33import struct
Guido van Rossuma48061a1995-01-10 00:31:14 +000034
Guido van Rossumd3703791998-10-22 20:15:36 +000035format_version = "1.3" # File format version we write
36compatible_formats = ["1.0", "1.1", "1.2"] # Old format versions we can read
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000037
38mdumps = marshal.dumps
39mloads = marshal.loads
Guido van Rossum0c891ce1995-03-14 15:09:05 +000040
Guido van Rossum7849da81995-03-09 14:08:35 +000041PicklingError = "pickle.PicklingError"
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000042UnpicklingError = "pickle.UnpicklingError"
Guido van Rossum7849da81995-03-09 14:08:35 +000043
Jeremy Hylton2b9d0291998-05-27 22:38:22 +000044try:
45 from org.python.core import PyStringMap
46except ImportError:
47 PyStringMap = None
48
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000049MARK = '('
50STOP = '.'
51POP = '0'
52POP_MARK = '1'
53DUP = '2'
54FLOAT = 'F'
55INT = 'I'
56BININT = 'J'
57BININT1 = 'K'
58LONG = 'L'
59BININT2 = 'M'
60NONE = 'N'
61PERSID = 'P'
62BINPERSID = 'Q'
63REDUCE = 'R'
64STRING = 'S'
65BINSTRING = 'T'
66SHORT_BINSTRING = 'U'
67APPEND = 'a'
68BUILD = 'b'
69GLOBAL = 'c'
70DICT = 'd'
71EMPTY_DICT = '}'
72APPENDS = 'e'
73GET = 'g'
74BINGET = 'h'
75INST = 'i'
76LONG_BINGET = 'j'
77LIST = 'l'
78EMPTY_LIST = ']'
79OBJ = 'o'
80PUT = 'p'
81BINPUT = 'q'
82LONG_BINPUT = 'r'
83SETITEM = 's'
84TUPLE = 't'
85EMPTY_TUPLE = ')'
86SETITEMS = 'u'
Guido van Rossumd3703791998-10-22 20:15:36 +000087BINFLOAT = 'G'
Guido van Rossuma48061a1995-01-10 00:31:14 +000088
89class Pickler:
90
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000091 def __init__(self, file, bin = 0):
92 self.write = file.write
93 self.memo = {}
94 self.bin = bin
Guido van Rossuma48061a1995-01-10 00:31:14 +000095
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000096 def dump(self, object):
97 self.save(object)
98 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +000099
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000100 def put(self, i):
101 if (self.bin):
102 s = mdumps(i)[1:]
103 if (i < 256):
104 return BINPUT + s[0]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000105
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000106 return LONG_BINPUT + s
Guido van Rossuma48061a1995-01-10 00:31:14 +0000107
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000108 return PUT + `i` + '\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000109
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000110 def get(self, i):
111 if (self.bin):
112 s = mdumps(i)[1:]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000113
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000114 if (i < 256):
115 return BINGET + s[0]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000116
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000117 return LONG_BINGET + s
Guido van Rossuma48061a1995-01-10 00:31:14 +0000118
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000119 return GET + `i` + '\n'
120
121 def save(self, object, pers_save = 0):
122 memo = self.memo
Guido van Rossuma48061a1995-01-10 00:31:14 +0000123
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000124 if (not pers_save):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000125 pid = self.persistent_id(object)
126 if (pid is not None):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000127 self.save_pers(pid)
128 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000129
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000130 d = id(object)
131
132 t = type(object)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000133
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000134 if ((t is TupleType) and (len(object) == 0)):
135 if (self.bin):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000136 self.save_empty_tuple(object)
137 else:
138 self.save_tuple(object)
139 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000140
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000141 if memo.has_key(d):
142 self.write(self.get(memo[d][0]))
143 return
144
145 try:
146 f = self.dispatch[t]
147 except KeyError:
148 pid = self.inst_persistent_id(object)
149 if pid is not None:
150 self.save_pers(pid)
151 return
152
153 try:
154 reduce = dispatch_table[t]
155 except KeyError:
156 try:
157 reduce = object.__reduce__
158 except AttributeError:
159 raise PicklingError, \
160 "can't pickle %s objects" % `t.__name__`
161 else:
162 tup = reduce()
163 else:
164 tup = reduce(object)
165
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000166 if type(tup) is StringType:
167 self.save_global(object, tup)
168 return
Guido van Rossumd1f49841997-12-10 23:40:18 +0000169
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000170 if (type(tup) is not TupleType):
171 raise PicklingError, "Value returned by %s must be a " \
172 "tuple" % reduce
173
174 l = len(tup)
175
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000176 if ((l != 2) and (l != 3)):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000177 raise PicklingError, "tuple returned by %s must contain " \
178 "only two or three elements" % reduce
179
180 callable = tup[0]
181 arg_tup = tup[1]
182
183 if (l > 2):
184 state = tup[2]
185 else:
186 state = None
187
Guido van Rossumd1f49841997-12-10 23:40:18 +0000188 if type(arg_tup) is not TupleType and arg_tup is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000189 raise PicklingError, "Second element of tuple returned " \
190 "by %s must be a tuple" % reduce
191
192 self.save_reduce(callable, arg_tup, state)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000193 memo_len = len(memo)
194 self.write(self.put(memo_len))
195 memo[d] = (memo_len, object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000196 return
197
198 f(self, object)
199
200 def persistent_id(self, object):
201 return None
202
203 def inst_persistent_id(self, object):
204 return None
205
206 def save_pers(self, pid):
207 if (not self.bin):
208 self.write(PERSID + str(pid) + '\n')
209 else:
210 self.save(pid, 1)
211 self.write(BINPERSID)
212
213 def save_reduce(self, callable, arg_tup, state = None):
214 write = self.write
215 save = self.save
216
217 save(callable)
218 save(arg_tup)
219 write(REDUCE)
220
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000221 if (state is not None):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000222 save(state)
223 write(BUILD)
224
225 dispatch = {}
226
227 def save_none(self, object):
228 self.write(NONE)
229 dispatch[NoneType] = save_none
230
231 def save_int(self, object):
232 if (self.bin):
233 i = mdumps(object)[1:]
234 if (i[-2:] == '\000\000'):
235 if (i[-3] == '\000'):
236 self.write(BININT1 + i[:-3])
237 return
238
239 self.write(BININT2 + i[:-2])
240 return
241
242 self.write(BININT + i)
243 else:
244 self.write(INT + `object` + '\n')
245 dispatch[IntType] = save_int
246
247 def save_long(self, object):
248 self.write(LONG + `object` + '\n')
249 dispatch[LongType] = save_long
250
Guido van Rossumd3703791998-10-22 20:15:36 +0000251 def save_float(self, object, pack=struct.pack):
252 if self.bin:
253 self.write(BINFLOAT + pack('>d', object))
254 else:
255 self.write(FLOAT + `object` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000256 dispatch[FloatType] = save_float
257
258 def save_string(self, object):
259 d = id(object)
260 memo = self.memo
261
262 if (self.bin):
263 l = len(object)
264 s = mdumps(l)[1:]
265 if (l < 256):
266 self.write(SHORT_BINSTRING + s[0] + object)
267 else:
268 self.write(BINSTRING + s + object)
269 else:
270 self.write(STRING + `object` + '\n')
271
272 memo_len = len(memo)
273 self.write(self.put(memo_len))
274 memo[d] = (memo_len, object)
275 dispatch[StringType] = save_string
276
277 def save_tuple(self, object):
278
279 write = self.write
280 save = self.save
281 memo = self.memo
282
283 d = id(object)
284
285 write(MARK)
286
287 for element in object:
288 save(element)
289
290 if (len(object) and memo.has_key(d)):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000291 if (self.bin):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000292 write(POP_MARK + self.get(memo[d][0]))
293 return
294
Guido van Rossum599174f1998-03-31 16:30:28 +0000295 write(POP * (len(object) + 1) + self.get(memo[d][0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000296 return
297
298 memo_len = len(memo)
299 self.write(TUPLE + self.put(memo_len))
300 memo[d] = (memo_len, object)
301 dispatch[TupleType] = save_tuple
302
303 def save_empty_tuple(self, object):
304 self.write(EMPTY_TUPLE)
305
306 def save_list(self, object):
307 d = id(object)
308
309 write = self.write
310 save = self.save
311 memo = self.memo
312
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000313 if (self.bin):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000314 write(EMPTY_LIST)
315 else:
316 write(MARK + LIST)
317
318 memo_len = len(memo)
319 write(self.put(memo_len))
320 memo[d] = (memo_len, object)
321
322 using_appends = (self.bin and (len(object) > 1))
323
324 if (using_appends):
325 write(MARK)
326
327 for element in object:
328 save(element)
329
330 if (not using_appends):
331 write(APPEND)
332
333 if (using_appends):
334 write(APPENDS)
335 dispatch[ListType] = save_list
336
337 def save_dict(self, object):
338 d = id(object)
339
340 write = self.write
341 save = self.save
342 memo = self.memo
343
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000344 if (self.bin):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000345 write(EMPTY_DICT)
346 else:
347 write(MARK + DICT)
348
349 memo_len = len(memo)
350 self.write(self.put(memo_len))
351 memo[d] = (memo_len, object)
352
353 using_setitems = (self.bin and (len(object) > 1))
354
355 if (using_setitems):
356 write(MARK)
357
358 items = object.items()
359 for key, value in items:
360 save(key)
361 save(value)
362
363 if (not using_setitems):
364 write(SETITEM)
365
366 if (using_setitems):
367 write(SETITEMS)
368
369 dispatch[DictionaryType] = save_dict
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000370 if not PyStringMap is None:
371 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000372
373 def save_inst(self, object):
374 d = id(object)
375 cls = object.__class__
376
377 memo = self.memo
378 write = self.write
379 save = self.save
380
381 if hasattr(object, '__getinitargs__'):
382 args = object.__getinitargs__()
383 len(args) # XXX Assert it's a sequence
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000384 _keep_alive(args, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000385 else:
386 args = ()
387
388 write(MARK)
389
390 if (self.bin):
391 save(cls)
392
393 for arg in args:
394 save(arg)
395
396 memo_len = len(memo)
397 if (self.bin):
398 write(OBJ + self.put(memo_len))
399 else:
Guido van Rossum4fb5b281997-09-12 20:07:24 +0000400 write(INST + cls.__module__ + '\n' + cls.__name__ + '\n' +
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000401 self.put(memo_len))
402
403 memo[d] = (memo_len, object)
404
405 try:
406 getstate = object.__getstate__
407 except AttributeError:
408 stuff = object.__dict__
409 else:
410 stuff = getstate()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000411 _keep_alive(stuff, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000412 save(stuff)
413 write(BUILD)
414 dispatch[InstanceType] = save_inst
415
416 def save_global(self, object, name = None):
417 write = self.write
418 memo = self.memo
419
420 if (name is None):
421 name = object.__name__
422
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000423 try:
424 module = object.__module__
425 except AttributeError:
426 module = whichmodule(object, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000427
428 memo_len = len(memo)
429 write(GLOBAL + module + '\n' + name + '\n' +
430 self.put(memo_len))
431 memo[id(object)] = (memo_len, object)
432 dispatch[ClassType] = save_global
433 dispatch[FunctionType] = save_global
434 dispatch[BuiltinFunctionType] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000435
Guido van Rossuma48061a1995-01-10 00:31:14 +0000436
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000437def _keep_alive(x, memo):
438 """Keeps a reference to the object x in the memo.
439
440 Because we remember objects by their id, we have
441 to assure that possibly temporary objects are kept
442 alive by referencing them.
443 We store a reference at the id of the memo, which should
444 normally not be used unless someone tries to deepcopy
445 the memo itself...
446 """
447 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000448 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000449 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000450 # aha, this is the first one :-)
451 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000452
453
Guido van Rossuma48061a1995-01-10 00:31:14 +0000454classmap = {}
455
Guido van Rossum4fb5b281997-09-12 20:07:24 +0000456# This is no longer used to find classes, but still for functions
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000457def whichmodule(cls, clsname):
458 """Figure out the module in which a class occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000459
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000460 Search sys.modules for the module.
461 Cache in classmap.
462 Return a module name.
463 If the class cannot be found, return __main__.
464 """
465 if classmap.has_key(cls):
466 return classmap[cls]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000467
468 for name, module in sys.modules.items():
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000469 if name != '__main__' and \
470 hasattr(module, clsname) and \
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000471 getattr(module, clsname) is cls:
472 break
473 else:
474 name = '__main__'
475 classmap[cls] = name
476 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000477
478
479class Unpickler:
480
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000481 def __init__(self, file):
482 self.readline = file.readline
483 self.read = file.read
484 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000485
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000486 def load(self):
487 self.mark = ['spam'] # Any new unique object
488 self.stack = []
489 self.append = self.stack.append
490 read = self.read
491 dispatch = self.dispatch
492 try:
493 while 1:
494 key = read(1)
495 dispatch[key](self)
496 except STOP, value:
497 return value
498
499 def marker(self):
500 stack = self.stack
501 mark = self.mark
502 k = len(stack)-1
503 while stack[k] is not mark: k = k-1
504 return k
505
506 dispatch = {}
507
508 def load_eof(self):
509 raise EOFError
510 dispatch[''] = load_eof
511
512 def load_persid(self):
513 pid = self.readline()[:-1]
514 self.append(self.persistent_load(pid))
515 dispatch[PERSID] = load_persid
516
517 def load_binpersid(self):
518 stack = self.stack
519
520 pid = stack[-1]
521 del stack[-1]
522
523 self.append(self.persistent_load(pid))
524 dispatch[BINPERSID] = load_binpersid
525
526 def load_none(self):
527 self.append(None)
528 dispatch[NONE] = load_none
529
530 def load_int(self):
Guido van Rossume6805461997-12-10 19:36:41 +0000531 self.append(string.atoi(self.readline()[:-1]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000532 dispatch[INT] = load_int
533
534 def load_binint(self):
535 self.append(mloads('i' + self.read(4)))
536 dispatch[BININT] = load_binint
537
538 def load_binint1(self):
539 self.append(mloads('i' + self.read(1) + '\000\000\000'))
540 dispatch[BININT1] = load_binint1
541
542 def load_binint2(self):
543 self.append(mloads('i' + self.read(2) + '\000\000'))
544 dispatch[BININT2] = load_binint2
545
546 def load_long(self):
547 self.append(string.atol(self.readline()[:-1], 0))
548 dispatch[LONG] = load_long
549
550 def load_float(self):
551 self.append(string.atof(self.readline()[:-1]))
552 dispatch[FLOAT] = load_float
553
Guido van Rossumd3703791998-10-22 20:15:36 +0000554 def load_binfloat(self, unpack=struct.unpack):
555 self.append(unpack('>d', self.read(8))[0])
556 dispatch[BINFLOAT] = load_binfloat
557
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000558 def load_string(self):
559 self.append(eval(self.readline()[:-1],
560 {'__builtins__': {}})) # Let's be careful
561 dispatch[STRING] = load_string
562
563 def load_binstring(self):
564 len = mloads('i' + self.read(4))
565 self.append(self.read(len))
566 dispatch[BINSTRING] = load_binstring
567
568 def load_short_binstring(self):
569 len = mloads('i' + self.read(1) + '\000\000\000')
570 self.append(self.read(len))
571 dispatch[SHORT_BINSTRING] = load_short_binstring
572
573 def load_tuple(self):
574 k = self.marker()
575 self.stack[k:] = [tuple(self.stack[k+1:])]
576 dispatch[TUPLE] = load_tuple
577
578 def load_empty_tuple(self):
579 self.stack.append(())
580 dispatch[EMPTY_TUPLE] = load_empty_tuple
581
582 def load_empty_list(self):
583 self.stack.append([])
584 dispatch[EMPTY_LIST] = load_empty_list
585
586 def load_empty_dictionary(self):
587 self.stack.append({})
588 dispatch[EMPTY_DICT] = load_empty_dictionary
589
590 def load_list(self):
591 k = self.marker()
592 self.stack[k:] = [self.stack[k+1:]]
593 dispatch[LIST] = load_list
594
595 def load_dict(self):
596 k = self.marker()
597 d = {}
598 items = self.stack[k+1:]
599 for i in range(0, len(items), 2):
600 key = items[i]
601 value = items[i+1]
602 d[key] = value
603 self.stack[k:] = [d]
604 dispatch[DICT] = load_dict
605
606 def load_inst(self):
607 k = self.marker()
608 args = tuple(self.stack[k+1:])
609 del self.stack[k:]
610 module = self.readline()[:-1]
611 name = self.readline()[:-1]
612 klass = self.find_class(module, name)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000613 instantiated = 0
614 if (not args and type(klass) is ClassType and
615 not hasattr(klass, "__getinitargs__")):
616 try:
617 value = _EmptyClass()
618 value.__class__ = klass
Guido van Rossumb19e2a31998-04-13 18:08:45 +0000619 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000620 except RuntimeError:
621 # In restricted execution, assignment to inst.__class__ is
622 # prohibited
623 pass
624 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +0000625 try:
626 value = apply(klass, args)
627 except TypeError, err:
628 raise TypeError, "in constructor for %s: %s" % (
629 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000630 self.append(value)
631 dispatch[INST] = load_inst
632
633 def load_obj(self):
634 stack = self.stack
635 k = self.marker()
636 klass = stack[k + 1]
637 del stack[k + 1]
638 args = tuple(stack[k + 1:])
639 del stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000640 instantiated = 0
641 if (not args and type(klass) is ClassType and
642 not hasattr(klass, "__getinitargs__")):
643 try:
644 value = _EmptyClass()
645 value.__class__ = klass
646 instantiated = 1
647 except RuntimeError:
648 # In restricted execution, assignment to inst.__class__ is
649 # prohibited
650 pass
651 if not instantiated:
652 value = apply(klass, args)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000653 self.append(value)
654 dispatch[OBJ] = load_obj
655
656 def load_global(self):
657 module = self.readline()[:-1]
658 name = self.readline()[:-1]
659 klass = self.find_class(module, name)
660 self.append(klass)
661 dispatch[GLOBAL] = load_global
662
663 def find_class(self, module, name):
664 env = {}
665
666 try:
667 exec 'from %s import %s' % (module, name) in env
668 except ImportError:
669 raise SystemError, \
670 "Failed to import class %s from module %s" % \
671 (name, module)
672 klass = env[name]
673 return klass
674
675 def load_reduce(self):
676 stack = self.stack
677
678 callable = stack[-2]
679 arg_tup = stack[-1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000680 del stack[-2:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000681
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000682 if type(callable) is not ClassType:
683 if not safe_constructors.has_key(callable):
684 try:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000685 safe = callable.__safe_for_unpickling__
686 except AttributeError:
687 safe = None
Guido van Rossuma48061a1995-01-10 00:31:14 +0000688
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000689 if (not safe):
690 raise UnpicklingError, "%s is not safe for " \
691 "unpickling" % callable
Guido van Rossuma48061a1995-01-10 00:31:14 +0000692
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000693 if arg_tup is None:
694 value = callable.__basicnew__()
695 else:
696 value = apply(callable, arg_tup)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000697 self.append(value)
698 dispatch[REDUCE] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +0000699
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000700 def load_pop(self):
701 del self.stack[-1]
702 dispatch[POP] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +0000703
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000704 def load_pop_mark(self):
705 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000706 del self.stack[k:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000707 dispatch[POP_MARK] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +0000708
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000709 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +0000710 self.append(self.stack[-1])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000711 dispatch[DUP] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +0000712
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000713 def load_get(self):
714 self.append(self.memo[self.readline()[:-1]])
715 dispatch[GET] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +0000716
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000717 def load_binget(self):
718 i = mloads('i' + self.read(1) + '\000\000\000')
719 self.append(self.memo[`i`])
720 dispatch[BINGET] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +0000721
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000722 def load_long_binget(self):
723 i = mloads('i' + self.read(4))
724 self.append(self.memo[`i`])
725 dispatch[LONG_BINGET] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +0000726
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000727 def load_put(self):
728 self.memo[self.readline()[:-1]] = self.stack[-1]
729 dispatch[PUT] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +0000730
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000731 def load_binput(self):
732 i = mloads('i' + self.read(1) + '\000\000\000')
733 self.memo[`i`] = self.stack[-1]
734 dispatch[BINPUT] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +0000735
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000736 def load_long_binput(self):
737 i = mloads('i' + self.read(4))
738 self.memo[`i`] = self.stack[-1]
739 dispatch[LONG_BINPUT] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +0000740
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000741 def load_append(self):
742 stack = self.stack
743 value = stack[-1]
744 del stack[-1]
745 list = stack[-1]
746 list.append(value)
747 dispatch[APPEND] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +0000748
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000749 def load_appends(self):
750 stack = self.stack
751 mark = self.marker()
752 list = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000753 for i in range(mark + 1, len(stack)):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000754 list.append(stack[i])
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000755
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000756 del stack[mark:]
757 dispatch[APPENDS] = load_appends
758
759 def load_setitem(self):
760 stack = self.stack
761 value = stack[-1]
762 key = stack[-2]
763 del stack[-2:]
764 dict = stack[-1]
765 dict[key] = value
766 dispatch[SETITEM] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000767
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000768 def load_setitems(self):
769 stack = self.stack
770 mark = self.marker()
771 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000772 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000773 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000774
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000775 del stack[mark:]
776 dispatch[SETITEMS] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +0000777
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000778 def load_build(self):
779 stack = self.stack
780 value = stack[-1]
781 del stack[-1]
782 inst = stack[-1]
783 try:
784 setstate = inst.__setstate__
785 except AttributeError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000786 try:
787 inst.__dict__.update(value)
788 except RuntimeError:
789 # XXX In restricted execution, the instance's __dict__ is not
790 # accessible. Use the old way of unpickling the instance
791 # variables. This is a semantic different when unpickling in
792 # restricted vs. unrestricted modes.
793 for k, v in value.items():
794 setattr(inst, k, v)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000795 else:
796 setstate(value)
797 dispatch[BUILD] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +0000798
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000799 def load_mark(self):
800 self.append(self.mark)
801 dispatch[MARK] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +0000802
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000803 def load_stop(self):
804 value = self.stack[-1]
805 del self.stack[-1]
806 raise STOP, value
807 dispatch[STOP] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +0000808
Guido van Rossume467be61997-12-05 19:42:42 +0000809# Helper class for load_inst/load_obj
810
811class _EmptyClass:
812 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +0000813
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000814# Shorthands
815
Guido van Rossumc7c5e691996-07-22 22:26:07 +0000816from StringIO import StringIO
817
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000818def dump(object, file, bin = 0):
819 Pickler(file, bin).dump(object)
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000820
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000821def dumps(object, bin = 0):
822 file = StringIO()
823 Pickler(file, bin).dump(object)
824 return file.getvalue()
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000825
826def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000827 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000828
829def loads(str):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000830 file = StringIO(str)
831 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000832
833
834# The rest is used for testing only
835
Guido van Rossuma48061a1995-01-10 00:31:14 +0000836class C:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000837 def __cmp__(self, other):
838 return cmp(self.__dict__, other.__dict__)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000839
840def test():
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000841 fn = 'out'
842 c = C()
843 c.foo = 1
844 c.bar = 2
845 x = [0, 1, 2, 3]
846 y = ('abc', 'abc', c, c)
847 x.append(y)
848 x.append(y)
849 x.append(5)
850 f = open(fn, 'w')
851 F = Pickler(f)
852 F.dump(x)
853 f.close()
854 f = open(fn, 'r')
855 U = Unpickler(f)
856 x2 = U.load()
857 print x
858 print x2
859 print x == x2
860 print map(id, x)
861 print map(id, x2)
862 print F.memo
863 print U.memo
Guido van Rossuma48061a1995-01-10 00:31:14 +0000864
865if __name__ == '__main__':
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000866 test()