blob: bb739c31129f791e405a64f302b029ce17082313 [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.
Tim Peters22a449a2003-01-27 20:16:36 +00005See module pickletools source for extensive comments.
Guido van Rossuma48061a1995-01-10 00:31:14 +00006
Guido van Rossume467be61997-12-05 19:42:42 +00007Classes:
Guido van Rossuma48061a1995-01-10 00:31:14 +00008
Guido van Rossume467be61997-12-05 19:42:42 +00009 Pickler
10 Unpickler
Guido van Rossuma48061a1995-01-10 00:31:14 +000011
Guido van Rossume467be61997-12-05 19:42:42 +000012Functions:
Guido van Rossuma48061a1995-01-10 00:31:14 +000013
Guido van Rossume467be61997-12-05 19:42:42 +000014 dump(object, file)
15 dumps(object) -> string
16 load(file) -> object
17 loads(string) -> object
Guido van Rossuma48061a1995-01-10 00:31:14 +000018
Guido van Rossume467be61997-12-05 19:42:42 +000019Misc variables:
Guido van Rossuma48061a1995-01-10 00:31:14 +000020
Fred Drakefe82acc1998-02-13 03:24:48 +000021 __version__
Guido van Rossume467be61997-12-05 19:42:42 +000022 format_version
23 compatible_formats
Guido van Rossuma48061a1995-01-10 00:31:14 +000024
Guido van Rossuma48061a1995-01-10 00:31:14 +000025"""
26
Guido van Rossum743d17e1998-09-15 20:25:57 +000027__version__ = "$Revision$" # Code version
Guido van Rossuma48061a1995-01-10 00:31:14 +000028
29from types import *
Guido van Rossum4fb5b281997-09-12 20:07:24 +000030from copy_reg import dispatch_table, safe_constructors
Guido van Rossumd3703791998-10-22 20:15:36 +000031import marshal
32import sys
33import struct
Skip Montanaro23bafc62001-02-18 03:10:09 +000034import re
Guido van Rossuma48061a1995-01-10 00:31:14 +000035
Skip Montanaro352674d2001-02-07 23:14:30 +000036__all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler",
37 "Unpickler", "dump", "dumps", "load", "loads"]
38
Guido van Rossumd3703791998-10-22 20:15:36 +000039format_version = "1.3" # File format version we write
40compatible_formats = ["1.0", "1.1", "1.2"] # Old format versions we can read
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000041
42mdumps = marshal.dumps
43mloads = marshal.loads
Guido van Rossum0c891ce1995-03-14 15:09:05 +000044
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000045class PickleError(Exception):
Neal Norwitzefbb67b2002-05-30 12:12:04 +000046 """A common base class for the other pickling exceptions."""
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000047 pass
48
49class PicklingError(PickleError):
50 """This exception is raised when an unpicklable object is passed to the
51 dump() method.
52
53 """
54 pass
55
56class UnpicklingError(PickleError):
57 """This exception is raised when there is a problem unpickling an object,
58 such as a security violation.
59
60 Note that other exceptions may also be raised during unpickling, including
61 (but not necessarily limited to) AttributeError, EOFError, ImportError,
62 and IndexError.
63
64 """
65 pass
Guido van Rossum7849da81995-03-09 14:08:35 +000066
Guido van Rossumff871742000-12-13 18:11:56 +000067class _Stop(Exception):
68 def __init__(self, value):
69 self.value = value
70
Jeremy Hylton2b9d0291998-05-27 22:38:22 +000071try:
72 from org.python.core import PyStringMap
73except ImportError:
74 PyStringMap = None
75
Guido van Rossumdbb718f2001-09-21 19:22:34 +000076try:
77 UnicodeType
78except NameError:
79 UnicodeType = None
80
Tim Peters22a449a2003-01-27 20:16:36 +000081# Pickle opcodes. See pickletools.py for extensive docs. The listing
82# here is in kind-of alphabetical order of 1-character pickle code.
83# pickletools groups them by purpose.
Guido van Rossumdbb718f2001-09-21 19:22:34 +000084
Tim Peters22a449a2003-01-27 20:16:36 +000085MARK = '(' # push special markobject on stack
86STOP = '.' # every pickle ends with STOP
87POP = '0' # discard topmost stack item
88POP_MARK = '1' # discard stack top through topmost markobject
89DUP = '2' # duplicate top stack item
90FLOAT = 'F' # push float object; decimal string argument
91INT = 'I' # push integer or bool; decimal string argument
92BININT = 'J' # push four-byte signed int
93BININT1 = 'K' # push 1-byte unsigned int
94LONG = 'L' # push long; decimal string argument
95BININT2 = 'M' # push 2-byte unsigned int
96NONE = 'N' # push None
97PERSID = 'P' # push persistent object; id is taken from string arg
98BINPERSID = 'Q' # " " " ; " " " " stack
99REDUCE = 'R' # apply callable to argtuple, both on stack
100STRING = 'S' # push string; NL-terminated string argument
101BINSTRING = 'T' # push string; counted binary string argument
102SHORT_BINSTRING = 'U' # " " ; " " " " < 256 bytes
103UNICODE = 'V' # push Unicode string; raw-unicode-escaped'd argument
104BINUNICODE = 'X' # " " " ; counted UTF-8 string argument
105APPEND = 'a' # append stack top to list below it
106BUILD = 'b' # call __setstate__ or __dict__.update()
107GLOBAL = 'c' # push self.find_class(modname, name); 2 string args
108DICT = 'd' # build a dict from stack items
109EMPTY_DICT = '}' # push empty dict
110APPENDS = 'e' # extend list on stack by topmost stack slice
111GET = 'g' # push item from memo on stack; index is string arg
112BINGET = 'h' # " " " " " " ; " " 1-byte arg
113INST = 'i' # build & push class instance
114LONG_BINGET = 'j' # push item from memo on stack; index is 4-byte arg
115LIST = 'l' # build list from topmost stack items
116EMPTY_LIST = ']' # push empty list
117OBJ = 'o' # build & push class instance
118PUT = 'p' # store stack top in memo; index is string arg
119BINPUT = 'q' # " " " " " ; " " 1-byte arg
120LONG_BINPUT = 'r' # " " " " " ; " " 4-byte arg
121SETITEM = 's' # add key+value pair to dict
122TUPLE = 't' # build tuple from topmost stack items
123EMPTY_TUPLE = ')' # push empty tuple
124SETITEMS = 'u' # modify dict by adding topmost key+value pairs
125BINFLOAT = 'G' # push float; arg is 8-byte float encoding
126
127TRUE = 'I01\n' # not an opcode; see INT docs in pickletools.py
128FALSE = 'I00\n' # not an opcode; see INT docs in pickletools.py
Guido van Rossum77f6a652002-04-03 22:41:51 +0000129
Guido van Rossuma48061a1995-01-10 00:31:14 +0000130
Skip Montanaro23bafc62001-02-18 03:10:09 +0000131__all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
Neal Norwitzd5ba4ae2002-02-11 18:12:06 +0000132del x
Skip Montanaro23bafc62001-02-18 03:10:09 +0000133
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000134_quotes = ["'", '"']
135
Guido van Rossuma48061a1995-01-10 00:31:14 +0000136class Pickler:
137
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000138 def __init__(self, file, bin = 0):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000139 """This takes a file-like object for writing a pickle data stream.
140
141 The optional bin parameter if true, tells the pickler to use the more
142 efficient binary pickle format, otherwise the ASCII format is used
143 (this is the default).
144
145 The file parameter must have a write() method that accepts a single
146 string argument. It can thus be an open file object, a StringIO
147 object, or any other custom object that meets this interface.
148
149 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000150 self.write = file.write
151 self.memo = {}
152 self.bin = bin
Guido van Rossuma48061a1995-01-10 00:31:14 +0000153
Fred Drake7f781c92002-05-01 20:33:53 +0000154 def clear_memo(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000155 """Clears the pickler's "memo".
156
157 The memo is the data structure that remembers which objects the
158 pickler has already seen, so that shared or recursive objects pickled
159 by reference and not by value. This method is useful when re-using
160 picklers.
161
162 """
Fred Drake7f781c92002-05-01 20:33:53 +0000163 self.memo.clear()
164
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000165 def dump(self, object):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000166 """Write a pickled representation of object to the open file object.
167
168 Either the binary or ASCII format will be used, depending on the
169 value of the bin flag passed to the constructor.
170
171 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000172 self.save(object)
173 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000174
Jeremy Hylton3422c992003-01-24 19:29:52 +0000175 def memoize(self, obj):
176 """Store an object in the memo."""
177
178 # The memo is a dictionary mapping object ids to 2-tuples
179 # that contains the memo value and the object being memoized.
180 # The memo value is written to the pickle and will become
181 # the key in the Unpickler's memo. The object is stored in the
182 # memo so that transient objects are kept alive during pickling.
183
184 # The use of the memo length as the memo value is just a convention.
185 # The only requirement is that the memo values by unique.
186 d = id(obj)
187 memo_len = len(self.memo)
188 self.write(self.put(memo_len))
189 self.memo[d] = memo_len, obj
190
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000191 def put(self, i):
Tim Petersc32d8242001-04-10 02:48:53 +0000192 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000193 s = mdumps(i)[1:]
Tim Petersc32d8242001-04-10 02:48:53 +0000194 if i < 256:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000195 return BINPUT + s[0]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000196
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000197 return LONG_BINPUT + s
Guido van Rossuma48061a1995-01-10 00:31:14 +0000198
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000199 return PUT + `i` + '\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000200
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000201 def get(self, i):
Tim Petersc32d8242001-04-10 02:48:53 +0000202 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000203 s = mdumps(i)[1:]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000204
Tim Petersc32d8242001-04-10 02:48:53 +0000205 if i < 256:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000206 return BINGET + s[0]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000207
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000208 return LONG_BINGET + s
Guido van Rossuma48061a1995-01-10 00:31:14 +0000209
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000210 return GET + `i` + '\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000211
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000212 def save(self, object):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000213 memo = self.memo
Guido van Rossuma48061a1995-01-10 00:31:14 +0000214
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000215 pid = self.persistent_id(object)
216 if pid is not None:
217 self.save_pers(pid)
218 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000219
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000220 d = id(object)
Tim Peters2344fae2001-01-15 00:50:52 +0000221
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000222 t = type(object)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000223
Tim Petersc32d8242001-04-10 02:48:53 +0000224 if (t is TupleType) and (len(object) == 0):
225 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000226 self.save_empty_tuple(object)
227 else:
228 self.save_tuple(object)
229 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000230
Raymond Hettinger54f02222002-06-01 14:18:47 +0000231 if d in memo:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000232 self.write(self.get(memo[d][0]))
233 return
234
235 try:
236 f = self.dispatch[t]
237 except KeyError:
Guido van Rossum85ee4912002-03-26 00:51:56 +0000238 try:
239 issc = issubclass(t, TypeType)
240 except TypeError: # t is not a class
241 issc = 0
242 if issc:
Guido van Rossumf048a8f2001-12-19 16:55:02 +0000243 self.save_global(object)
244 return
245
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000246 try:
247 reduce = dispatch_table[t]
248 except KeyError:
249 try:
250 reduce = object.__reduce__
251 except AttributeError:
252 raise PicklingError, \
Guido van Rossum08a92cb1999-10-10 21:14:25 +0000253 "can't pickle %s object: %s" % (`t.__name__`,
254 `object`)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000255 else:
256 tup = reduce()
257 else:
258 tup = reduce(object)
259
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000260 if type(tup) is StringType:
261 self.save_global(object, tup)
262 return
Guido van Rossumd1f49841997-12-10 23:40:18 +0000263
Tim Petersc32d8242001-04-10 02:48:53 +0000264 if type(tup) is not TupleType:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000265 raise PicklingError, "Value returned by %s must be a " \
266 "tuple" % reduce
267
268 l = len(tup)
Tim Peters2344fae2001-01-15 00:50:52 +0000269
Tim Petersc32d8242001-04-10 02:48:53 +0000270 if (l != 2) and (l != 3):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000271 raise PicklingError, "tuple returned by %s must contain " \
272 "only two or three elements" % reduce
273
274 callable = tup[0]
275 arg_tup = tup[1]
Tim Peters2344fae2001-01-15 00:50:52 +0000276
Tim Petersc32d8242001-04-10 02:48:53 +0000277 if l > 2:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000278 state = tup[2]
279 else:
280 state = None
281
Guido van Rossumd1f49841997-12-10 23:40:18 +0000282 if type(arg_tup) is not TupleType and arg_tup is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000283 raise PicklingError, "Second element of tuple returned " \
284 "by %s must be a tuple" % reduce
285
Tim Peters2344fae2001-01-15 00:50:52 +0000286 self.save_reduce(callable, arg_tup, state)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000287 memo_len = len(memo)
288 self.write(self.put(memo_len))
289 memo[d] = (memo_len, object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000290 return
291
292 f(self, object)
293
294 def persistent_id(self, object):
295 return None
296
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000297 def save_pers(self, pid):
Tim Petersc32d8242001-04-10 02:48:53 +0000298 if not self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000299 self.write(PERSID + str(pid) + '\n')
300 else:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000301 self.save(pid)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000302 self.write(BINPERSID)
303
Jeremy Hylton3422c992003-01-24 19:29:52 +0000304 def save_reduce(self, acallable, arg_tup, state = None):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000305 write = self.write
306 save = self.save
307
Jeremy Hylton3422c992003-01-24 19:29:52 +0000308 if not callable(acallable):
309 raise PicklingError("__reduce__() must return callable as "
310 "first argument, not %s" % `acallable`)
Tim Peters22a449a2003-01-27 20:16:36 +0000311
Jeremy Hylton3422c992003-01-24 19:29:52 +0000312 save(acallable)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000313 save(arg_tup)
314 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000315
Tim Petersc32d8242001-04-10 02:48:53 +0000316 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000317 save(state)
318 write(BUILD)
319
320 dispatch = {}
321
322 def save_none(self, object):
323 self.write(NONE)
324 dispatch[NoneType] = save_none
325
Guido van Rossum77f6a652002-04-03 22:41:51 +0000326 def save_bool(self, object):
327 if object:
328 self.write(TRUE)
329 else:
330 self.write(FALSE)
331 dispatch[bool] = save_bool
332
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000333 def save_int(self, object):
Tim Petersc32d8242001-04-10 02:48:53 +0000334 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000335 # If the int is small enough to fit in a signed 4-byte 2's-comp
336 # format, we can store it more efficiently than the general
337 # case.
338 high_bits = object >> 31 # note that Python shift sign-extends
339 if high_bits == 0 or high_bits == -1:
340 # All high bits are copies of bit 2**31, so the value
341 # fits in a 4-byte signed int.
342 i = mdumps(object)[1:]
343 assert len(i) == 4
344 if i[-2:] == '\000\000': # fits in 2-byte unsigned int
345 if i[-3] == '\000': # fits in 1-byte unsigned int
346 self.write(BININT1 + i[0])
347 else:
348 self.write(BININT2 + i[:2])
349 else:
350 self.write(BININT + i)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000351 return
Tim Peters44714002001-04-10 05:02:52 +0000352 # Text pickle, or int too big to fit in signed 4-byte format.
353 self.write(INT + `object` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000354 dispatch[IntType] = save_int
355
356 def save_long(self, object):
357 self.write(LONG + `object` + '\n')
358 dispatch[LongType] = save_long
359
Guido van Rossumd3703791998-10-22 20:15:36 +0000360 def save_float(self, object, pack=struct.pack):
361 if self.bin:
362 self.write(BINFLOAT + pack('>d', object))
363 else:
364 self.write(FLOAT + `object` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000365 dispatch[FloatType] = save_float
366
367 def save_string(self, object):
Tim Petersc32d8242001-04-10 02:48:53 +0000368 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000369 l = len(object)
370 s = mdumps(l)[1:]
Tim Petersc32d8242001-04-10 02:48:53 +0000371 if l < 256:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000372 self.write(SHORT_BINSTRING + s[0] + object)
373 else:
374 self.write(BINSTRING + s + object)
375 else:
376 self.write(STRING + `object` + '\n')
Jeremy Hylton3422c992003-01-24 19:29:52 +0000377 self.memoize(object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000378 dispatch[StringType] = save_string
379
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000380 def save_unicode(self, object):
Tim Petersc32d8242001-04-10 02:48:53 +0000381 if self.bin:
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000382 encoding = object.encode('utf-8')
383 l = len(encoding)
384 s = mdumps(l)[1:]
385 self.write(BINUNICODE + s + encoding)
386 else:
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000387 object = object.replace("\\", "\\u005c")
388 object = object.replace("\n", "\\u000a")
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000389 self.write(UNICODE + object.encode('raw-unicode-escape') + '\n')
Jeremy Hylton3422c992003-01-24 19:29:52 +0000390 self.memoize(object)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000391 dispatch[UnicodeType] = save_unicode
392
Guido van Rossum31584cb2001-01-22 14:53:29 +0000393 if StringType == UnicodeType:
394 # This is true for Jython
395 def save_string(self, object):
Guido van Rossum31584cb2001-01-22 14:53:29 +0000396 unicode = object.isunicode()
397
Tim Petersc32d8242001-04-10 02:48:53 +0000398 if self.bin:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000399 if unicode:
400 object = object.encode("utf-8")
401 l = len(object)
402 s = mdumps(l)[1:]
Tim Petersc32d8242001-04-10 02:48:53 +0000403 if l < 256 and not unicode:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000404 self.write(SHORT_BINSTRING + s[0] + object)
405 else:
406 if unicode:
407 self.write(BINUNICODE + s + object)
408 else:
409 self.write(BINSTRING + s + object)
410 else:
Tim Peters658cba62001-02-09 20:06:00 +0000411 if unicode:
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000412 object = object.replace("\\", "\\u005c")
413 object = object.replace("\n", "\\u000a")
Guido van Rossum31584cb2001-01-22 14:53:29 +0000414 object = object.encode('raw-unicode-escape')
415 self.write(UNICODE + object + '\n')
416 else:
417 self.write(STRING + `object` + '\n')
Jeremy Hylton3422c992003-01-24 19:29:52 +0000418 self.memoize(object)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000419 dispatch[StringType] = save_string
Tim Peters658cba62001-02-09 20:06:00 +0000420
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000421 def save_tuple(self, object):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000422 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)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000444
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000445 dispatch[TupleType] = save_tuple
446
447 def save_empty_tuple(self, object):
448 self.write(EMPTY_TUPLE)
449
450 def save_list(self, object):
451 d = id(object)
452
453 write = self.write
454 save = self.save
455 memo = self.memo
456
Tim Petersc32d8242001-04-10 02:48:53 +0000457 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000458 write(EMPTY_LIST)
459 else:
460 write(MARK + LIST)
461
Jeremy Hylton3422c992003-01-24 19:29:52 +0000462 self.memoize(object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000463
464 using_appends = (self.bin and (len(object) > 1))
465
Tim Petersc32d8242001-04-10 02:48:53 +0000466 if using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000467 write(MARK)
468
469 for element in object:
470 save(element)
Tim Peters2344fae2001-01-15 00:50:52 +0000471
Tim Petersc32d8242001-04-10 02:48:53 +0000472 if not using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000473 write(APPEND)
474
Tim Petersc32d8242001-04-10 02:48:53 +0000475 if using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000476 write(APPENDS)
477 dispatch[ListType] = save_list
478
479 def save_dict(self, object):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000480 write = self.write
481 save = self.save
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000482
Tim Petersc32d8242001-04-10 02:48:53 +0000483 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000484 write(EMPTY_DICT)
485 else:
486 write(MARK + DICT)
487
Jeremy Hylton3422c992003-01-24 19:29:52 +0000488 self.memoize(object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000489
490 using_setitems = (self.bin and (len(object) > 1))
491
Tim Petersc32d8242001-04-10 02:48:53 +0000492 if using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000493 write(MARK)
494
495 items = object.items()
496 for key, value in items:
497 save(key)
498 save(value)
499
Tim Petersc32d8242001-04-10 02:48:53 +0000500 if not using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000501 write(SETITEM)
502
Tim Petersc32d8242001-04-10 02:48:53 +0000503 if using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000504 write(SETITEMS)
505
506 dispatch[DictionaryType] = save_dict
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000507 if not PyStringMap is None:
508 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000509
510 def save_inst(self, object):
511 d = id(object)
512 cls = object.__class__
513
514 memo = self.memo
515 write = self.write
516 save = self.save
517
518 if hasattr(object, '__getinitargs__'):
519 args = object.__getinitargs__()
520 len(args) # XXX Assert it's a sequence
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000521 _keep_alive(args, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000522 else:
523 args = ()
524
525 write(MARK)
526
Tim Petersc32d8242001-04-10 02:48:53 +0000527 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000528 save(cls)
529
530 for arg in args:
531 save(arg)
532
Jeremy Hylton3422c992003-01-24 19:29:52 +0000533 # This method does not use memoize() so that it can handle
534 # the special case for non-binary mode.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000535 memo_len = len(memo)
Tim Petersc32d8242001-04-10 02:48:53 +0000536 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000537 write(OBJ + self.put(memo_len))
538 else:
Guido van Rossum4fb5b281997-09-12 20:07:24 +0000539 write(INST + cls.__module__ + '\n' + cls.__name__ + '\n' +
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000540 self.put(memo_len))
541
542 memo[d] = (memo_len, object)
543
544 try:
545 getstate = object.__getstate__
546 except AttributeError:
547 stuff = object.__dict__
548 else:
549 stuff = getstate()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000550 _keep_alive(stuff, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000551 save(stuff)
552 write(BUILD)
553 dispatch[InstanceType] = save_inst
554
555 def save_global(self, object, name = None):
556 write = self.write
557 memo = self.memo
558
Tim Petersc32d8242001-04-10 02:48:53 +0000559 if name is None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000560 name = object.__name__
561
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000562 try:
563 module = object.__module__
564 except AttributeError:
565 module = whichmodule(object, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000566
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000567 try:
568 __import__(module)
569 mod = sys.modules[module]
570 klass = getattr(mod, name)
571 except (ImportError, KeyError, AttributeError):
572 raise PicklingError(
573 "Can't pickle %r: it's not found as %s.%s" %
574 (object, module, name))
575 else:
576 if klass is not object:
577 raise PicklingError(
578 "Can't pickle %r: it's not the same object as %s.%s" %
579 (object, module, name))
580
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000581 memo_len = len(memo)
582 write(GLOBAL + module + '\n' + name + '\n' +
583 self.put(memo_len))
584 memo[id(object)] = (memo_len, object)
585 dispatch[ClassType] = save_global
586 dispatch[FunctionType] = save_global
587 dispatch[BuiltinFunctionType] = save_global
Tim Peters6d6c1a32001-08-02 04:15:00 +0000588 dispatch[TypeType] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000589
Guido van Rossuma48061a1995-01-10 00:31:14 +0000590
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000591def _keep_alive(x, memo):
592 """Keeps a reference to the object x in the memo.
593
594 Because we remember objects by their id, we have
595 to assure that possibly temporary objects are kept
596 alive by referencing them.
597 We store a reference at the id of the memo, which should
598 normally not be used unless someone tries to deepcopy
599 the memo itself...
600 """
601 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000602 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000603 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000604 # aha, this is the first one :-)
605 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000606
607
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000608classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000609
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000610def whichmodule(func, funcname):
611 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000612
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000613 Search sys.modules for the module.
614 Cache in classmap.
615 Return a module name.
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000616 If the function cannot be found, return __main__.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000617 """
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000618 if func in classmap:
619 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000620
621 for name, module in sys.modules.items():
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000622 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000623 continue # skip dummy package entries
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000624 if name != '__main__' and \
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000625 hasattr(module, funcname) and \
626 getattr(module, funcname) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000627 break
628 else:
629 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000630 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000631 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000632
633
634class Unpickler:
635
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000636 def __init__(self, file):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000637 """This takes a file-like object for reading a pickle data stream.
638
639 This class automatically determines whether the data stream was
640 written in binary mode or not, so it does not need a flag as in
641 the Pickler class factory.
642
643 The file-like object must have two methods, a read() method that
644 takes an integer argument, and a readline() method that requires no
645 arguments. Both methods should return a string. Thus file-like
646 object can be a file object opened for reading, a StringIO object,
647 or any other custom object that meets this interface.
648
649 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000650 self.readline = file.readline
651 self.read = file.read
652 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000653
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000654 def load(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000655 """Read a pickled object representation from the open file object.
656
657 Return the reconstituted object hierarchy specified in the file
658 object.
659
660 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000661 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000662 self.stack = []
663 self.append = self.stack.append
664 read = self.read
665 dispatch = self.dispatch
666 try:
667 while 1:
668 key = read(1)
669 dispatch[key](self)
Guido van Rossumff871742000-12-13 18:11:56 +0000670 except _Stop, stopinst:
671 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000672
673 def marker(self):
674 stack = self.stack
675 mark = self.mark
676 k = len(stack)-1
677 while stack[k] is not mark: k = k-1
678 return k
679
680 dispatch = {}
681
682 def load_eof(self):
683 raise EOFError
684 dispatch[''] = load_eof
685
686 def load_persid(self):
687 pid = self.readline()[:-1]
688 self.append(self.persistent_load(pid))
689 dispatch[PERSID] = load_persid
690
691 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000692 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000693 self.append(self.persistent_load(pid))
694 dispatch[BINPERSID] = load_binpersid
695
696 def load_none(self):
697 self.append(None)
698 dispatch[NONE] = load_none
699
700 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000701 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000702 if data == FALSE[1:]:
703 val = False
704 elif data == TRUE[1:]:
705 val = True
706 else:
707 try:
708 val = int(data)
709 except ValueError:
710 val = long(data)
711 self.append(val)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000712 dispatch[INT] = load_int
713
714 def load_binint(self):
715 self.append(mloads('i' + self.read(4)))
716 dispatch[BININT] = load_binint
717
718 def load_binint1(self):
719 self.append(mloads('i' + self.read(1) + '\000\000\000'))
720 dispatch[BININT1] = load_binint1
721
722 def load_binint2(self):
723 self.append(mloads('i' + self.read(2) + '\000\000'))
724 dispatch[BININT2] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000725
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000726 def load_long(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000727 self.append(long(self.readline()[:-1], 0))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000728 dispatch[LONG] = load_long
729
730 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000731 self.append(float(self.readline()[:-1]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000732 dispatch[FLOAT] = load_float
733
Guido van Rossumd3703791998-10-22 20:15:36 +0000734 def load_binfloat(self, unpack=struct.unpack):
735 self.append(unpack('>d', self.read(8))[0])
736 dispatch[BINFLOAT] = load_binfloat
737
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000738 def load_string(self):
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000739 rep = self.readline()[:-1]
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000740 for q in _quotes:
741 if rep.startswith(q):
742 if not rep.endswith(q):
743 raise ValueError, "insecure string pickle"
744 rep = rep[len(q):-len(q)]
745 break
746 else:
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000747 raise ValueError, "insecure string pickle"
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000748 self.append(rep.decode("string-escape"))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000749 dispatch[STRING] = load_string
750
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000751 def _is_string_secure(self, s):
752 """Return true if s contains a string that is safe to eval
753
754 The definition of secure string is based on the implementation
755 in cPickle. s is secure as long as it only contains a quoted
756 string and optional trailing whitespace.
757 """
758 q = s[0]
759 if q not in ("'", '"'):
760 return 0
761 # find the closing quote
762 offset = 1
763 i = None
764 while 1:
765 try:
766 i = s.index(q, offset)
767 except ValueError:
768 # if there is an error the first time, there is no
769 # close quote
770 if offset == 1:
771 return 0
772 if s[i-1] != '\\':
773 break
774 # check to see if this one is escaped
775 nslash = 0
776 j = i - 1
777 while j >= offset and s[j] == '\\':
778 j = j - 1
779 nslash = nslash + 1
780 if nslash % 2 == 0:
781 break
782 offset = i + 1
783 for c in s[i+1:]:
784 if ord(c) > 32:
785 return 0
786 return 1
787
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000788 def load_binstring(self):
789 len = mloads('i' + self.read(4))
790 self.append(self.read(len))
791 dispatch[BINSTRING] = load_binstring
792
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000793 def load_unicode(self):
794 self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
795 dispatch[UNICODE] = load_unicode
796
797 def load_binunicode(self):
798 len = mloads('i' + self.read(4))
799 self.append(unicode(self.read(len),'utf-8'))
800 dispatch[BINUNICODE] = load_binunicode
801
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000802 def load_short_binstring(self):
803 len = mloads('i' + self.read(1) + '\000\000\000')
804 self.append(self.read(len))
805 dispatch[SHORT_BINSTRING] = load_short_binstring
806
807 def load_tuple(self):
808 k = self.marker()
809 self.stack[k:] = [tuple(self.stack[k+1:])]
810 dispatch[TUPLE] = load_tuple
811
812 def load_empty_tuple(self):
813 self.stack.append(())
814 dispatch[EMPTY_TUPLE] = load_empty_tuple
815
816 def load_empty_list(self):
817 self.stack.append([])
818 dispatch[EMPTY_LIST] = load_empty_list
819
820 def load_empty_dictionary(self):
821 self.stack.append({})
822 dispatch[EMPTY_DICT] = load_empty_dictionary
823
824 def load_list(self):
825 k = self.marker()
826 self.stack[k:] = [self.stack[k+1:]]
827 dispatch[LIST] = load_list
828
829 def load_dict(self):
830 k = self.marker()
831 d = {}
832 items = self.stack[k+1:]
833 for i in range(0, len(items), 2):
834 key = items[i]
835 value = items[i+1]
836 d[key] = value
837 self.stack[k:] = [d]
838 dispatch[DICT] = load_dict
839
840 def load_inst(self):
841 k = self.marker()
842 args = tuple(self.stack[k+1:])
843 del self.stack[k:]
844 module = self.readline()[:-1]
845 name = self.readline()[:-1]
846 klass = self.find_class(module, name)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000847 instantiated = 0
848 if (not args and type(klass) is ClassType and
849 not hasattr(klass, "__getinitargs__")):
850 try:
851 value = _EmptyClass()
852 value.__class__ = klass
Guido van Rossumb19e2a31998-04-13 18:08:45 +0000853 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000854 except RuntimeError:
855 # In restricted execution, assignment to inst.__class__ is
856 # prohibited
857 pass
858 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +0000859 try:
Barry Warsawbf4d9592001-11-15 23:42:58 +0000860 if not hasattr(klass, '__safe_for_unpickling__'):
861 raise UnpicklingError('%s is not safe for unpickling' %
862 klass)
Guido van Rossum743d17e1998-09-15 20:25:57 +0000863 value = apply(klass, args)
864 except TypeError, err:
865 raise TypeError, "in constructor for %s: %s" % (
866 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000867 self.append(value)
868 dispatch[INST] = load_inst
869
870 def load_obj(self):
871 stack = self.stack
872 k = self.marker()
873 klass = stack[k + 1]
874 del stack[k + 1]
Tim Peters2344fae2001-01-15 00:50:52 +0000875 args = tuple(stack[k + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000876 del stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000877 instantiated = 0
878 if (not args and type(klass) is ClassType and
879 not hasattr(klass, "__getinitargs__")):
880 try:
881 value = _EmptyClass()
882 value.__class__ = klass
883 instantiated = 1
884 except RuntimeError:
885 # In restricted execution, assignment to inst.__class__ is
886 # prohibited
887 pass
888 if not instantiated:
889 value = apply(klass, args)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000890 self.append(value)
Tim Peters2344fae2001-01-15 00:50:52 +0000891 dispatch[OBJ] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000892
893 def load_global(self):
894 module = self.readline()[:-1]
895 name = self.readline()[:-1]
896 klass = self.find_class(module, name)
897 self.append(klass)
898 dispatch[GLOBAL] = load_global
899
900 def find_class(self, module, name):
Barry Warsawbf4d9592001-11-15 23:42:58 +0000901 __import__(module)
902 mod = sys.modules[module]
903 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000904 return klass
905
906 def load_reduce(self):
907 stack = self.stack
908
909 callable = stack[-2]
910 arg_tup = stack[-1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000911 del stack[-2:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000912
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000913 if type(callable) is not ClassType:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000914 if not callable in safe_constructors:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000915 try:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000916 safe = callable.__safe_for_unpickling__
917 except AttributeError:
918 safe = None
Guido van Rossuma48061a1995-01-10 00:31:14 +0000919
Tim Petersc32d8242001-04-10 02:48:53 +0000920 if not safe:
Tim Peters2344fae2001-01-15 00:50:52 +0000921 raise UnpicklingError, "%s is not safe for " \
922 "unpickling" % callable
Guido van Rossuma48061a1995-01-10 00:31:14 +0000923
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000924 if arg_tup is None:
Raymond Hettinger97394bc2002-05-21 17:22:02 +0000925 import warnings
926 warnings.warn("The None return argument form of __reduce__ is "
927 "deprecated. Return a tuple of arguments instead.",
Tim Peters8ac14952002-05-23 15:15:30 +0000928 DeprecationWarning)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000929 value = callable.__basicnew__()
930 else:
931 value = apply(callable, arg_tup)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000932 self.append(value)
933 dispatch[REDUCE] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +0000934
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000935 def load_pop(self):
936 del self.stack[-1]
937 dispatch[POP] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +0000938
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000939 def load_pop_mark(self):
940 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000941 del self.stack[k:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000942 dispatch[POP_MARK] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +0000943
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000944 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +0000945 self.append(self.stack[-1])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000946 dispatch[DUP] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +0000947
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000948 def load_get(self):
949 self.append(self.memo[self.readline()[:-1]])
950 dispatch[GET] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +0000951
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000952 def load_binget(self):
953 i = mloads('i' + self.read(1) + '\000\000\000')
954 self.append(self.memo[`i`])
955 dispatch[BINGET] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +0000956
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000957 def load_long_binget(self):
958 i = mloads('i' + self.read(4))
959 self.append(self.memo[`i`])
960 dispatch[LONG_BINGET] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +0000961
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000962 def load_put(self):
963 self.memo[self.readline()[:-1]] = self.stack[-1]
964 dispatch[PUT] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +0000965
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000966 def load_binput(self):
967 i = mloads('i' + self.read(1) + '\000\000\000')
968 self.memo[`i`] = self.stack[-1]
969 dispatch[BINPUT] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +0000970
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000971 def load_long_binput(self):
972 i = mloads('i' + self.read(4))
973 self.memo[`i`] = self.stack[-1]
974 dispatch[LONG_BINPUT] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +0000975
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000976 def load_append(self):
977 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000978 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000979 list = stack[-1]
980 list.append(value)
981 dispatch[APPEND] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +0000982
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000983 def load_appends(self):
984 stack = self.stack
985 mark = self.marker()
986 list = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000987 for i in range(mark + 1, len(stack)):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000988 list.append(stack[i])
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000989
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000990 del stack[mark:]
991 dispatch[APPENDS] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +0000992
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000993 def load_setitem(self):
994 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000995 value = stack.pop()
996 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000997 dict = stack[-1]
998 dict[key] = value
999 dispatch[SETITEM] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001000
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001001 def load_setitems(self):
1002 stack = self.stack
1003 mark = self.marker()
1004 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001005 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001006 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001007
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001008 del stack[mark:]
1009 dispatch[SETITEMS] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001010
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001011 def load_build(self):
1012 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001013 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001014 inst = stack[-1]
1015 try:
1016 setstate = inst.__setstate__
1017 except AttributeError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001018 try:
1019 inst.__dict__.update(value)
1020 except RuntimeError:
1021 # XXX In restricted execution, the instance's __dict__ is not
1022 # accessible. Use the old way of unpickling the instance
1023 # variables. This is a semantic different when unpickling in
1024 # restricted vs. unrestricted modes.
1025 for k, v in value.items():
1026 setattr(inst, k, v)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001027 else:
1028 setstate(value)
1029 dispatch[BUILD] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001030
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001031 def load_mark(self):
1032 self.append(self.mark)
1033 dispatch[MARK] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001034
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001035 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001036 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001037 raise _Stop(value)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001038 dispatch[STOP] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001039
Guido van Rossume467be61997-12-05 19:42:42 +00001040# Helper class for load_inst/load_obj
1041
1042class _EmptyClass:
1043 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001044
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001045# Shorthands
1046
Jeremy Hyltonabe2c622001-10-15 21:29:28 +00001047try:
1048 from cStringIO import StringIO
1049except ImportError:
1050 from StringIO import StringIO
Guido van Rossumc7c5e691996-07-22 22:26:07 +00001051
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001052def dump(object, file, bin = 0):
1053 Pickler(file, bin).dump(object)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001054
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001055def dumps(object, bin = 0):
1056 file = StringIO()
1057 Pickler(file, bin).dump(object)
1058 return file.getvalue()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001059
1060def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001061 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001062
1063def loads(str):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001064 file = StringIO(str)
1065 return Unpickler(file).load()