blob: f29df510a27d1defd3099fbb21d9dbd43caed5a9 [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
Guido van Rossuma48061a1995-01-10 00:31:14 +0000129class Pickler:
130
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000131 def __init__(self, file, bin = 0):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000132 """This takes a file-like object for writing a pickle data stream.
133
134 The optional bin parameter if true, tells the pickler to use the more
135 efficient binary pickle format, otherwise the ASCII format is used
136 (this is the default).
137
138 The file parameter must have a write() method that accepts a single
139 string argument. It can thus be an open file object, a StringIO
140 object, or any other custom object that meets this interface.
141
142 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000143 self.write = file.write
144 self.memo = {}
145 self.bin = bin
Guido van Rossuma48061a1995-01-10 00:31:14 +0000146
Fred Drake7f781c92002-05-01 20:33:53 +0000147 def clear_memo(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000148 """Clears the pickler's "memo".
149
150 The memo is the data structure that remembers which objects the
151 pickler has already seen, so that shared or recursive objects pickled
152 by reference and not by value. This method is useful when re-using
153 picklers.
154
155 """
Fred Drake7f781c92002-05-01 20:33:53 +0000156 self.memo.clear()
157
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000158 def dump(self, object):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000159 """Write a pickled representation of object to the open file object.
160
161 Either the binary or ASCII format will be used, depending on the
162 value of the bin flag passed to the constructor.
163
164 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000165 self.save(object)
166 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000167
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000168 def put(self, i):
Tim Petersc32d8242001-04-10 02:48:53 +0000169 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000170 s = mdumps(i)[1:]
Tim Petersc32d8242001-04-10 02:48:53 +0000171 if i < 256:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000172 return BINPUT + s[0]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000173
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000174 return LONG_BINPUT + s
Guido van Rossuma48061a1995-01-10 00:31:14 +0000175
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000176 return PUT + `i` + '\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000177
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000178 def get(self, i):
Tim Petersc32d8242001-04-10 02:48:53 +0000179 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000180 s = mdumps(i)[1:]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000181
Tim Petersc32d8242001-04-10 02:48:53 +0000182 if i < 256:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000183 return BINGET + s[0]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000184
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000185 return LONG_BINGET + s
Guido van Rossuma48061a1995-01-10 00:31:14 +0000186
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000187 return GET + `i` + '\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000188
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000189 def save(self, object, pers_save = 0):
190 memo = self.memo
Guido van Rossuma48061a1995-01-10 00:31:14 +0000191
Tim Petersc32d8242001-04-10 02:48:53 +0000192 if not pers_save:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000193 pid = self.persistent_id(object)
Tim Petersc32d8242001-04-10 02:48:53 +0000194 if pid is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000195 self.save_pers(pid)
196 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000197
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000198 d = id(object)
Tim Peters2344fae2001-01-15 00:50:52 +0000199
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000200 t = type(object)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000201
Tim Petersc32d8242001-04-10 02:48:53 +0000202 if (t is TupleType) and (len(object) == 0):
203 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000204 self.save_empty_tuple(object)
205 else:
206 self.save_tuple(object)
207 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000208
Raymond Hettinger54f02222002-06-01 14:18:47 +0000209 if d in memo:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000210 self.write(self.get(memo[d][0]))
211 return
212
213 try:
214 f = self.dispatch[t]
215 except KeyError:
Guido van Rossum85ee4912002-03-26 00:51:56 +0000216 try:
217 issc = issubclass(t, TypeType)
218 except TypeError: # t is not a class
219 issc = 0
220 if issc:
Guido van Rossumf048a8f2001-12-19 16:55:02 +0000221 self.save_global(object)
222 return
223
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000224 pid = self.inst_persistent_id(object)
225 if pid is not None:
226 self.save_pers(pid)
227 return
228
229 try:
230 reduce = dispatch_table[t]
231 except KeyError:
232 try:
233 reduce = object.__reduce__
234 except AttributeError:
235 raise PicklingError, \
Guido van Rossum08a92cb1999-10-10 21:14:25 +0000236 "can't pickle %s object: %s" % (`t.__name__`,
237 `object`)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000238 else:
239 tup = reduce()
240 else:
241 tup = reduce(object)
242
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000243 if type(tup) is StringType:
244 self.save_global(object, tup)
245 return
Guido van Rossumd1f49841997-12-10 23:40:18 +0000246
Tim Petersc32d8242001-04-10 02:48:53 +0000247 if type(tup) is not TupleType:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000248 raise PicklingError, "Value returned by %s must be a " \
249 "tuple" % reduce
250
251 l = len(tup)
Tim Peters2344fae2001-01-15 00:50:52 +0000252
Tim Petersc32d8242001-04-10 02:48:53 +0000253 if (l != 2) and (l != 3):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000254 raise PicklingError, "tuple returned by %s must contain " \
255 "only two or three elements" % reduce
256
257 callable = tup[0]
258 arg_tup = tup[1]
Tim Peters2344fae2001-01-15 00:50:52 +0000259
Tim Petersc32d8242001-04-10 02:48:53 +0000260 if l > 2:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000261 state = tup[2]
262 else:
263 state = None
264
Guido van Rossumd1f49841997-12-10 23:40:18 +0000265 if type(arg_tup) is not TupleType and arg_tup is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000266 raise PicklingError, "Second element of tuple returned " \
267 "by %s must be a tuple" % reduce
268
Tim Peters2344fae2001-01-15 00:50:52 +0000269 self.save_reduce(callable, arg_tup, state)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000270 memo_len = len(memo)
271 self.write(self.put(memo_len))
272 memo[d] = (memo_len, object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000273 return
274
275 f(self, object)
276
277 def persistent_id(self, object):
278 return None
279
280 def inst_persistent_id(self, object):
281 return None
282
283 def save_pers(self, pid):
Tim Petersc32d8242001-04-10 02:48:53 +0000284 if not self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000285 self.write(PERSID + str(pid) + '\n')
286 else:
287 self.save(pid, 1)
288 self.write(BINPERSID)
289
290 def save_reduce(self, callable, arg_tup, state = None):
291 write = self.write
292 save = self.save
293
294 save(callable)
295 save(arg_tup)
296 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000297
Tim Petersc32d8242001-04-10 02:48:53 +0000298 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000299 save(state)
300 write(BUILD)
301
302 dispatch = {}
303
304 def save_none(self, object):
305 self.write(NONE)
306 dispatch[NoneType] = save_none
307
Guido van Rossum77f6a652002-04-03 22:41:51 +0000308 def save_bool(self, object):
309 if object:
310 self.write(TRUE)
311 else:
312 self.write(FALSE)
313 dispatch[bool] = save_bool
314
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000315 def save_int(self, object):
Tim Petersc32d8242001-04-10 02:48:53 +0000316 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000317 # If the int is small enough to fit in a signed 4-byte 2's-comp
318 # format, we can store it more efficiently than the general
319 # case.
320 high_bits = object >> 31 # note that Python shift sign-extends
321 if high_bits == 0 or high_bits == -1:
322 # All high bits are copies of bit 2**31, so the value
323 # fits in a 4-byte signed int.
324 i = mdumps(object)[1:]
325 assert len(i) == 4
326 if i[-2:] == '\000\000': # fits in 2-byte unsigned int
327 if i[-3] == '\000': # fits in 1-byte unsigned int
328 self.write(BININT1 + i[0])
329 else:
330 self.write(BININT2 + i[:2])
331 else:
332 self.write(BININT + i)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000333 return
Tim Peters44714002001-04-10 05:02:52 +0000334 # Text pickle, or int too big to fit in signed 4-byte format.
335 self.write(INT + `object` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000336 dispatch[IntType] = save_int
337
338 def save_long(self, object):
339 self.write(LONG + `object` + '\n')
340 dispatch[LongType] = save_long
341
Guido van Rossumd3703791998-10-22 20:15:36 +0000342 def save_float(self, object, pack=struct.pack):
343 if self.bin:
344 self.write(BINFLOAT + pack('>d', object))
345 else:
346 self.write(FLOAT + `object` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000347 dispatch[FloatType] = save_float
348
349 def save_string(self, object):
350 d = id(object)
351 memo = self.memo
352
Tim Petersc32d8242001-04-10 02:48:53 +0000353 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000354 l = len(object)
355 s = mdumps(l)[1:]
Tim Petersc32d8242001-04-10 02:48:53 +0000356 if l < 256:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000357 self.write(SHORT_BINSTRING + s[0] + object)
358 else:
359 self.write(BINSTRING + s + object)
360 else:
361 self.write(STRING + `object` + '\n')
362
363 memo_len = len(memo)
364 self.write(self.put(memo_len))
365 memo[d] = (memo_len, object)
366 dispatch[StringType] = save_string
367
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000368 def save_unicode(self, object):
369 d = id(object)
370 memo = self.memo
371
Tim Petersc32d8242001-04-10 02:48:53 +0000372 if self.bin:
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000373 encoding = object.encode('utf-8')
374 l = len(encoding)
375 s = mdumps(l)[1:]
376 self.write(BINUNICODE + s + encoding)
377 else:
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000378 object = object.replace("\\", "\\u005c")
379 object = object.replace("\n", "\\u000a")
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000380 self.write(UNICODE + object.encode('raw-unicode-escape') + '\n')
381
382 memo_len = len(memo)
383 self.write(self.put(memo_len))
384 memo[d] = (memo_len, object)
385 dispatch[UnicodeType] = save_unicode
386
Guido van Rossum31584cb2001-01-22 14:53:29 +0000387 if StringType == UnicodeType:
388 # This is true for Jython
389 def save_string(self, object):
390 d = id(object)
391 memo = self.memo
392 unicode = object.isunicode()
393
Tim Petersc32d8242001-04-10 02:48:53 +0000394 if self.bin:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000395 if unicode:
396 object = object.encode("utf-8")
397 l = len(object)
398 s = mdumps(l)[1:]
Tim Petersc32d8242001-04-10 02:48:53 +0000399 if l < 256 and not unicode:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000400 self.write(SHORT_BINSTRING + s[0] + object)
401 else:
402 if unicode:
403 self.write(BINUNICODE + s + object)
404 else:
405 self.write(BINSTRING + s + object)
406 else:
Tim Peters658cba62001-02-09 20:06:00 +0000407 if unicode:
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000408 object = object.replace("\\", "\\u005c")
409 object = object.replace("\n", "\\u000a")
Guido van Rossum31584cb2001-01-22 14:53:29 +0000410 object = object.encode('raw-unicode-escape')
411 self.write(UNICODE + object + '\n')
412 else:
413 self.write(STRING + `object` + '\n')
414
415 memo_len = len(memo)
416 self.write(self.put(memo_len))
417 memo[d] = (memo_len, object)
418 dispatch[StringType] = save_string
Tim Peters658cba62001-02-09 20:06:00 +0000419
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000420 def save_tuple(self, object):
421
422 write = self.write
423 save = self.save
424 memo = self.memo
425
426 d = id(object)
427
428 write(MARK)
429
430 for element in object:
431 save(element)
432
Raymond Hettinger54f02222002-06-01 14:18:47 +0000433 if len(object) and d in memo:
Tim Petersc32d8242001-04-10 02:48:53 +0000434 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000435 write(POP_MARK + self.get(memo[d][0]))
436 return
Tim Peters2344fae2001-01-15 00:50:52 +0000437
Guido van Rossum599174f1998-03-31 16:30:28 +0000438 write(POP * (len(object) + 1) + self.get(memo[d][0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000439 return
440
441 memo_len = len(memo)
442 self.write(TUPLE + self.put(memo_len))
443 memo[d] = (memo_len, object)
444 dispatch[TupleType] = save_tuple
445
446 def save_empty_tuple(self, object):
447 self.write(EMPTY_TUPLE)
448
449 def save_list(self, object):
450 d = id(object)
451
452 write = self.write
453 save = self.save
454 memo = self.memo
455
Tim Petersc32d8242001-04-10 02:48:53 +0000456 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000457 write(EMPTY_LIST)
458 else:
459 write(MARK + LIST)
460
461 memo_len = len(memo)
462 write(self.put(memo_len))
463 memo[d] = (memo_len, object)
464
465 using_appends = (self.bin and (len(object) > 1))
466
Tim Petersc32d8242001-04-10 02:48:53 +0000467 if using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000468 write(MARK)
469
470 for element in object:
471 save(element)
Tim Peters2344fae2001-01-15 00:50:52 +0000472
Tim Petersc32d8242001-04-10 02:48:53 +0000473 if not using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000474 write(APPEND)
475
Tim Petersc32d8242001-04-10 02:48:53 +0000476 if using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000477 write(APPENDS)
478 dispatch[ListType] = save_list
479
480 def save_dict(self, object):
481 d = id(object)
482
483 write = self.write
484 save = self.save
485 memo = self.memo
486
Tim Petersc32d8242001-04-10 02:48:53 +0000487 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000488 write(EMPTY_DICT)
489 else:
490 write(MARK + DICT)
491
492 memo_len = len(memo)
493 self.write(self.put(memo_len))
494 memo[d] = (memo_len, object)
495
496 using_setitems = (self.bin and (len(object) > 1))
497
Tim Petersc32d8242001-04-10 02:48:53 +0000498 if using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000499 write(MARK)
500
501 items = object.items()
502 for key, value in items:
503 save(key)
504 save(value)
505
Tim Petersc32d8242001-04-10 02:48:53 +0000506 if not using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000507 write(SETITEM)
508
Tim Petersc32d8242001-04-10 02:48:53 +0000509 if using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000510 write(SETITEMS)
511
512 dispatch[DictionaryType] = save_dict
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000513 if not PyStringMap is None:
514 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000515
516 def save_inst(self, object):
517 d = id(object)
518 cls = object.__class__
519
520 memo = self.memo
521 write = self.write
522 save = self.save
523
524 if hasattr(object, '__getinitargs__'):
525 args = object.__getinitargs__()
526 len(args) # XXX Assert it's a sequence
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000527 _keep_alive(args, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000528 else:
529 args = ()
530
531 write(MARK)
532
Tim Petersc32d8242001-04-10 02:48:53 +0000533 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000534 save(cls)
535
536 for arg in args:
537 save(arg)
538
539 memo_len = len(memo)
Tim Petersc32d8242001-04-10 02:48:53 +0000540 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000541 write(OBJ + self.put(memo_len))
542 else:
Guido van Rossum4fb5b281997-09-12 20:07:24 +0000543 write(INST + cls.__module__ + '\n' + cls.__name__ + '\n' +
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000544 self.put(memo_len))
545
546 memo[d] = (memo_len, object)
547
548 try:
549 getstate = object.__getstate__
550 except AttributeError:
551 stuff = object.__dict__
552 else:
553 stuff = getstate()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000554 _keep_alive(stuff, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000555 save(stuff)
556 write(BUILD)
557 dispatch[InstanceType] = save_inst
558
559 def save_global(self, object, name = None):
560 write = self.write
561 memo = self.memo
562
Tim Petersc32d8242001-04-10 02:48:53 +0000563 if name is None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000564 name = object.__name__
565
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000566 try:
567 module = object.__module__
568 except AttributeError:
569 module = whichmodule(object, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000570
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000571 try:
572 __import__(module)
573 mod = sys.modules[module]
574 klass = getattr(mod, name)
575 except (ImportError, KeyError, AttributeError):
576 raise PicklingError(
577 "Can't pickle %r: it's not found as %s.%s" %
578 (object, module, name))
579 else:
580 if klass is not object:
581 raise PicklingError(
582 "Can't pickle %r: it's not the same object as %s.%s" %
583 (object, module, name))
584
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000585 memo_len = len(memo)
586 write(GLOBAL + module + '\n' + name + '\n' +
587 self.put(memo_len))
588 memo[id(object)] = (memo_len, object)
589 dispatch[ClassType] = save_global
590 dispatch[FunctionType] = save_global
591 dispatch[BuiltinFunctionType] = save_global
Tim Peters6d6c1a32001-08-02 04:15:00 +0000592 dispatch[TypeType] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000593
Guido van Rossuma48061a1995-01-10 00:31:14 +0000594
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000595def _keep_alive(x, memo):
596 """Keeps a reference to the object x in the memo.
597
598 Because we remember objects by their id, we have
599 to assure that possibly temporary objects are kept
600 alive by referencing them.
601 We store a reference at the id of the memo, which should
602 normally not be used unless someone tries to deepcopy
603 the memo itself...
604 """
605 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000606 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000607 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000608 # aha, this is the first one :-)
609 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000610
611
Guido van Rossuma48061a1995-01-10 00:31:14 +0000612classmap = {}
613
Guido van Rossum4fb5b281997-09-12 20:07:24 +0000614# This is no longer used to find classes, but still for functions
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000615def whichmodule(cls, clsname):
616 """Figure out the module in which a class occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000617
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000618 Search sys.modules for the module.
619 Cache in classmap.
620 Return a module name.
621 If the class cannot be found, return __main__.
622 """
Raymond Hettinger54f02222002-06-01 14:18:47 +0000623 if cls in classmap:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000624 return classmap[cls]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000625
626 for name, module in sys.modules.items():
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000627 if name != '__main__' and \
628 hasattr(module, clsname) and \
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000629 getattr(module, clsname) is cls:
630 break
631 else:
632 name = '__main__'
633 classmap[cls] = name
634 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000635
636
637class Unpickler:
638
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000639 def __init__(self, file):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000640 """This takes a file-like object for reading a pickle data stream.
641
642 This class automatically determines whether the data stream was
643 written in binary mode or not, so it does not need a flag as in
644 the Pickler class factory.
645
646 The file-like object must have two methods, a read() method that
647 takes an integer argument, and a readline() method that requires no
648 arguments. Both methods should return a string. Thus file-like
649 object can be a file object opened for reading, a StringIO object,
650 or any other custom object that meets this interface.
651
652 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000653 self.readline = file.readline
654 self.read = file.read
655 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000656
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000657 def load(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000658 """Read a pickled object representation from the open file object.
659
660 Return the reconstituted object hierarchy specified in the file
661 object.
662
663 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000664 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000665 self.stack = []
666 self.append = self.stack.append
667 read = self.read
668 dispatch = self.dispatch
669 try:
670 while 1:
671 key = read(1)
672 dispatch[key](self)
Guido van Rossumff871742000-12-13 18:11:56 +0000673 except _Stop, stopinst:
674 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000675
676 def marker(self):
677 stack = self.stack
678 mark = self.mark
679 k = len(stack)-1
680 while stack[k] is not mark: k = k-1
681 return k
682
683 dispatch = {}
684
685 def load_eof(self):
686 raise EOFError
687 dispatch[''] = load_eof
688
689 def load_persid(self):
690 pid = self.readline()[:-1]
691 self.append(self.persistent_load(pid))
692 dispatch[PERSID] = load_persid
693
694 def load_binpersid(self):
695 stack = self.stack
Tim Peters2344fae2001-01-15 00:50:52 +0000696
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000697 pid = stack[-1]
698 del stack[-1]
699
700 self.append(self.persistent_load(pid))
701 dispatch[BINPERSID] = load_binpersid
702
703 def load_none(self):
704 self.append(None)
705 dispatch[NONE] = load_none
706
707 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000708 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000709 if data == FALSE[1:]:
710 val = False
711 elif data == TRUE[1:]:
712 val = True
713 else:
714 try:
715 val = int(data)
716 except ValueError:
717 val = long(data)
718 self.append(val)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000719 dispatch[INT] = load_int
720
721 def load_binint(self):
722 self.append(mloads('i' + self.read(4)))
723 dispatch[BININT] = load_binint
724
725 def load_binint1(self):
726 self.append(mloads('i' + self.read(1) + '\000\000\000'))
727 dispatch[BININT1] = load_binint1
728
729 def load_binint2(self):
730 self.append(mloads('i' + self.read(2) + '\000\000'))
731 dispatch[BININT2] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000732
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000733 def load_long(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000734 self.append(long(self.readline()[:-1], 0))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000735 dispatch[LONG] = load_long
736
737 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000738 self.append(float(self.readline()[:-1]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000739 dispatch[FLOAT] = load_float
740
Guido van Rossumd3703791998-10-22 20:15:36 +0000741 def load_binfloat(self, unpack=struct.unpack):
742 self.append(unpack('>d', self.read(8))[0])
743 dispatch[BINFLOAT] = load_binfloat
744
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000745 def load_string(self):
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000746 rep = self.readline()[:-1]
747 if not self._is_string_secure(rep):
748 raise ValueError, "insecure string pickle"
749 self.append(eval(rep,
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000750 {'__builtins__': {}})) # Let's be careful
751 dispatch[STRING] = load_string
752
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000753 def _is_string_secure(self, s):
754 """Return true if s contains a string that is safe to eval
755
756 The definition of secure string is based on the implementation
757 in cPickle. s is secure as long as it only contains a quoted
758 string and optional trailing whitespace.
759 """
760 q = s[0]
761 if q not in ("'", '"'):
762 return 0
763 # find the closing quote
764 offset = 1
765 i = None
766 while 1:
767 try:
768 i = s.index(q, offset)
769 except ValueError:
770 # if there is an error the first time, there is no
771 # close quote
772 if offset == 1:
773 return 0
774 if s[i-1] != '\\':
775 break
776 # check to see if this one is escaped
777 nslash = 0
778 j = i - 1
779 while j >= offset and s[j] == '\\':
780 j = j - 1
781 nslash = nslash + 1
782 if nslash % 2 == 0:
783 break
784 offset = i + 1
785 for c in s[i+1:]:
786 if ord(c) > 32:
787 return 0
788 return 1
789
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000790 def load_binstring(self):
791 len = mloads('i' + self.read(4))
792 self.append(self.read(len))
793 dispatch[BINSTRING] = load_binstring
794
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000795 def load_unicode(self):
796 self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
797 dispatch[UNICODE] = load_unicode
798
799 def load_binunicode(self):
800 len = mloads('i' + self.read(4))
801 self.append(unicode(self.read(len),'utf-8'))
802 dispatch[BINUNICODE] = load_binunicode
803
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000804 def load_short_binstring(self):
805 len = mloads('i' + self.read(1) + '\000\000\000')
806 self.append(self.read(len))
807 dispatch[SHORT_BINSTRING] = load_short_binstring
808
809 def load_tuple(self):
810 k = self.marker()
811 self.stack[k:] = [tuple(self.stack[k+1:])]
812 dispatch[TUPLE] = load_tuple
813
814 def load_empty_tuple(self):
815 self.stack.append(())
816 dispatch[EMPTY_TUPLE] = load_empty_tuple
817
818 def load_empty_list(self):
819 self.stack.append([])
820 dispatch[EMPTY_LIST] = load_empty_list
821
822 def load_empty_dictionary(self):
823 self.stack.append({})
824 dispatch[EMPTY_DICT] = load_empty_dictionary
825
826 def load_list(self):
827 k = self.marker()
828 self.stack[k:] = [self.stack[k+1:]]
829 dispatch[LIST] = load_list
830
831 def load_dict(self):
832 k = self.marker()
833 d = {}
834 items = self.stack[k+1:]
835 for i in range(0, len(items), 2):
836 key = items[i]
837 value = items[i+1]
838 d[key] = value
839 self.stack[k:] = [d]
840 dispatch[DICT] = load_dict
841
842 def load_inst(self):
843 k = self.marker()
844 args = tuple(self.stack[k+1:])
845 del self.stack[k:]
846 module = self.readline()[:-1]
847 name = self.readline()[:-1]
848 klass = self.find_class(module, name)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000849 instantiated = 0
850 if (not args and type(klass) is ClassType and
851 not hasattr(klass, "__getinitargs__")):
852 try:
853 value = _EmptyClass()
854 value.__class__ = klass
Guido van Rossumb19e2a31998-04-13 18:08:45 +0000855 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000856 except RuntimeError:
857 # In restricted execution, assignment to inst.__class__ is
858 # prohibited
859 pass
860 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +0000861 try:
Barry Warsawbf4d9592001-11-15 23:42:58 +0000862 if not hasattr(klass, '__safe_for_unpickling__'):
863 raise UnpicklingError('%s is not safe for unpickling' %
864 klass)
Guido van Rossum743d17e1998-09-15 20:25:57 +0000865 value = apply(klass, args)
866 except TypeError, err:
867 raise TypeError, "in constructor for %s: %s" % (
868 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000869 self.append(value)
870 dispatch[INST] = load_inst
871
872 def load_obj(self):
873 stack = self.stack
874 k = self.marker()
875 klass = stack[k + 1]
876 del stack[k + 1]
Tim Peters2344fae2001-01-15 00:50:52 +0000877 args = tuple(stack[k + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000878 del stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000879 instantiated = 0
880 if (not args and type(klass) is ClassType and
881 not hasattr(klass, "__getinitargs__")):
882 try:
883 value = _EmptyClass()
884 value.__class__ = klass
885 instantiated = 1
886 except RuntimeError:
887 # In restricted execution, assignment to inst.__class__ is
888 # prohibited
889 pass
890 if not instantiated:
891 value = apply(klass, args)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000892 self.append(value)
Tim Peters2344fae2001-01-15 00:50:52 +0000893 dispatch[OBJ] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000894
895 def load_global(self):
896 module = self.readline()[:-1]
897 name = self.readline()[:-1]
898 klass = self.find_class(module, name)
899 self.append(klass)
900 dispatch[GLOBAL] = load_global
901
902 def find_class(self, module, name):
Barry Warsawbf4d9592001-11-15 23:42:58 +0000903 __import__(module)
904 mod = sys.modules[module]
905 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000906 return klass
907
908 def load_reduce(self):
909 stack = self.stack
910
911 callable = stack[-2]
912 arg_tup = stack[-1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000913 del stack[-2:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000914
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000915 if type(callable) is not ClassType:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000916 if not callable in safe_constructors:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000917 try:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000918 safe = callable.__safe_for_unpickling__
919 except AttributeError:
920 safe = None
Guido van Rossuma48061a1995-01-10 00:31:14 +0000921
Tim Petersc32d8242001-04-10 02:48:53 +0000922 if not safe:
Tim Peters2344fae2001-01-15 00:50:52 +0000923 raise UnpicklingError, "%s is not safe for " \
924 "unpickling" % callable
Guido van Rossuma48061a1995-01-10 00:31:14 +0000925
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000926 if arg_tup is None:
Raymond Hettinger97394bc2002-05-21 17:22:02 +0000927 import warnings
928 warnings.warn("The None return argument form of __reduce__ is "
929 "deprecated. Return a tuple of arguments instead.",
Tim Peters8ac14952002-05-23 15:15:30 +0000930 DeprecationWarning)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000931 value = callable.__basicnew__()
932 else:
933 value = apply(callable, arg_tup)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000934 self.append(value)
935 dispatch[REDUCE] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +0000936
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000937 def load_pop(self):
938 del self.stack[-1]
939 dispatch[POP] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +0000940
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000941 def load_pop_mark(self):
942 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000943 del self.stack[k:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000944 dispatch[POP_MARK] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +0000945
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000946 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +0000947 self.append(self.stack[-1])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000948 dispatch[DUP] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +0000949
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000950 def load_get(self):
951 self.append(self.memo[self.readline()[:-1]])
952 dispatch[GET] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +0000953
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000954 def load_binget(self):
955 i = mloads('i' + self.read(1) + '\000\000\000')
956 self.append(self.memo[`i`])
957 dispatch[BINGET] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +0000958
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000959 def load_long_binget(self):
960 i = mloads('i' + self.read(4))
961 self.append(self.memo[`i`])
962 dispatch[LONG_BINGET] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +0000963
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000964 def load_put(self):
965 self.memo[self.readline()[:-1]] = self.stack[-1]
966 dispatch[PUT] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +0000967
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000968 def load_binput(self):
969 i = mloads('i' + self.read(1) + '\000\000\000')
970 self.memo[`i`] = self.stack[-1]
971 dispatch[BINPUT] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +0000972
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000973 def load_long_binput(self):
974 i = mloads('i' + self.read(4))
975 self.memo[`i`] = self.stack[-1]
976 dispatch[LONG_BINPUT] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +0000977
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000978 def load_append(self):
979 stack = self.stack
980 value = stack[-1]
981 del stack[-1]
982 list = stack[-1]
983 list.append(value)
984 dispatch[APPEND] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +0000985
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000986 def load_appends(self):
987 stack = self.stack
988 mark = self.marker()
989 list = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000990 for i in range(mark + 1, len(stack)):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000991 list.append(stack[i])
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000992
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000993 del stack[mark:]
994 dispatch[APPENDS] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +0000995
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000996 def load_setitem(self):
997 stack = self.stack
998 value = stack[-1]
999 key = stack[-2]
1000 del stack[-2:]
1001 dict = stack[-1]
1002 dict[key] = value
1003 dispatch[SETITEM] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001004
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001005 def load_setitems(self):
1006 stack = self.stack
1007 mark = self.marker()
1008 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001009 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001010 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001011
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001012 del stack[mark:]
1013 dispatch[SETITEMS] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001014
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001015 def load_build(self):
1016 stack = self.stack
1017 value = stack[-1]
1018 del stack[-1]
1019 inst = stack[-1]
1020 try:
1021 setstate = inst.__setstate__
1022 except AttributeError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001023 try:
1024 inst.__dict__.update(value)
1025 except RuntimeError:
1026 # XXX In restricted execution, the instance's __dict__ is not
1027 # accessible. Use the old way of unpickling the instance
1028 # variables. This is a semantic different when unpickling in
1029 # restricted vs. unrestricted modes.
1030 for k, v in value.items():
1031 setattr(inst, k, v)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001032 else:
1033 setstate(value)
1034 dispatch[BUILD] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001035
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001036 def load_mark(self):
1037 self.append(self.mark)
1038 dispatch[MARK] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001039
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001040 def load_stop(self):
1041 value = self.stack[-1]
1042 del self.stack[-1]
Guido van Rossumff871742000-12-13 18:11:56 +00001043 raise _Stop(value)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001044 dispatch[STOP] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001045
Guido van Rossume467be61997-12-05 19:42:42 +00001046# Helper class for load_inst/load_obj
1047
1048class _EmptyClass:
1049 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001050
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001051# Shorthands
1052
Jeremy Hyltonabe2c622001-10-15 21:29:28 +00001053try:
1054 from cStringIO import StringIO
1055except ImportError:
1056 from StringIO import StringIO
Guido van Rossumc7c5e691996-07-22 22:26:07 +00001057
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001058def dump(object, file, bin = 0):
1059 Pickler(file, bin).dump(object)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001060
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001061def dumps(object, bin = 0):
1062 file = StringIO()
1063 Pickler(file, bin).dump(object)
1064 return file.getvalue()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001065
1066def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001067 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001068
1069def loads(str):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001070 file = StringIO(str)
1071 return Unpickler(file).load()