blob: a8b2b51567a349542ac69b1431f2b49715143399 [file] [log] [blame]
Guido van Rossum54f22ed2000-02-04 15:10:34 +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 marshal
31import sys
32import struct
Skip Montanaro23bafc62001-02-18 03:10:09 +000033import re
Guido van Rossuma48061a1995-01-10 00:31:14 +000034
Skip Montanaro352674d2001-02-07 23:14:30 +000035__all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler",
36 "Unpickler", "dump", "dumps", "load", "loads"]
37
Guido van Rossumd3703791998-10-22 20:15:36 +000038format_version = "1.3" # File format version we write
39compatible_formats = ["1.0", "1.1", "1.2"] # Old format versions we can read
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000040
41mdumps = marshal.dumps
42mloads = marshal.loads
Guido van Rossum0c891ce1995-03-14 15:09:05 +000043
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000044class PickleError(Exception):
Neal Norwitzefbb67b2002-05-30 12:12:04 +000045 """A common base class for the other pickling exceptions."""
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000046 pass
47
48class PicklingError(PickleError):
49 """This exception is raised when an unpicklable object is passed to the
50 dump() method.
51
52 """
53 pass
54
55class UnpicklingError(PickleError):
56 """This exception is raised when there is a problem unpickling an object,
57 such as a security violation.
58
59 Note that other exceptions may also be raised during unpickling, including
60 (but not necessarily limited to) AttributeError, EOFError, ImportError,
61 and IndexError.
62
63 """
64 pass
Guido van Rossum7849da81995-03-09 14:08:35 +000065
Guido van Rossumff871742000-12-13 18:11:56 +000066class _Stop(Exception):
67 def __init__(self, value):
68 self.value = value
69
Jeremy Hylton2b9d0291998-05-27 22:38:22 +000070try:
71 from org.python.core import PyStringMap
72except ImportError:
73 PyStringMap = None
74
Guido van Rossumdbb718f2001-09-21 19:22:34 +000075try:
76 UnicodeType
77except NameError:
78 UnicodeType = None
79
80
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000081MARK = '('
82STOP = '.'
83POP = '0'
84POP_MARK = '1'
85DUP = '2'
86FLOAT = 'F'
87INT = 'I'
88BININT = 'J'
89BININT1 = 'K'
90LONG = 'L'
91BININT2 = 'M'
92NONE = 'N'
93PERSID = 'P'
94BINPERSID = 'Q'
95REDUCE = 'R'
96STRING = 'S'
97BINSTRING = 'T'
98SHORT_BINSTRING = 'U'
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +000099UNICODE = 'V'
100BINUNICODE = 'X'
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000101APPEND = 'a'
102BUILD = 'b'
103GLOBAL = 'c'
104DICT = 'd'
105EMPTY_DICT = '}'
106APPENDS = 'e'
107GET = 'g'
108BINGET = 'h'
109INST = 'i'
110LONG_BINGET = 'j'
111LIST = 'l'
112EMPTY_LIST = ']'
113OBJ = 'o'
114PUT = 'p'
115BINPUT = 'q'
116LONG_BINPUT = 'r'
117SETITEM = 's'
118TUPLE = 't'
119EMPTY_TUPLE = ')'
120SETITEMS = 'u'
Guido van Rossumd3703791998-10-22 20:15:36 +0000121BINFLOAT = 'G'
Guido van Rossume2763392002-04-05 19:30:08 +0000122TRUE = 'I01\n'
123FALSE = 'I00\n'
Guido van Rossum77f6a652002-04-03 22:41:51 +0000124
Guido van Rossuma48061a1995-01-10 00:31:14 +0000125
Skip Montanaro23bafc62001-02-18 03:10:09 +0000126__all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
Neal Norwitzd5ba4ae2002-02-11 18:12:06 +0000127del x
Skip Montanaro23bafc62001-02-18 03:10:09 +0000128
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000129_quotes = ["'", '"']
130
Guido van Rossuma48061a1995-01-10 00:31:14 +0000131class Pickler:
132
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000133 def __init__(self, file, bin = 0):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000134 """This takes a file-like object for writing a pickle data stream.
135
136 The optional bin parameter if true, tells the pickler to use the more
137 efficient binary pickle format, otherwise the ASCII format is used
138 (this is the default).
139
140 The file parameter must have a write() method that accepts a single
141 string argument. It can thus be an open file object, a StringIO
142 object, or any other custom object that meets this interface.
143
144 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000145 self.write = file.write
146 self.memo = {}
147 self.bin = bin
Guido van Rossuma48061a1995-01-10 00:31:14 +0000148
Fred Drake7f781c92002-05-01 20:33:53 +0000149 def clear_memo(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000150 """Clears the pickler's "memo".
151
152 The memo is the data structure that remembers which objects the
153 pickler has already seen, so that shared or recursive objects pickled
154 by reference and not by value. This method is useful when re-using
155 picklers.
156
157 """
Fred Drake7f781c92002-05-01 20:33:53 +0000158 self.memo.clear()
159
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000160 def dump(self, object):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000161 """Write a pickled representation of object to the open file object.
162
163 Either the binary or ASCII format will be used, depending on the
164 value of the bin flag passed to the constructor.
165
166 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000167 self.save(object)
168 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000169
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000170 def put(self, i):
Tim Petersc32d8242001-04-10 02:48:53 +0000171 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000172 s = mdumps(i)[1:]
Tim Petersc32d8242001-04-10 02:48:53 +0000173 if i < 256:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000174 return BINPUT + s[0]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000175
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000176 return LONG_BINPUT + s
Guido van Rossuma48061a1995-01-10 00:31:14 +0000177
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000178 return PUT + `i` + '\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000179
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000180 def get(self, i):
Tim Petersc32d8242001-04-10 02:48:53 +0000181 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000182 s = mdumps(i)[1:]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000183
Tim Petersc32d8242001-04-10 02:48:53 +0000184 if i < 256:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000185 return BINGET + s[0]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000186
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000187 return LONG_BINGET + s
Guido van Rossuma48061a1995-01-10 00:31:14 +0000188
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000189 return GET + `i` + '\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000190
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000191 def save(self, object):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000192 memo = self.memo
Guido van Rossuma48061a1995-01-10 00:31:14 +0000193
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000194 pid = self.persistent_id(object)
195 if pid is not None:
196 self.save_pers(pid)
197 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000198
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000199 d = id(object)
Tim Peters2344fae2001-01-15 00:50:52 +0000200
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000201 t = type(object)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000202
Tim Petersc32d8242001-04-10 02:48:53 +0000203 if (t is TupleType) and (len(object) == 0):
204 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000205 self.save_empty_tuple(object)
206 else:
207 self.save_tuple(object)
208 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000209
Raymond Hettinger54f02222002-06-01 14:18:47 +0000210 if d in memo:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000211 self.write(self.get(memo[d][0]))
212 return
213
214 try:
215 f = self.dispatch[t]
216 except KeyError:
Guido van Rossum85ee4912002-03-26 00:51:56 +0000217 try:
218 issc = issubclass(t, TypeType)
219 except TypeError: # t is not a class
220 issc = 0
221 if issc:
Guido van Rossumf048a8f2001-12-19 16:55:02 +0000222 self.save_global(object)
223 return
224
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000225 try:
226 reduce = dispatch_table[t]
227 except KeyError:
228 try:
229 reduce = object.__reduce__
230 except AttributeError:
231 raise PicklingError, \
Guido van Rossum08a92cb1999-10-10 21:14:25 +0000232 "can't pickle %s object: %s" % (`t.__name__`,
233 `object`)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000234 else:
235 tup = reduce()
236 else:
237 tup = reduce(object)
238
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000239 if type(tup) is StringType:
240 self.save_global(object, tup)
241 return
Guido van Rossumd1f49841997-12-10 23:40:18 +0000242
Tim Petersc32d8242001-04-10 02:48:53 +0000243 if type(tup) is not TupleType:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000244 raise PicklingError, "Value returned by %s must be a " \
245 "tuple" % reduce
246
247 l = len(tup)
Tim Peters2344fae2001-01-15 00:50:52 +0000248
Tim Petersc32d8242001-04-10 02:48:53 +0000249 if (l != 2) and (l != 3):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000250 raise PicklingError, "tuple returned by %s must contain " \
251 "only two or three elements" % reduce
252
253 callable = tup[0]
254 arg_tup = tup[1]
Tim Peters2344fae2001-01-15 00:50:52 +0000255
Tim Petersc32d8242001-04-10 02:48:53 +0000256 if l > 2:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000257 state = tup[2]
258 else:
259 state = None
260
Guido van Rossumd1f49841997-12-10 23:40:18 +0000261 if type(arg_tup) is not TupleType and arg_tup is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000262 raise PicklingError, "Second element of tuple returned " \
263 "by %s must be a tuple" % reduce
264
Tim Peters2344fae2001-01-15 00:50:52 +0000265 self.save_reduce(callable, arg_tup, state)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000266 memo_len = len(memo)
267 self.write(self.put(memo_len))
268 memo[d] = (memo_len, object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000269 return
270
271 f(self, object)
272
273 def persistent_id(self, object):
274 return None
275
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000276 def save_pers(self, pid):
Tim Petersc32d8242001-04-10 02:48:53 +0000277 if not self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000278 self.write(PERSID + str(pid) + '\n')
279 else:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000280 self.save(pid)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000281 self.write(BINPERSID)
282
283 def save_reduce(self, callable, arg_tup, state = None):
284 write = self.write
285 save = self.save
286
287 save(callable)
288 save(arg_tup)
289 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000290
Tim Petersc32d8242001-04-10 02:48:53 +0000291 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000292 save(state)
293 write(BUILD)
294
295 dispatch = {}
296
297 def save_none(self, object):
298 self.write(NONE)
299 dispatch[NoneType] = save_none
300
Guido van Rossum77f6a652002-04-03 22:41:51 +0000301 def save_bool(self, object):
302 if object:
303 self.write(TRUE)
304 else:
305 self.write(FALSE)
306 dispatch[bool] = save_bool
307
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000308 def save_int(self, object):
Tim Petersc32d8242001-04-10 02:48:53 +0000309 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000310 # If the int is small enough to fit in a signed 4-byte 2's-comp
311 # format, we can store it more efficiently than the general
312 # case.
313 high_bits = object >> 31 # note that Python shift sign-extends
314 if high_bits == 0 or high_bits == -1:
315 # All high bits are copies of bit 2**31, so the value
316 # fits in a 4-byte signed int.
317 i = mdumps(object)[1:]
318 assert len(i) == 4
319 if i[-2:] == '\000\000': # fits in 2-byte unsigned int
320 if i[-3] == '\000': # fits in 1-byte unsigned int
321 self.write(BININT1 + i[0])
322 else:
323 self.write(BININT2 + i[:2])
324 else:
325 self.write(BININT + i)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000326 return
Tim Peters44714002001-04-10 05:02:52 +0000327 # Text pickle, or int too big to fit in signed 4-byte format.
328 self.write(INT + `object` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000329 dispatch[IntType] = save_int
330
331 def save_long(self, object):
332 self.write(LONG + `object` + '\n')
333 dispatch[LongType] = save_long
334
Guido van Rossumd3703791998-10-22 20:15:36 +0000335 def save_float(self, object, pack=struct.pack):
336 if self.bin:
337 self.write(BINFLOAT + pack('>d', object))
338 else:
339 self.write(FLOAT + `object` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000340 dispatch[FloatType] = save_float
341
342 def save_string(self, object):
343 d = id(object)
344 memo = self.memo
345
Tim Petersc32d8242001-04-10 02:48:53 +0000346 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000347 l = len(object)
348 s = mdumps(l)[1:]
Tim Petersc32d8242001-04-10 02:48:53 +0000349 if l < 256:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000350 self.write(SHORT_BINSTRING + s[0] + object)
351 else:
352 self.write(BINSTRING + s + object)
353 else:
354 self.write(STRING + `object` + '\n')
355
356 memo_len = len(memo)
357 self.write(self.put(memo_len))
358 memo[d] = (memo_len, object)
359 dispatch[StringType] = save_string
360
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000361 def save_unicode(self, object):
362 d = id(object)
363 memo = self.memo
364
Tim Petersc32d8242001-04-10 02:48:53 +0000365 if self.bin:
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000366 encoding = object.encode('utf-8')
367 l = len(encoding)
368 s = mdumps(l)[1:]
369 self.write(BINUNICODE + s + encoding)
370 else:
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000371 object = object.replace("\\", "\\u005c")
372 object = object.replace("\n", "\\u000a")
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000373 self.write(UNICODE + object.encode('raw-unicode-escape') + '\n')
374
375 memo_len = len(memo)
376 self.write(self.put(memo_len))
377 memo[d] = (memo_len, object)
378 dispatch[UnicodeType] = save_unicode
379
Guido van Rossum31584cb2001-01-22 14:53:29 +0000380 if StringType == UnicodeType:
381 # This is true for Jython
382 def save_string(self, object):
383 d = id(object)
384 memo = self.memo
385 unicode = object.isunicode()
386
Tim Petersc32d8242001-04-10 02:48:53 +0000387 if self.bin:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000388 if unicode:
389 object = object.encode("utf-8")
390 l = len(object)
391 s = mdumps(l)[1:]
Tim Petersc32d8242001-04-10 02:48:53 +0000392 if l < 256 and not unicode:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000393 self.write(SHORT_BINSTRING + s[0] + object)
394 else:
395 if unicode:
396 self.write(BINUNICODE + s + object)
397 else:
398 self.write(BINSTRING + s + object)
399 else:
Tim Peters658cba62001-02-09 20:06:00 +0000400 if unicode:
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000401 object = object.replace("\\", "\\u005c")
402 object = object.replace("\n", "\\u000a")
Guido van Rossum31584cb2001-01-22 14:53:29 +0000403 object = object.encode('raw-unicode-escape')
404 self.write(UNICODE + object + '\n')
405 else:
406 self.write(STRING + `object` + '\n')
407
408 memo_len = len(memo)
409 self.write(self.put(memo_len))
410 memo[d] = (memo_len, object)
411 dispatch[StringType] = save_string
Tim Peters658cba62001-02-09 20:06:00 +0000412
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000413 def save_tuple(self, object):
414
415 write = self.write
416 save = self.save
417 memo = self.memo
418
419 d = id(object)
420
421 write(MARK)
422
423 for element in object:
424 save(element)
425
Raymond Hettinger54f02222002-06-01 14:18:47 +0000426 if len(object) and d in memo:
Tim Petersc32d8242001-04-10 02:48:53 +0000427 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000428 write(POP_MARK + self.get(memo[d][0]))
429 return
Tim Peters2344fae2001-01-15 00:50:52 +0000430
Guido van Rossum599174f1998-03-31 16:30:28 +0000431 write(POP * (len(object) + 1) + self.get(memo[d][0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000432 return
433
434 memo_len = len(memo)
435 self.write(TUPLE + self.put(memo_len))
436 memo[d] = (memo_len, object)
437 dispatch[TupleType] = save_tuple
438
439 def save_empty_tuple(self, object):
440 self.write(EMPTY_TUPLE)
441
442 def save_list(self, object):
443 d = id(object)
444
445 write = self.write
446 save = self.save
447 memo = self.memo
448
Tim Petersc32d8242001-04-10 02:48:53 +0000449 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000450 write(EMPTY_LIST)
451 else:
452 write(MARK + LIST)
453
454 memo_len = len(memo)
455 write(self.put(memo_len))
456 memo[d] = (memo_len, object)
457
458 using_appends = (self.bin and (len(object) > 1))
459
Tim Petersc32d8242001-04-10 02:48:53 +0000460 if using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000461 write(MARK)
462
463 for element in object:
464 save(element)
Tim Peters2344fae2001-01-15 00:50:52 +0000465
Tim Petersc32d8242001-04-10 02:48:53 +0000466 if not using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000467 write(APPEND)
468
Tim Petersc32d8242001-04-10 02:48:53 +0000469 if using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000470 write(APPENDS)
471 dispatch[ListType] = save_list
472
473 def save_dict(self, object):
474 d = id(object)
475
476 write = self.write
477 save = self.save
478 memo = self.memo
479
Tim Petersc32d8242001-04-10 02:48:53 +0000480 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000481 write(EMPTY_DICT)
482 else:
483 write(MARK + DICT)
484
485 memo_len = len(memo)
486 self.write(self.put(memo_len))
487 memo[d] = (memo_len, object)
488
489 using_setitems = (self.bin and (len(object) > 1))
490
Tim Petersc32d8242001-04-10 02:48:53 +0000491 if using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000492 write(MARK)
493
494 items = object.items()
495 for key, value in items:
496 save(key)
497 save(value)
498
Tim Petersc32d8242001-04-10 02:48:53 +0000499 if not using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000500 write(SETITEM)
501
Tim Petersc32d8242001-04-10 02:48:53 +0000502 if using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000503 write(SETITEMS)
504
505 dispatch[DictionaryType] = save_dict
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000506 if not PyStringMap is None:
507 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000508
509 def save_inst(self, object):
510 d = id(object)
511 cls = object.__class__
512
513 memo = self.memo
514 write = self.write
515 save = self.save
516
517 if hasattr(object, '__getinitargs__'):
518 args = object.__getinitargs__()
519 len(args) # XXX Assert it's a sequence
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000520 _keep_alive(args, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000521 else:
522 args = ()
523
524 write(MARK)
525
Tim Petersc32d8242001-04-10 02:48:53 +0000526 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000527 save(cls)
528
529 for arg in args:
530 save(arg)
531
532 memo_len = len(memo)
Tim Petersc32d8242001-04-10 02:48:53 +0000533 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000534 write(OBJ + self.put(memo_len))
535 else:
Guido van Rossum4fb5b281997-09-12 20:07:24 +0000536 write(INST + cls.__module__ + '\n' + cls.__name__ + '\n' +
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000537 self.put(memo_len))
538
539 memo[d] = (memo_len, object)
540
541 try:
542 getstate = object.__getstate__
543 except AttributeError:
544 stuff = object.__dict__
545 else:
546 stuff = getstate()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000547 _keep_alive(stuff, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000548 save(stuff)
549 write(BUILD)
550 dispatch[InstanceType] = save_inst
551
552 def save_global(self, object, name = None):
553 write = self.write
554 memo = self.memo
555
Tim Petersc32d8242001-04-10 02:48:53 +0000556 if name is None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000557 name = object.__name__
558
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000559 try:
560 module = object.__module__
561 except AttributeError:
562 module = whichmodule(object, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000563
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000564 try:
565 __import__(module)
566 mod = sys.modules[module]
567 klass = getattr(mod, name)
568 except (ImportError, KeyError, AttributeError):
569 raise PicklingError(
570 "Can't pickle %r: it's not found as %s.%s" %
571 (object, module, name))
572 else:
573 if klass is not object:
574 raise PicklingError(
575 "Can't pickle %r: it's not the same object as %s.%s" %
576 (object, module, name))
577
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000578 memo_len = len(memo)
579 write(GLOBAL + module + '\n' + name + '\n' +
580 self.put(memo_len))
581 memo[id(object)] = (memo_len, object)
582 dispatch[ClassType] = save_global
583 dispatch[FunctionType] = save_global
584 dispatch[BuiltinFunctionType] = save_global
Tim Peters6d6c1a32001-08-02 04:15:00 +0000585 dispatch[TypeType] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000586
Guido van Rossuma48061a1995-01-10 00:31:14 +0000587
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000588def _keep_alive(x, memo):
589 """Keeps a reference to the object x in the memo.
590
591 Because we remember objects by their id, we have
592 to assure that possibly temporary objects are kept
593 alive by referencing them.
594 We store a reference at the id of the memo, which should
595 normally not be used unless someone tries to deepcopy
596 the memo itself...
597 """
598 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000599 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000600 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000601 # aha, this is the first one :-)
602 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000603
604
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000605classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000606
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000607def whichmodule(func, funcname):
608 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000609
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000610 Search sys.modules for the module.
611 Cache in classmap.
612 Return a module name.
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000613 If the function cannot be found, return __main__.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000614 """
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000615 if func in classmap:
616 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000617
618 for name, module in sys.modules.items():
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000619 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000620 continue # skip dummy package entries
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000621 if name != '__main__' and \
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000622 hasattr(module, funcname) and \
623 getattr(module, funcname) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000624 break
625 else:
626 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000627 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000628 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000629
630
631class Unpickler:
632
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000633 def __init__(self, file):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000634 """This takes a file-like object for reading a pickle data stream.
635
636 This class automatically determines whether the data stream was
637 written in binary mode or not, so it does not need a flag as in
638 the Pickler class factory.
639
640 The file-like object must have two methods, a read() method that
641 takes an integer argument, and a readline() method that requires no
642 arguments. Both methods should return a string. Thus file-like
643 object can be a file object opened for reading, a StringIO object,
644 or any other custom object that meets this interface.
645
646 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000647 self.readline = file.readline
648 self.read = file.read
649 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000650
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000651 def load(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000652 """Read a pickled object representation from the open file object.
653
654 Return the reconstituted object hierarchy specified in the file
655 object.
656
657 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000658 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000659 self.stack = []
660 self.append = self.stack.append
661 read = self.read
662 dispatch = self.dispatch
663 try:
664 while 1:
665 key = read(1)
666 dispatch[key](self)
Guido van Rossumff871742000-12-13 18:11:56 +0000667 except _Stop, stopinst:
668 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000669
670 def marker(self):
671 stack = self.stack
672 mark = self.mark
673 k = len(stack)-1
674 while stack[k] is not mark: k = k-1
675 return k
676
677 dispatch = {}
678
679 def load_eof(self):
680 raise EOFError
681 dispatch[''] = load_eof
682
683 def load_persid(self):
684 pid = self.readline()[:-1]
685 self.append(self.persistent_load(pid))
686 dispatch[PERSID] = load_persid
687
688 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000689 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000690 self.append(self.persistent_load(pid))
691 dispatch[BINPERSID] = load_binpersid
692
693 def load_none(self):
694 self.append(None)
695 dispatch[NONE] = load_none
696
697 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000698 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000699 if data == FALSE[1:]:
700 val = False
701 elif data == TRUE[1:]:
702 val = True
703 else:
704 try:
705 val = int(data)
706 except ValueError:
707 val = long(data)
708 self.append(val)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000709 dispatch[INT] = load_int
710
711 def load_binint(self):
712 self.append(mloads('i' + self.read(4)))
713 dispatch[BININT] = load_binint
714
715 def load_binint1(self):
716 self.append(mloads('i' + self.read(1) + '\000\000\000'))
717 dispatch[BININT1] = load_binint1
718
719 def load_binint2(self):
720 self.append(mloads('i' + self.read(2) + '\000\000'))
721 dispatch[BININT2] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000722
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000723 def load_long(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000724 self.append(long(self.readline()[:-1], 0))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000725 dispatch[LONG] = load_long
726
727 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000728 self.append(float(self.readline()[:-1]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000729 dispatch[FLOAT] = load_float
730
Guido van Rossumd3703791998-10-22 20:15:36 +0000731 def load_binfloat(self, unpack=struct.unpack):
732 self.append(unpack('>d', self.read(8))[0])
733 dispatch[BINFLOAT] = load_binfloat
734
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000735 def load_string(self):
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000736 rep = self.readline()[:-1]
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000737 for q in _quotes:
738 if rep.startswith(q):
739 if not rep.endswith(q):
740 raise ValueError, "insecure string pickle"
741 rep = rep[len(q):-len(q)]
742 break
743 else:
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000744 raise ValueError, "insecure string pickle"
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000745 self.append(rep.decode("string-escape"))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000746 dispatch[STRING] = load_string
747
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000748 def _is_string_secure(self, s):
749 """Return true if s contains a string that is safe to eval
750
751 The definition of secure string is based on the implementation
752 in cPickle. s is secure as long as it only contains a quoted
753 string and optional trailing whitespace.
754 """
755 q = s[0]
756 if q not in ("'", '"'):
757 return 0
758 # find the closing quote
759 offset = 1
760 i = None
761 while 1:
762 try:
763 i = s.index(q, offset)
764 except ValueError:
765 # if there is an error the first time, there is no
766 # close quote
767 if offset == 1:
768 return 0
769 if s[i-1] != '\\':
770 break
771 # check to see if this one is escaped
772 nslash = 0
773 j = i - 1
774 while j >= offset and s[j] == '\\':
775 j = j - 1
776 nslash = nslash + 1
777 if nslash % 2 == 0:
778 break
779 offset = i + 1
780 for c in s[i+1:]:
781 if ord(c) > 32:
782 return 0
783 return 1
784
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000785 def load_binstring(self):
786 len = mloads('i' + self.read(4))
787 self.append(self.read(len))
788 dispatch[BINSTRING] = load_binstring
789
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000790 def load_unicode(self):
791 self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
792 dispatch[UNICODE] = load_unicode
793
794 def load_binunicode(self):
795 len = mloads('i' + self.read(4))
796 self.append(unicode(self.read(len),'utf-8'))
797 dispatch[BINUNICODE] = load_binunicode
798
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000799 def load_short_binstring(self):
800 len = mloads('i' + self.read(1) + '\000\000\000')
801 self.append(self.read(len))
802 dispatch[SHORT_BINSTRING] = load_short_binstring
803
804 def load_tuple(self):
805 k = self.marker()
806 self.stack[k:] = [tuple(self.stack[k+1:])]
807 dispatch[TUPLE] = load_tuple
808
809 def load_empty_tuple(self):
810 self.stack.append(())
811 dispatch[EMPTY_TUPLE] = load_empty_tuple
812
813 def load_empty_list(self):
814 self.stack.append([])
815 dispatch[EMPTY_LIST] = load_empty_list
816
817 def load_empty_dictionary(self):
818 self.stack.append({})
819 dispatch[EMPTY_DICT] = load_empty_dictionary
820
821 def load_list(self):
822 k = self.marker()
823 self.stack[k:] = [self.stack[k+1:]]
824 dispatch[LIST] = load_list
825
826 def load_dict(self):
827 k = self.marker()
828 d = {}
829 items = self.stack[k+1:]
830 for i in range(0, len(items), 2):
831 key = items[i]
832 value = items[i+1]
833 d[key] = value
834 self.stack[k:] = [d]
835 dispatch[DICT] = load_dict
836
837 def load_inst(self):
838 k = self.marker()
839 args = tuple(self.stack[k+1:])
840 del self.stack[k:]
841 module = self.readline()[:-1]
842 name = self.readline()[:-1]
843 klass = self.find_class(module, name)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000844 instantiated = 0
845 if (not args and type(klass) is ClassType and
846 not hasattr(klass, "__getinitargs__")):
847 try:
848 value = _EmptyClass()
849 value.__class__ = klass
Guido van Rossumb19e2a31998-04-13 18:08:45 +0000850 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000851 except RuntimeError:
852 # In restricted execution, assignment to inst.__class__ is
853 # prohibited
854 pass
855 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +0000856 try:
Barry Warsawbf4d9592001-11-15 23:42:58 +0000857 if not hasattr(klass, '__safe_for_unpickling__'):
858 raise UnpicklingError('%s is not safe for unpickling' %
859 klass)
Guido van Rossum743d17e1998-09-15 20:25:57 +0000860 value = apply(klass, args)
861 except TypeError, err:
862 raise TypeError, "in constructor for %s: %s" % (
863 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000864 self.append(value)
865 dispatch[INST] = load_inst
866
867 def load_obj(self):
868 stack = self.stack
869 k = self.marker()
870 klass = stack[k + 1]
871 del stack[k + 1]
Tim Peters2344fae2001-01-15 00:50:52 +0000872 args = tuple(stack[k + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000873 del stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000874 instantiated = 0
875 if (not args and type(klass) is ClassType and
876 not hasattr(klass, "__getinitargs__")):
877 try:
878 value = _EmptyClass()
879 value.__class__ = klass
880 instantiated = 1
881 except RuntimeError:
882 # In restricted execution, assignment to inst.__class__ is
883 # prohibited
884 pass
885 if not instantiated:
886 value = apply(klass, args)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000887 self.append(value)
Tim Peters2344fae2001-01-15 00:50:52 +0000888 dispatch[OBJ] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000889
890 def load_global(self):
891 module = self.readline()[:-1]
892 name = self.readline()[:-1]
893 klass = self.find_class(module, name)
894 self.append(klass)
895 dispatch[GLOBAL] = load_global
896
897 def find_class(self, module, name):
Barry Warsawbf4d9592001-11-15 23:42:58 +0000898 __import__(module)
899 mod = sys.modules[module]
900 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000901 return klass
902
903 def load_reduce(self):
904 stack = self.stack
905
906 callable = stack[-2]
907 arg_tup = stack[-1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000908 del stack[-2:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000909
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000910 if type(callable) is not ClassType:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000911 if not callable in safe_constructors:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000912 try:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000913 safe = callable.__safe_for_unpickling__
914 except AttributeError:
915 safe = None
Guido van Rossuma48061a1995-01-10 00:31:14 +0000916
Tim Petersc32d8242001-04-10 02:48:53 +0000917 if not safe:
Tim Peters2344fae2001-01-15 00:50:52 +0000918 raise UnpicklingError, "%s is not safe for " \
919 "unpickling" % callable
Guido van Rossuma48061a1995-01-10 00:31:14 +0000920
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000921 if arg_tup is None:
Raymond Hettinger97394bc2002-05-21 17:22:02 +0000922 import warnings
923 warnings.warn("The None return argument form of __reduce__ is "
924 "deprecated. Return a tuple of arguments instead.",
Tim Peters8ac14952002-05-23 15:15:30 +0000925 DeprecationWarning)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000926 value = callable.__basicnew__()
927 else:
928 value = apply(callable, arg_tup)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000929 self.append(value)
930 dispatch[REDUCE] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +0000931
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000932 def load_pop(self):
933 del self.stack[-1]
934 dispatch[POP] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +0000935
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000936 def load_pop_mark(self):
937 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000938 del self.stack[k:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000939 dispatch[POP_MARK] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +0000940
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000941 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +0000942 self.append(self.stack[-1])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000943 dispatch[DUP] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +0000944
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000945 def load_get(self):
946 self.append(self.memo[self.readline()[:-1]])
947 dispatch[GET] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +0000948
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000949 def load_binget(self):
950 i = mloads('i' + self.read(1) + '\000\000\000')
951 self.append(self.memo[`i`])
952 dispatch[BINGET] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +0000953
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000954 def load_long_binget(self):
955 i = mloads('i' + self.read(4))
956 self.append(self.memo[`i`])
957 dispatch[LONG_BINGET] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +0000958
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000959 def load_put(self):
960 self.memo[self.readline()[:-1]] = self.stack[-1]
961 dispatch[PUT] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +0000962
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000963 def load_binput(self):
964 i = mloads('i' + self.read(1) + '\000\000\000')
965 self.memo[`i`] = self.stack[-1]
966 dispatch[BINPUT] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +0000967
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000968 def load_long_binput(self):
969 i = mloads('i' + self.read(4))
970 self.memo[`i`] = self.stack[-1]
971 dispatch[LONG_BINPUT] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +0000972
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000973 def load_append(self):
974 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000975 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000976 list = stack[-1]
977 list.append(value)
978 dispatch[APPEND] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +0000979
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000980 def load_appends(self):
981 stack = self.stack
982 mark = self.marker()
983 list = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000984 for i in range(mark + 1, len(stack)):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000985 list.append(stack[i])
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000986
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000987 del stack[mark:]
988 dispatch[APPENDS] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +0000989
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000990 def load_setitem(self):
991 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000992 value = stack.pop()
993 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000994 dict = stack[-1]
995 dict[key] = value
996 dispatch[SETITEM] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000997
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000998 def load_setitems(self):
999 stack = self.stack
1000 mark = self.marker()
1001 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001002 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001003 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001004
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001005 del stack[mark:]
1006 dispatch[SETITEMS] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001007
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001008 def load_build(self):
1009 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001010 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001011 inst = stack[-1]
1012 try:
1013 setstate = inst.__setstate__
1014 except AttributeError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001015 try:
1016 inst.__dict__.update(value)
1017 except RuntimeError:
1018 # XXX In restricted execution, the instance's __dict__ is not
1019 # accessible. Use the old way of unpickling the instance
1020 # variables. This is a semantic different when unpickling in
1021 # restricted vs. unrestricted modes.
1022 for k, v in value.items():
1023 setattr(inst, k, v)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001024 else:
1025 setstate(value)
1026 dispatch[BUILD] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001027
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001028 def load_mark(self):
1029 self.append(self.mark)
1030 dispatch[MARK] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001031
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001032 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001033 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001034 raise _Stop(value)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001035 dispatch[STOP] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001036
Guido van Rossume467be61997-12-05 19:42:42 +00001037# Helper class for load_inst/load_obj
1038
1039class _EmptyClass:
1040 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001041
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001042# Shorthands
1043
Jeremy Hyltonabe2c622001-10-15 21:29:28 +00001044try:
1045 from cStringIO import StringIO
1046except ImportError:
1047 from StringIO import StringIO
Guido van Rossumc7c5e691996-07-22 22:26:07 +00001048
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001049def dump(object, file, bin = 0):
1050 Pickler(file, bin).dump(object)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001051
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001052def dumps(object, bin = 0):
1053 file = StringIO()
1054 Pickler(file, bin).dump(object)
1055 return file.getvalue()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001056
1057def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001058 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001059
1060def loads(str):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001061 file = StringIO(str)
1062 return Unpickler(file).load()