blob: d3d1dcfee34e71aa09a6b178273a606e98c44c1e [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
Tim Peterse46b73f2003-01-27 21:22:10 +0000178 # The Pickler memo is a dictionary mapping object ids to 2-tuples
179 # that contain the Unpickler memo key and the object being memoized.
180 # The memo key is written to the pickle and will become
Jeremy Hylton3422c992003-01-24 19:29:52 +0000181 # the key in the Unpickler's memo. The object is stored in the
Tim Peterse46b73f2003-01-27 21:22:10 +0000182 # Pickler memo so that transient objects are kept alive during
183 # pickling.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000184
Tim Peterse46b73f2003-01-27 21:22:10 +0000185 # The use of the Unpickler memo length as the memo key is just a
186 # convention. The only requirement is that the memo values be unique.
187 # But there appears no advantage to any other scheme, and this
188 # scheme allows the Unpickler memo to implemented as a plain (but
189 # growable) array, indexed by memo key.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000190 d = id(obj)
191 memo_len = len(self.memo)
192 self.write(self.put(memo_len))
193 self.memo[d] = memo_len, obj
194
Tim Petersbb38e302003-01-27 21:25:41 +0000195 # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000196 def put(self, i):
Tim Petersc32d8242001-04-10 02:48:53 +0000197 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000198 s = mdumps(i)[1:]
Tim Petersc32d8242001-04-10 02:48:53 +0000199 if i < 256:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000200 return BINPUT + s[0]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000201
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000202 return LONG_BINPUT + s
Guido van Rossuma48061a1995-01-10 00:31:14 +0000203
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000204 return PUT + `i` + '\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000205
Tim Petersbb38e302003-01-27 21:25:41 +0000206 # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000207 def get(self, i):
Tim Petersc32d8242001-04-10 02:48:53 +0000208 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000209 s = mdumps(i)[1:]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000210
Tim Petersc32d8242001-04-10 02:48:53 +0000211 if i < 256:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000212 return BINGET + s[0]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000213
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000214 return LONG_BINGET + s
Guido van Rossuma48061a1995-01-10 00:31:14 +0000215
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000216 return GET + `i` + '\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000217
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000218 def save(self, object):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000219 memo = self.memo
Guido van Rossuma48061a1995-01-10 00:31:14 +0000220
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000221 pid = self.persistent_id(object)
222 if pid is not None:
223 self.save_pers(pid)
224 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000225
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000226 d = id(object)
Tim Peters2344fae2001-01-15 00:50:52 +0000227
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000228 t = type(object)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000229
Tim Petersc32d8242001-04-10 02:48:53 +0000230 if (t is TupleType) and (len(object) == 0):
231 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000232 self.save_empty_tuple(object)
233 else:
234 self.save_tuple(object)
235 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000236
Raymond Hettinger54f02222002-06-01 14:18:47 +0000237 if d in memo:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000238 self.write(self.get(memo[d][0]))
239 return
240
241 try:
242 f = self.dispatch[t]
243 except KeyError:
Guido van Rossum85ee4912002-03-26 00:51:56 +0000244 try:
245 issc = issubclass(t, TypeType)
246 except TypeError: # t is not a class
247 issc = 0
248 if issc:
Guido van Rossumf048a8f2001-12-19 16:55:02 +0000249 self.save_global(object)
250 return
251
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000252 try:
253 reduce = dispatch_table[t]
254 except KeyError:
255 try:
256 reduce = object.__reduce__
257 except AttributeError:
258 raise PicklingError, \
Guido van Rossum08a92cb1999-10-10 21:14:25 +0000259 "can't pickle %s object: %s" % (`t.__name__`,
260 `object`)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000261 else:
262 tup = reduce()
263 else:
264 tup = reduce(object)
265
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000266 if type(tup) is StringType:
267 self.save_global(object, tup)
268 return
Guido van Rossumd1f49841997-12-10 23:40:18 +0000269
Tim Petersc32d8242001-04-10 02:48:53 +0000270 if type(tup) is not TupleType:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000271 raise PicklingError, "Value returned by %s must be a " \
272 "tuple" % reduce
273
274 l = len(tup)
Tim Peters2344fae2001-01-15 00:50:52 +0000275
Tim Petersc32d8242001-04-10 02:48:53 +0000276 if (l != 2) and (l != 3):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000277 raise PicklingError, "tuple returned by %s must contain " \
278 "only two or three elements" % reduce
279
280 callable = tup[0]
281 arg_tup = tup[1]
Tim Peters2344fae2001-01-15 00:50:52 +0000282
Tim Petersc32d8242001-04-10 02:48:53 +0000283 if l > 2:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000284 state = tup[2]
285 else:
286 state = None
287
Guido van Rossumd1f49841997-12-10 23:40:18 +0000288 if type(arg_tup) is not TupleType and arg_tup is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000289 raise PicklingError, "Second element of tuple returned " \
290 "by %s must be a tuple" % reduce
291
Tim Peters2344fae2001-01-15 00:50:52 +0000292 self.save_reduce(callable, arg_tup, state)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000293 memo_len = len(memo)
294 self.write(self.put(memo_len))
295 memo[d] = (memo_len, object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000296 return
297
298 f(self, object)
299
300 def persistent_id(self, object):
301 return None
302
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000303 def save_pers(self, pid):
Tim Petersc32d8242001-04-10 02:48:53 +0000304 if not self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000305 self.write(PERSID + str(pid) + '\n')
306 else:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000307 self.save(pid)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000308 self.write(BINPERSID)
309
Jeremy Hylton3422c992003-01-24 19:29:52 +0000310 def save_reduce(self, acallable, arg_tup, state = None):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000311 write = self.write
312 save = self.save
313
Jeremy Hylton3422c992003-01-24 19:29:52 +0000314 if not callable(acallable):
315 raise PicklingError("__reduce__() must return callable as "
316 "first argument, not %s" % `acallable`)
Tim Peters22a449a2003-01-27 20:16:36 +0000317
Jeremy Hylton3422c992003-01-24 19:29:52 +0000318 save(acallable)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000319 save(arg_tup)
320 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000321
Tim Petersc32d8242001-04-10 02:48:53 +0000322 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000323 save(state)
324 write(BUILD)
325
326 dispatch = {}
327
328 def save_none(self, object):
329 self.write(NONE)
330 dispatch[NoneType] = save_none
331
Guido van Rossum77f6a652002-04-03 22:41:51 +0000332 def save_bool(self, object):
333 if object:
334 self.write(TRUE)
335 else:
336 self.write(FALSE)
337 dispatch[bool] = save_bool
338
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000339 def save_int(self, object):
Tim Petersc32d8242001-04-10 02:48:53 +0000340 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000341 # If the int is small enough to fit in a signed 4-byte 2's-comp
342 # format, we can store it more efficiently than the general
343 # case.
344 high_bits = object >> 31 # note that Python shift sign-extends
345 if high_bits == 0 or high_bits == -1:
346 # All high bits are copies of bit 2**31, so the value
347 # fits in a 4-byte signed int.
348 i = mdumps(object)[1:]
349 assert len(i) == 4
350 if i[-2:] == '\000\000': # fits in 2-byte unsigned int
351 if i[-3] == '\000': # fits in 1-byte unsigned int
352 self.write(BININT1 + i[0])
353 else:
354 self.write(BININT2 + i[:2])
355 else:
356 self.write(BININT + i)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000357 return
Tim Peters44714002001-04-10 05:02:52 +0000358 # Text pickle, or int too big to fit in signed 4-byte format.
359 self.write(INT + `object` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000360 dispatch[IntType] = save_int
361
362 def save_long(self, object):
363 self.write(LONG + `object` + '\n')
364 dispatch[LongType] = save_long
365
Guido van Rossumd3703791998-10-22 20:15:36 +0000366 def save_float(self, object, pack=struct.pack):
367 if self.bin:
368 self.write(BINFLOAT + pack('>d', object))
369 else:
370 self.write(FLOAT + `object` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000371 dispatch[FloatType] = save_float
372
373 def save_string(self, object):
Tim Petersc32d8242001-04-10 02:48:53 +0000374 if self.bin:
Tim Petersbbf63cd2003-01-27 21:15:36 +0000375 n = len(object)
376 if n < 256:
377 self.write(SHORT_BINSTRING + chr(n) + object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000378 else:
Tim Petersbbf63cd2003-01-27 21:15:36 +0000379 self.write(BINSTRING + mdumps(n)[1:] + object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000380 else:
381 self.write(STRING + `object` + '\n')
Jeremy Hylton3422c992003-01-24 19:29:52 +0000382 self.memoize(object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000383 dispatch[StringType] = save_string
384
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000385 def save_unicode(self, object):
Tim Petersc32d8242001-04-10 02:48:53 +0000386 if self.bin:
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000387 encoding = object.encode('utf-8')
Tim Petersbbf63cd2003-01-27 21:15:36 +0000388 n = len(encoding)
389 s = mdumps(n)[1:]
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000390 self.write(BINUNICODE + s + encoding)
391 else:
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000392 object = object.replace("\\", "\\u005c")
393 object = object.replace("\n", "\\u000a")
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000394 self.write(UNICODE + object.encode('raw-unicode-escape') + '\n')
Jeremy Hylton3422c992003-01-24 19:29:52 +0000395 self.memoize(object)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000396 dispatch[UnicodeType] = save_unicode
397
Guido van Rossum31584cb2001-01-22 14:53:29 +0000398 if StringType == UnicodeType:
399 # This is true for Jython
400 def save_string(self, object):
Guido van Rossum31584cb2001-01-22 14:53:29 +0000401 unicode = object.isunicode()
402
Tim Petersc32d8242001-04-10 02:48:53 +0000403 if self.bin:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000404 if unicode:
405 object = object.encode("utf-8")
406 l = len(object)
407 s = mdumps(l)[1:]
Tim Petersc32d8242001-04-10 02:48:53 +0000408 if l < 256 and not unicode:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000409 self.write(SHORT_BINSTRING + s[0] + object)
410 else:
411 if unicode:
412 self.write(BINUNICODE + s + object)
413 else:
414 self.write(BINSTRING + s + object)
415 else:
Tim Peters658cba62001-02-09 20:06:00 +0000416 if unicode:
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000417 object = object.replace("\\", "\\u005c")
418 object = object.replace("\n", "\\u000a")
Guido van Rossum31584cb2001-01-22 14:53:29 +0000419 object = object.encode('raw-unicode-escape')
420 self.write(UNICODE + object + '\n')
421 else:
422 self.write(STRING + `object` + '\n')
Jeremy Hylton3422c992003-01-24 19:29:52 +0000423 self.memoize(object)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000424 dispatch[StringType] = save_string
Tim Peters658cba62001-02-09 20:06:00 +0000425
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000426 def save_tuple(self, object):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000427 write = self.write
428 save = self.save
429 memo = self.memo
430
431 d = id(object)
432
433 write(MARK)
434
435 for element in object:
436 save(element)
437
Raymond Hettinger54f02222002-06-01 14:18:47 +0000438 if len(object) and d in memo:
Tim Petersc32d8242001-04-10 02:48:53 +0000439 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000440 write(POP_MARK + self.get(memo[d][0]))
441 return
Tim Peters2344fae2001-01-15 00:50:52 +0000442
Guido van Rossum599174f1998-03-31 16:30:28 +0000443 write(POP * (len(object) + 1) + self.get(memo[d][0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000444 return
445
446 memo_len = len(memo)
447 self.write(TUPLE + self.put(memo_len))
448 memo[d] = (memo_len, object)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000449
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000450 dispatch[TupleType] = save_tuple
451
452 def save_empty_tuple(self, object):
453 self.write(EMPTY_TUPLE)
454
455 def save_list(self, object):
456 d = id(object)
457
458 write = self.write
459 save = self.save
460 memo = self.memo
461
Tim Petersc32d8242001-04-10 02:48:53 +0000462 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000463 write(EMPTY_LIST)
464 else:
465 write(MARK + LIST)
466
Jeremy Hylton3422c992003-01-24 19:29:52 +0000467 self.memoize(object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000468
469 using_appends = (self.bin and (len(object) > 1))
470
Tim Petersc32d8242001-04-10 02:48:53 +0000471 if using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000472 write(MARK)
473
474 for element in object:
475 save(element)
Tim Peters2344fae2001-01-15 00:50:52 +0000476
Tim Petersc32d8242001-04-10 02:48:53 +0000477 if not using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000478 write(APPEND)
479
Tim Petersc32d8242001-04-10 02:48:53 +0000480 if using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000481 write(APPENDS)
482 dispatch[ListType] = save_list
483
484 def save_dict(self, object):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000485 write = self.write
486 save = self.save
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000487
Tim Petersc32d8242001-04-10 02:48:53 +0000488 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000489 write(EMPTY_DICT)
490 else:
491 write(MARK + DICT)
492
Jeremy Hylton3422c992003-01-24 19:29:52 +0000493 self.memoize(object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000494
495 using_setitems = (self.bin and (len(object) > 1))
496
Tim Petersc32d8242001-04-10 02:48:53 +0000497 if using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000498 write(MARK)
499
500 items = object.items()
501 for key, value in items:
502 save(key)
503 save(value)
504
Tim Petersc32d8242001-04-10 02:48:53 +0000505 if not using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000506 write(SETITEM)
507
Tim Petersc32d8242001-04-10 02:48:53 +0000508 if using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000509 write(SETITEMS)
510
511 dispatch[DictionaryType] = save_dict
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000512 if not PyStringMap is None:
513 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000514
515 def save_inst(self, object):
516 d = id(object)
517 cls = object.__class__
518
519 memo = self.memo
520 write = self.write
521 save = self.save
522
523 if hasattr(object, '__getinitargs__'):
524 args = object.__getinitargs__()
525 len(args) # XXX Assert it's a sequence
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000526 _keep_alive(args, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000527 else:
528 args = ()
529
530 write(MARK)
531
Tim Petersc32d8242001-04-10 02:48:53 +0000532 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000533 save(cls)
534
535 for arg in args:
536 save(arg)
537
Jeremy Hylton3422c992003-01-24 19:29:52 +0000538 # This method does not use memoize() so that it can handle
539 # the special case for non-binary mode.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000540 memo_len = len(memo)
Tim Petersc32d8242001-04-10 02:48:53 +0000541 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000542 write(OBJ + self.put(memo_len))
543 else:
Guido van Rossum4fb5b281997-09-12 20:07:24 +0000544 write(INST + cls.__module__ + '\n' + cls.__name__ + '\n' +
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000545 self.put(memo_len))
546
547 memo[d] = (memo_len, object)
548
549 try:
550 getstate = object.__getstate__
551 except AttributeError:
552 stuff = object.__dict__
553 else:
554 stuff = getstate()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000555 _keep_alive(stuff, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000556 save(stuff)
557 write(BUILD)
558 dispatch[InstanceType] = save_inst
559
560 def save_global(self, object, name = None):
561 write = self.write
562 memo = self.memo
563
Tim Petersc32d8242001-04-10 02:48:53 +0000564 if name is None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000565 name = object.__name__
566
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000567 try:
568 module = object.__module__
569 except AttributeError:
570 module = whichmodule(object, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000571
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000572 try:
573 __import__(module)
574 mod = sys.modules[module]
575 klass = getattr(mod, name)
576 except (ImportError, KeyError, AttributeError):
577 raise PicklingError(
578 "Can't pickle %r: it's not found as %s.%s" %
579 (object, module, name))
580 else:
581 if klass is not object:
582 raise PicklingError(
583 "Can't pickle %r: it's not the same object as %s.%s" %
584 (object, module, name))
585
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000586 memo_len = len(memo)
587 write(GLOBAL + module + '\n' + name + '\n' +
588 self.put(memo_len))
589 memo[id(object)] = (memo_len, object)
590 dispatch[ClassType] = save_global
591 dispatch[FunctionType] = save_global
592 dispatch[BuiltinFunctionType] = save_global
Tim Peters6d6c1a32001-08-02 04:15:00 +0000593 dispatch[TypeType] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000594
Guido van Rossuma48061a1995-01-10 00:31:14 +0000595
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000596def _keep_alive(x, memo):
597 """Keeps a reference to the object x in the memo.
598
599 Because we remember objects by their id, we have
600 to assure that possibly temporary objects are kept
601 alive by referencing them.
602 We store a reference at the id of the memo, which should
603 normally not be used unless someone tries to deepcopy
604 the memo itself...
605 """
606 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000607 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000608 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000609 # aha, this is the first one :-)
610 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000611
612
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000613classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000614
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000615def whichmodule(func, funcname):
616 """Figure out the module in which a function 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.
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000621 If the function cannot be found, return __main__.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000622 """
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000623 if func in classmap:
624 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000625
626 for name, module in sys.modules.items():
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000627 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000628 continue # skip dummy package entries
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000629 if name != '__main__' and \
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000630 hasattr(module, funcname) and \
631 getattr(module, funcname) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000632 break
633 else:
634 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000635 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000636 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000637
638
639class Unpickler:
640
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000641 def __init__(self, file):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000642 """This takes a file-like object for reading a pickle data stream.
643
644 This class automatically determines whether the data stream was
645 written in binary mode or not, so it does not need a flag as in
646 the Pickler class factory.
647
648 The file-like object must have two methods, a read() method that
649 takes an integer argument, and a readline() method that requires no
650 arguments. Both methods should return a string. Thus file-like
651 object can be a file object opened for reading, a StringIO object,
652 or any other custom object that meets this interface.
653
654 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000655 self.readline = file.readline
656 self.read = file.read
657 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000658
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000659 def load(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000660 """Read a pickled object representation from the open file object.
661
662 Return the reconstituted object hierarchy specified in the file
663 object.
664
665 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000666 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000667 self.stack = []
668 self.append = self.stack.append
669 read = self.read
670 dispatch = self.dispatch
671 try:
672 while 1:
673 key = read(1)
674 dispatch[key](self)
Guido van Rossumff871742000-12-13 18:11:56 +0000675 except _Stop, stopinst:
676 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000677
678 def marker(self):
679 stack = self.stack
680 mark = self.mark
681 k = len(stack)-1
682 while stack[k] is not mark: k = k-1
683 return k
684
685 dispatch = {}
686
687 def load_eof(self):
688 raise EOFError
689 dispatch[''] = load_eof
690
691 def load_persid(self):
692 pid = self.readline()[:-1]
693 self.append(self.persistent_load(pid))
694 dispatch[PERSID] = load_persid
695
696 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000697 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000698 self.append(self.persistent_load(pid))
699 dispatch[BINPERSID] = load_binpersid
700
701 def load_none(self):
702 self.append(None)
703 dispatch[NONE] = load_none
704
705 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000706 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000707 if data == FALSE[1:]:
708 val = False
709 elif data == TRUE[1:]:
710 val = True
711 else:
712 try:
713 val = int(data)
714 except ValueError:
715 val = long(data)
716 self.append(val)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000717 dispatch[INT] = load_int
718
719 def load_binint(self):
720 self.append(mloads('i' + self.read(4)))
721 dispatch[BININT] = load_binint
722
723 def load_binint1(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000724 self.append(ord(self.read(1)))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000725 dispatch[BININT1] = load_binint1
726
727 def load_binint2(self):
728 self.append(mloads('i' + self.read(2) + '\000\000'))
729 dispatch[BININT2] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000730
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000731 def load_long(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000732 self.append(long(self.readline()[:-1], 0))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000733 dispatch[LONG] = load_long
734
735 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000736 self.append(float(self.readline()[:-1]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000737 dispatch[FLOAT] = load_float
738
Guido van Rossumd3703791998-10-22 20:15:36 +0000739 def load_binfloat(self, unpack=struct.unpack):
740 self.append(unpack('>d', self.read(8))[0])
741 dispatch[BINFLOAT] = load_binfloat
742
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000743 def load_string(self):
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000744 rep = self.readline()[:-1]
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000745 for q in _quotes:
746 if rep.startswith(q):
747 if not rep.endswith(q):
748 raise ValueError, "insecure string pickle"
749 rep = rep[len(q):-len(q)]
750 break
751 else:
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000752 raise ValueError, "insecure string pickle"
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000753 self.append(rep.decode("string-escape"))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000754 dispatch[STRING] = load_string
755
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000756 def _is_string_secure(self, s):
757 """Return true if s contains a string that is safe to eval
758
759 The definition of secure string is based on the implementation
760 in cPickle. s is secure as long as it only contains a quoted
761 string and optional trailing whitespace.
762 """
763 q = s[0]
764 if q not in ("'", '"'):
765 return 0
766 # find the closing quote
767 offset = 1
768 i = None
769 while 1:
770 try:
771 i = s.index(q, offset)
772 except ValueError:
773 # if there is an error the first time, there is no
774 # close quote
775 if offset == 1:
776 return 0
777 if s[i-1] != '\\':
778 break
779 # check to see if this one is escaped
780 nslash = 0
781 j = i - 1
782 while j >= offset and s[j] == '\\':
783 j = j - 1
784 nslash = nslash + 1
785 if nslash % 2 == 0:
786 break
787 offset = i + 1
788 for c in s[i+1:]:
789 if ord(c) > 32:
790 return 0
791 return 1
792
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000793 def load_binstring(self):
794 len = mloads('i' + self.read(4))
795 self.append(self.read(len))
796 dispatch[BINSTRING] = load_binstring
797
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000798 def load_unicode(self):
799 self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
800 dispatch[UNICODE] = load_unicode
801
802 def load_binunicode(self):
803 len = mloads('i' + self.read(4))
804 self.append(unicode(self.read(len),'utf-8'))
805 dispatch[BINUNICODE] = load_binunicode
806
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000807 def load_short_binstring(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000808 len = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000809 self.append(self.read(len))
810 dispatch[SHORT_BINSTRING] = load_short_binstring
811
812 def load_tuple(self):
813 k = self.marker()
814 self.stack[k:] = [tuple(self.stack[k+1:])]
815 dispatch[TUPLE] = load_tuple
816
817 def load_empty_tuple(self):
818 self.stack.append(())
819 dispatch[EMPTY_TUPLE] = load_empty_tuple
820
821 def load_empty_list(self):
822 self.stack.append([])
823 dispatch[EMPTY_LIST] = load_empty_list
824
825 def load_empty_dictionary(self):
826 self.stack.append({})
827 dispatch[EMPTY_DICT] = load_empty_dictionary
828
829 def load_list(self):
830 k = self.marker()
831 self.stack[k:] = [self.stack[k+1:]]
832 dispatch[LIST] = load_list
833
834 def load_dict(self):
835 k = self.marker()
836 d = {}
837 items = self.stack[k+1:]
838 for i in range(0, len(items), 2):
839 key = items[i]
840 value = items[i+1]
841 d[key] = value
842 self.stack[k:] = [d]
843 dispatch[DICT] = load_dict
844
845 def load_inst(self):
846 k = self.marker()
847 args = tuple(self.stack[k+1:])
848 del self.stack[k:]
849 module = self.readline()[:-1]
850 name = self.readline()[:-1]
851 klass = self.find_class(module, name)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000852 instantiated = 0
853 if (not args and type(klass) is ClassType and
854 not hasattr(klass, "__getinitargs__")):
855 try:
856 value = _EmptyClass()
857 value.__class__ = klass
Guido van Rossumb19e2a31998-04-13 18:08:45 +0000858 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000859 except RuntimeError:
860 # In restricted execution, assignment to inst.__class__ is
861 # prohibited
862 pass
863 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +0000864 try:
Barry Warsawbf4d9592001-11-15 23:42:58 +0000865 if not hasattr(klass, '__safe_for_unpickling__'):
866 raise UnpicklingError('%s is not safe for unpickling' %
867 klass)
Guido van Rossum743d17e1998-09-15 20:25:57 +0000868 value = apply(klass, args)
869 except TypeError, err:
870 raise TypeError, "in constructor for %s: %s" % (
871 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000872 self.append(value)
873 dispatch[INST] = load_inst
874
875 def load_obj(self):
876 stack = self.stack
877 k = self.marker()
878 klass = stack[k + 1]
879 del stack[k + 1]
Tim Peters2344fae2001-01-15 00:50:52 +0000880 args = tuple(stack[k + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000881 del stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000882 instantiated = 0
883 if (not args and type(klass) is ClassType and
884 not hasattr(klass, "__getinitargs__")):
885 try:
886 value = _EmptyClass()
887 value.__class__ = klass
888 instantiated = 1
889 except RuntimeError:
890 # In restricted execution, assignment to inst.__class__ is
891 # prohibited
892 pass
893 if not instantiated:
894 value = apply(klass, args)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000895 self.append(value)
Tim Peters2344fae2001-01-15 00:50:52 +0000896 dispatch[OBJ] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000897
898 def load_global(self):
899 module = self.readline()[:-1]
900 name = self.readline()[:-1]
901 klass = self.find_class(module, name)
902 self.append(klass)
903 dispatch[GLOBAL] = load_global
904
905 def find_class(self, module, name):
Barry Warsawbf4d9592001-11-15 23:42:58 +0000906 __import__(module)
907 mod = sys.modules[module]
908 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000909 return klass
910
911 def load_reduce(self):
912 stack = self.stack
913
914 callable = stack[-2]
915 arg_tup = stack[-1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000916 del stack[-2:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000917
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000918 if type(callable) is not ClassType:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000919 if not callable in safe_constructors:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000920 try:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000921 safe = callable.__safe_for_unpickling__
922 except AttributeError:
923 safe = None
Guido van Rossuma48061a1995-01-10 00:31:14 +0000924
Tim Petersc32d8242001-04-10 02:48:53 +0000925 if not safe:
Tim Peters2344fae2001-01-15 00:50:52 +0000926 raise UnpicklingError, "%s is not safe for " \
927 "unpickling" % callable
Guido van Rossuma48061a1995-01-10 00:31:14 +0000928
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000929 if arg_tup is None:
Raymond Hettinger97394bc2002-05-21 17:22:02 +0000930 import warnings
931 warnings.warn("The None return argument form of __reduce__ is "
932 "deprecated. Return a tuple of arguments instead.",
Tim Peters8ac14952002-05-23 15:15:30 +0000933 DeprecationWarning)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000934 value = callable.__basicnew__()
935 else:
936 value = apply(callable, arg_tup)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000937 self.append(value)
938 dispatch[REDUCE] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +0000939
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000940 def load_pop(self):
941 del self.stack[-1]
942 dispatch[POP] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +0000943
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000944 def load_pop_mark(self):
945 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000946 del self.stack[k:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000947 dispatch[POP_MARK] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +0000948
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000949 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +0000950 self.append(self.stack[-1])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000951 dispatch[DUP] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +0000952
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000953 def load_get(self):
954 self.append(self.memo[self.readline()[:-1]])
955 dispatch[GET] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +0000956
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000957 def load_binget(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000958 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000959 self.append(self.memo[`i`])
960 dispatch[BINGET] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +0000961
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000962 def load_long_binget(self):
963 i = mloads('i' + self.read(4))
964 self.append(self.memo[`i`])
965 dispatch[LONG_BINGET] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +0000966
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000967 def load_put(self):
968 self.memo[self.readline()[:-1]] = self.stack[-1]
969 dispatch[PUT] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +0000970
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000971 def load_binput(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000972 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000973 self.memo[`i`] = self.stack[-1]
974 dispatch[BINPUT] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +0000975
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000976 def load_long_binput(self):
977 i = mloads('i' + self.read(4))
978 self.memo[`i`] = self.stack[-1]
979 dispatch[LONG_BINPUT] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +0000980
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000981 def load_append(self):
982 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000983 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000984 list = stack[-1]
985 list.append(value)
986 dispatch[APPEND] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +0000987
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000988 def load_appends(self):
989 stack = self.stack
990 mark = self.marker()
991 list = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000992 for i in range(mark + 1, len(stack)):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000993 list.append(stack[i])
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000994
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000995 del stack[mark:]
996 dispatch[APPENDS] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +0000997
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000998 def load_setitem(self):
999 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001000 value = stack.pop()
1001 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001002 dict = stack[-1]
1003 dict[key] = value
1004 dispatch[SETITEM] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001005
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001006 def load_setitems(self):
1007 stack = self.stack
1008 mark = self.marker()
1009 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001010 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001011 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001012
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001013 del stack[mark:]
1014 dispatch[SETITEMS] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001015
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001016 def load_build(self):
1017 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001018 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001019 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):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001041 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001042 raise _Stop(value)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001043 dispatch[STOP] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001044
Guido van Rossume467be61997-12-05 19:42:42 +00001045# Helper class for load_inst/load_obj
1046
1047class _EmptyClass:
1048 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001049
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001050# Shorthands
1051
Jeremy Hyltonabe2c622001-10-15 21:29:28 +00001052try:
1053 from cStringIO import StringIO
1054except ImportError:
1055 from StringIO import StringIO
Guido van Rossumc7c5e691996-07-22 22:26:07 +00001056
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001057def dump(object, file, bin = 0):
1058 Pickler(file, bin).dump(object)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001059
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001060def dumps(object, bin = 0):
1061 file = StringIO()
1062 Pickler(file, bin).dump(object)
1063 return file.getvalue()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001064
1065def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001066 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001067
1068def loads(str):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001069 file = StringIO(str)
1070 return Unpickler(file).load()