blob: 4d7a5bec2b01b23df3f1f40192bd535a8f38bed7 [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
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000195 def put(self, i):
Tim Petersc32d8242001-04-10 02:48:53 +0000196 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000197 s = mdumps(i)[1:]
Tim Petersc32d8242001-04-10 02:48:53 +0000198 if i < 256:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000199 return BINPUT + s[0]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000200
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000201 return LONG_BINPUT + s
Guido van Rossuma48061a1995-01-10 00:31:14 +0000202
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000203 return PUT + `i` + '\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000204
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000205 def get(self, i):
Tim Petersc32d8242001-04-10 02:48:53 +0000206 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000207 s = mdumps(i)[1:]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000208
Tim Petersc32d8242001-04-10 02:48:53 +0000209 if i < 256:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000210 return BINGET + s[0]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000211
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000212 return LONG_BINGET + s
Guido van Rossuma48061a1995-01-10 00:31:14 +0000213
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000214 return GET + `i` + '\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000215
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000216 def save(self, object):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000217 memo = self.memo
Guido van Rossuma48061a1995-01-10 00:31:14 +0000218
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000219 pid = self.persistent_id(object)
220 if pid is not None:
221 self.save_pers(pid)
222 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000223
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000224 d = id(object)
Tim Peters2344fae2001-01-15 00:50:52 +0000225
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000226 t = type(object)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000227
Tim Petersc32d8242001-04-10 02:48:53 +0000228 if (t is TupleType) and (len(object) == 0):
229 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000230 self.save_empty_tuple(object)
231 else:
232 self.save_tuple(object)
233 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000234
Raymond Hettinger54f02222002-06-01 14:18:47 +0000235 if d in memo:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000236 self.write(self.get(memo[d][0]))
237 return
238
239 try:
240 f = self.dispatch[t]
241 except KeyError:
Guido van Rossum85ee4912002-03-26 00:51:56 +0000242 try:
243 issc = issubclass(t, TypeType)
244 except TypeError: # t is not a class
245 issc = 0
246 if issc:
Guido van Rossumf048a8f2001-12-19 16:55:02 +0000247 self.save_global(object)
248 return
249
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000250 try:
251 reduce = dispatch_table[t]
252 except KeyError:
253 try:
254 reduce = object.__reduce__
255 except AttributeError:
256 raise PicklingError, \
Guido van Rossum08a92cb1999-10-10 21:14:25 +0000257 "can't pickle %s object: %s" % (`t.__name__`,
258 `object`)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000259 else:
260 tup = reduce()
261 else:
262 tup = reduce(object)
263
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000264 if type(tup) is StringType:
265 self.save_global(object, tup)
266 return
Guido van Rossumd1f49841997-12-10 23:40:18 +0000267
Tim Petersc32d8242001-04-10 02:48:53 +0000268 if type(tup) is not TupleType:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000269 raise PicklingError, "Value returned by %s must be a " \
270 "tuple" % reduce
271
272 l = len(tup)
Tim Peters2344fae2001-01-15 00:50:52 +0000273
Tim Petersc32d8242001-04-10 02:48:53 +0000274 if (l != 2) and (l != 3):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000275 raise PicklingError, "tuple returned by %s must contain " \
276 "only two or three elements" % reduce
277
278 callable = tup[0]
279 arg_tup = tup[1]
Tim Peters2344fae2001-01-15 00:50:52 +0000280
Tim Petersc32d8242001-04-10 02:48:53 +0000281 if l > 2:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000282 state = tup[2]
283 else:
284 state = None
285
Guido van Rossumd1f49841997-12-10 23:40:18 +0000286 if type(arg_tup) is not TupleType and arg_tup is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000287 raise PicklingError, "Second element of tuple returned " \
288 "by %s must be a tuple" % reduce
289
Tim Peters2344fae2001-01-15 00:50:52 +0000290 self.save_reduce(callable, arg_tup, state)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000291 memo_len = len(memo)
292 self.write(self.put(memo_len))
293 memo[d] = (memo_len, object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000294 return
295
296 f(self, object)
297
298 def persistent_id(self, object):
299 return None
300
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000301 def save_pers(self, pid):
Tim Petersc32d8242001-04-10 02:48:53 +0000302 if not self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000303 self.write(PERSID + str(pid) + '\n')
304 else:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000305 self.save(pid)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000306 self.write(BINPERSID)
307
Jeremy Hylton3422c992003-01-24 19:29:52 +0000308 def save_reduce(self, acallable, arg_tup, state = None):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000309 write = self.write
310 save = self.save
311
Jeremy Hylton3422c992003-01-24 19:29:52 +0000312 if not callable(acallable):
313 raise PicklingError("__reduce__() must return callable as "
314 "first argument, not %s" % `acallable`)
Tim Peters22a449a2003-01-27 20:16:36 +0000315
Jeremy Hylton3422c992003-01-24 19:29:52 +0000316 save(acallable)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000317 save(arg_tup)
318 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000319
Tim Petersc32d8242001-04-10 02:48:53 +0000320 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000321 save(state)
322 write(BUILD)
323
324 dispatch = {}
325
326 def save_none(self, object):
327 self.write(NONE)
328 dispatch[NoneType] = save_none
329
Guido van Rossum77f6a652002-04-03 22:41:51 +0000330 def save_bool(self, object):
331 if object:
332 self.write(TRUE)
333 else:
334 self.write(FALSE)
335 dispatch[bool] = save_bool
336
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000337 def save_int(self, object):
Tim Petersc32d8242001-04-10 02:48:53 +0000338 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000339 # If the int is small enough to fit in a signed 4-byte 2's-comp
340 # format, we can store it more efficiently than the general
341 # case.
342 high_bits = object >> 31 # note that Python shift sign-extends
343 if high_bits == 0 or high_bits == -1:
344 # All high bits are copies of bit 2**31, so the value
345 # fits in a 4-byte signed int.
346 i = mdumps(object)[1:]
347 assert len(i) == 4
348 if i[-2:] == '\000\000': # fits in 2-byte unsigned int
349 if i[-3] == '\000': # fits in 1-byte unsigned int
350 self.write(BININT1 + i[0])
351 else:
352 self.write(BININT2 + i[:2])
353 else:
354 self.write(BININT + i)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000355 return
Tim Peters44714002001-04-10 05:02:52 +0000356 # Text pickle, or int too big to fit in signed 4-byte format.
357 self.write(INT + `object` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000358 dispatch[IntType] = save_int
359
360 def save_long(self, object):
361 self.write(LONG + `object` + '\n')
362 dispatch[LongType] = save_long
363
Guido van Rossumd3703791998-10-22 20:15:36 +0000364 def save_float(self, object, pack=struct.pack):
365 if self.bin:
366 self.write(BINFLOAT + pack('>d', object))
367 else:
368 self.write(FLOAT + `object` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000369 dispatch[FloatType] = save_float
370
371 def save_string(self, object):
Tim Petersc32d8242001-04-10 02:48:53 +0000372 if self.bin:
Tim Petersbbf63cd2003-01-27 21:15:36 +0000373 n = len(object)
374 if n < 256:
375 self.write(SHORT_BINSTRING + chr(n) + object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000376 else:
Tim Petersbbf63cd2003-01-27 21:15:36 +0000377 self.write(BINSTRING + mdumps(n)[1:] + object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000378 else:
379 self.write(STRING + `object` + '\n')
Jeremy Hylton3422c992003-01-24 19:29:52 +0000380 self.memoize(object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000381 dispatch[StringType] = save_string
382
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000383 def save_unicode(self, object):
Tim Petersc32d8242001-04-10 02:48:53 +0000384 if self.bin:
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000385 encoding = object.encode('utf-8')
Tim Petersbbf63cd2003-01-27 21:15:36 +0000386 n = len(encoding)
387 s = mdumps(n)[1:]
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000388 self.write(BINUNICODE + s + encoding)
389 else:
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000390 object = object.replace("\\", "\\u005c")
391 object = object.replace("\n", "\\u000a")
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000392 self.write(UNICODE + object.encode('raw-unicode-escape') + '\n')
Jeremy Hylton3422c992003-01-24 19:29:52 +0000393 self.memoize(object)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000394 dispatch[UnicodeType] = save_unicode
395
Guido van Rossum31584cb2001-01-22 14:53:29 +0000396 if StringType == UnicodeType:
397 # This is true for Jython
398 def save_string(self, object):
Guido van Rossum31584cb2001-01-22 14:53:29 +0000399 unicode = object.isunicode()
400
Tim Petersc32d8242001-04-10 02:48:53 +0000401 if self.bin:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000402 if unicode:
403 object = object.encode("utf-8")
404 l = len(object)
405 s = mdumps(l)[1:]
Tim Petersc32d8242001-04-10 02:48:53 +0000406 if l < 256 and not unicode:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000407 self.write(SHORT_BINSTRING + s[0] + object)
408 else:
409 if unicode:
410 self.write(BINUNICODE + s + object)
411 else:
412 self.write(BINSTRING + s + object)
413 else:
Tim Peters658cba62001-02-09 20:06:00 +0000414 if unicode:
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000415 object = object.replace("\\", "\\u005c")
416 object = object.replace("\n", "\\u000a")
Guido van Rossum31584cb2001-01-22 14:53:29 +0000417 object = object.encode('raw-unicode-escape')
418 self.write(UNICODE + object + '\n')
419 else:
420 self.write(STRING + `object` + '\n')
Jeremy Hylton3422c992003-01-24 19:29:52 +0000421 self.memoize(object)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000422 dispatch[StringType] = save_string
Tim Peters658cba62001-02-09 20:06:00 +0000423
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000424 def save_tuple(self, object):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000425 write = self.write
426 save = self.save
427 memo = self.memo
428
429 d = id(object)
430
431 write(MARK)
432
433 for element in object:
434 save(element)
435
Raymond Hettinger54f02222002-06-01 14:18:47 +0000436 if len(object) and d in memo:
Tim Petersc32d8242001-04-10 02:48:53 +0000437 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000438 write(POP_MARK + self.get(memo[d][0]))
439 return
Tim Peters2344fae2001-01-15 00:50:52 +0000440
Guido van Rossum599174f1998-03-31 16:30:28 +0000441 write(POP * (len(object) + 1) + self.get(memo[d][0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000442 return
443
444 memo_len = len(memo)
445 self.write(TUPLE + self.put(memo_len))
446 memo[d] = (memo_len, object)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000447
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000448 dispatch[TupleType] = save_tuple
449
450 def save_empty_tuple(self, object):
451 self.write(EMPTY_TUPLE)
452
453 def save_list(self, object):
454 d = id(object)
455
456 write = self.write
457 save = self.save
458 memo = self.memo
459
Tim Petersc32d8242001-04-10 02:48:53 +0000460 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000461 write(EMPTY_LIST)
462 else:
463 write(MARK + LIST)
464
Jeremy Hylton3422c992003-01-24 19:29:52 +0000465 self.memoize(object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000466
467 using_appends = (self.bin and (len(object) > 1))
468
Tim Petersc32d8242001-04-10 02:48:53 +0000469 if using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000470 write(MARK)
471
472 for element in object:
473 save(element)
Tim Peters2344fae2001-01-15 00:50:52 +0000474
Tim Petersc32d8242001-04-10 02:48:53 +0000475 if not using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000476 write(APPEND)
477
Tim Petersc32d8242001-04-10 02:48:53 +0000478 if using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000479 write(APPENDS)
480 dispatch[ListType] = save_list
481
482 def save_dict(self, object):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000483 write = self.write
484 save = self.save
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000485
Tim Petersc32d8242001-04-10 02:48:53 +0000486 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000487 write(EMPTY_DICT)
488 else:
489 write(MARK + DICT)
490
Jeremy Hylton3422c992003-01-24 19:29:52 +0000491 self.memoize(object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000492
493 using_setitems = (self.bin and (len(object) > 1))
494
Tim Petersc32d8242001-04-10 02:48:53 +0000495 if using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000496 write(MARK)
497
498 items = object.items()
499 for key, value in items:
500 save(key)
501 save(value)
502
Tim Petersc32d8242001-04-10 02:48:53 +0000503 if not using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000504 write(SETITEM)
505
Tim Petersc32d8242001-04-10 02:48:53 +0000506 if using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000507 write(SETITEMS)
508
509 dispatch[DictionaryType] = save_dict
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000510 if not PyStringMap is None:
511 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000512
513 def save_inst(self, object):
514 d = id(object)
515 cls = object.__class__
516
517 memo = self.memo
518 write = self.write
519 save = self.save
520
521 if hasattr(object, '__getinitargs__'):
522 args = object.__getinitargs__()
523 len(args) # XXX Assert it's a sequence
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000524 _keep_alive(args, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000525 else:
526 args = ()
527
528 write(MARK)
529
Tim Petersc32d8242001-04-10 02:48:53 +0000530 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000531 save(cls)
532
533 for arg in args:
534 save(arg)
535
Jeremy Hylton3422c992003-01-24 19:29:52 +0000536 # This method does not use memoize() so that it can handle
537 # the special case for non-binary mode.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000538 memo_len = len(memo)
Tim Petersc32d8242001-04-10 02:48:53 +0000539 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000540 write(OBJ + self.put(memo_len))
541 else:
Guido van Rossum4fb5b281997-09-12 20:07:24 +0000542 write(INST + cls.__module__ + '\n' + cls.__name__ + '\n' +
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000543 self.put(memo_len))
544
545 memo[d] = (memo_len, object)
546
547 try:
548 getstate = object.__getstate__
549 except AttributeError:
550 stuff = object.__dict__
551 else:
552 stuff = getstate()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000553 _keep_alive(stuff, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000554 save(stuff)
555 write(BUILD)
556 dispatch[InstanceType] = save_inst
557
558 def save_global(self, object, name = None):
559 write = self.write
560 memo = self.memo
561
Tim Petersc32d8242001-04-10 02:48:53 +0000562 if name is None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000563 name = object.__name__
564
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000565 try:
566 module = object.__module__
567 except AttributeError:
568 module = whichmodule(object, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000569
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000570 try:
571 __import__(module)
572 mod = sys.modules[module]
573 klass = getattr(mod, name)
574 except (ImportError, KeyError, AttributeError):
575 raise PicklingError(
576 "Can't pickle %r: it's not found as %s.%s" %
577 (object, module, name))
578 else:
579 if klass is not object:
580 raise PicklingError(
581 "Can't pickle %r: it's not the same object as %s.%s" %
582 (object, module, name))
583
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000584 memo_len = len(memo)
585 write(GLOBAL + module + '\n' + name + '\n' +
586 self.put(memo_len))
587 memo[id(object)] = (memo_len, object)
588 dispatch[ClassType] = save_global
589 dispatch[FunctionType] = save_global
590 dispatch[BuiltinFunctionType] = save_global
Tim Peters6d6c1a32001-08-02 04:15:00 +0000591 dispatch[TypeType] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000592
Guido van Rossuma48061a1995-01-10 00:31:14 +0000593
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000594def _keep_alive(x, memo):
595 """Keeps a reference to the object x in the memo.
596
597 Because we remember objects by their id, we have
598 to assure that possibly temporary objects are kept
599 alive by referencing them.
600 We store a reference at the id of the memo, which should
601 normally not be used unless someone tries to deepcopy
602 the memo itself...
603 """
604 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000605 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000606 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000607 # aha, this is the first one :-)
608 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000609
610
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000611classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000612
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000613def whichmodule(func, funcname):
614 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000615
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000616 Search sys.modules for the module.
617 Cache in classmap.
618 Return a module name.
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000619 If the function cannot be found, return __main__.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000620 """
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000621 if func in classmap:
622 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000623
624 for name, module in sys.modules.items():
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000625 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000626 continue # skip dummy package entries
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000627 if name != '__main__' and \
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000628 hasattr(module, funcname) and \
629 getattr(module, funcname) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000630 break
631 else:
632 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000633 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000634 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):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000695 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000696 self.append(self.persistent_load(pid))
697 dispatch[BINPERSID] = load_binpersid
698
699 def load_none(self):
700 self.append(None)
701 dispatch[NONE] = load_none
702
703 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000704 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000705 if data == FALSE[1:]:
706 val = False
707 elif data == TRUE[1:]:
708 val = True
709 else:
710 try:
711 val = int(data)
712 except ValueError:
713 val = long(data)
714 self.append(val)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000715 dispatch[INT] = load_int
716
717 def load_binint(self):
718 self.append(mloads('i' + self.read(4)))
719 dispatch[BININT] = load_binint
720
721 def load_binint1(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000722 self.append(ord(self.read(1)))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000723 dispatch[BININT1] = load_binint1
724
725 def load_binint2(self):
726 self.append(mloads('i' + self.read(2) + '\000\000'))
727 dispatch[BININT2] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000728
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000729 def load_long(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000730 self.append(long(self.readline()[:-1], 0))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000731 dispatch[LONG] = load_long
732
733 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000734 self.append(float(self.readline()[:-1]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000735 dispatch[FLOAT] = load_float
736
Guido van Rossumd3703791998-10-22 20:15:36 +0000737 def load_binfloat(self, unpack=struct.unpack):
738 self.append(unpack('>d', self.read(8))[0])
739 dispatch[BINFLOAT] = load_binfloat
740
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000741 def load_string(self):
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000742 rep = self.readline()[:-1]
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000743 for q in _quotes:
744 if rep.startswith(q):
745 if not rep.endswith(q):
746 raise ValueError, "insecure string pickle"
747 rep = rep[len(q):-len(q)]
748 break
749 else:
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000750 raise ValueError, "insecure string pickle"
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000751 self.append(rep.decode("string-escape"))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000752 dispatch[STRING] = load_string
753
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000754 def _is_string_secure(self, s):
755 """Return true if s contains a string that is safe to eval
756
757 The definition of secure string is based on the implementation
758 in cPickle. s is secure as long as it only contains a quoted
759 string and optional trailing whitespace.
760 """
761 q = s[0]
762 if q not in ("'", '"'):
763 return 0
764 # find the closing quote
765 offset = 1
766 i = None
767 while 1:
768 try:
769 i = s.index(q, offset)
770 except ValueError:
771 # if there is an error the first time, there is no
772 # close quote
773 if offset == 1:
774 return 0
775 if s[i-1] != '\\':
776 break
777 # check to see if this one is escaped
778 nslash = 0
779 j = i - 1
780 while j >= offset and s[j] == '\\':
781 j = j - 1
782 nslash = nslash + 1
783 if nslash % 2 == 0:
784 break
785 offset = i + 1
786 for c in s[i+1:]:
787 if ord(c) > 32:
788 return 0
789 return 1
790
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000791 def load_binstring(self):
792 len = mloads('i' + self.read(4))
793 self.append(self.read(len))
794 dispatch[BINSTRING] = load_binstring
795
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000796 def load_unicode(self):
797 self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
798 dispatch[UNICODE] = load_unicode
799
800 def load_binunicode(self):
801 len = mloads('i' + self.read(4))
802 self.append(unicode(self.read(len),'utf-8'))
803 dispatch[BINUNICODE] = load_binunicode
804
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000805 def load_short_binstring(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000806 len = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000807 self.append(self.read(len))
808 dispatch[SHORT_BINSTRING] = load_short_binstring
809
810 def load_tuple(self):
811 k = self.marker()
812 self.stack[k:] = [tuple(self.stack[k+1:])]
813 dispatch[TUPLE] = load_tuple
814
815 def load_empty_tuple(self):
816 self.stack.append(())
817 dispatch[EMPTY_TUPLE] = load_empty_tuple
818
819 def load_empty_list(self):
820 self.stack.append([])
821 dispatch[EMPTY_LIST] = load_empty_list
822
823 def load_empty_dictionary(self):
824 self.stack.append({})
825 dispatch[EMPTY_DICT] = load_empty_dictionary
826
827 def load_list(self):
828 k = self.marker()
829 self.stack[k:] = [self.stack[k+1:]]
830 dispatch[LIST] = load_list
831
832 def load_dict(self):
833 k = self.marker()
834 d = {}
835 items = self.stack[k+1:]
836 for i in range(0, len(items), 2):
837 key = items[i]
838 value = items[i+1]
839 d[key] = value
840 self.stack[k:] = [d]
841 dispatch[DICT] = load_dict
842
843 def load_inst(self):
844 k = self.marker()
845 args = tuple(self.stack[k+1:])
846 del self.stack[k:]
847 module = self.readline()[:-1]
848 name = self.readline()[:-1]
849 klass = self.find_class(module, name)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000850 instantiated = 0
851 if (not args and type(klass) is ClassType and
852 not hasattr(klass, "__getinitargs__")):
853 try:
854 value = _EmptyClass()
855 value.__class__ = klass
Guido van Rossumb19e2a31998-04-13 18:08:45 +0000856 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000857 except RuntimeError:
858 # In restricted execution, assignment to inst.__class__ is
859 # prohibited
860 pass
861 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +0000862 try:
Barry Warsawbf4d9592001-11-15 23:42:58 +0000863 if not hasattr(klass, '__safe_for_unpickling__'):
864 raise UnpicklingError('%s is not safe for unpickling' %
865 klass)
Guido van Rossum743d17e1998-09-15 20:25:57 +0000866 value = apply(klass, args)
867 except TypeError, err:
868 raise TypeError, "in constructor for %s: %s" % (
869 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000870 self.append(value)
871 dispatch[INST] = load_inst
872
873 def load_obj(self):
874 stack = self.stack
875 k = self.marker()
876 klass = stack[k + 1]
877 del stack[k + 1]
Tim Peters2344fae2001-01-15 00:50:52 +0000878 args = tuple(stack[k + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000879 del stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000880 instantiated = 0
881 if (not args and type(klass) is ClassType and
882 not hasattr(klass, "__getinitargs__")):
883 try:
884 value = _EmptyClass()
885 value.__class__ = klass
886 instantiated = 1
887 except RuntimeError:
888 # In restricted execution, assignment to inst.__class__ is
889 # prohibited
890 pass
891 if not instantiated:
892 value = apply(klass, args)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000893 self.append(value)
Tim Peters2344fae2001-01-15 00:50:52 +0000894 dispatch[OBJ] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000895
896 def load_global(self):
897 module = self.readline()[:-1]
898 name = self.readline()[:-1]
899 klass = self.find_class(module, name)
900 self.append(klass)
901 dispatch[GLOBAL] = load_global
902
903 def find_class(self, module, name):
Barry Warsawbf4d9592001-11-15 23:42:58 +0000904 __import__(module)
905 mod = sys.modules[module]
906 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000907 return klass
908
909 def load_reduce(self):
910 stack = self.stack
911
912 callable = stack[-2]
913 arg_tup = stack[-1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000914 del stack[-2:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000915
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000916 if type(callable) is not ClassType:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000917 if not callable in safe_constructors:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000918 try:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000919 safe = callable.__safe_for_unpickling__
920 except AttributeError:
921 safe = None
Guido van Rossuma48061a1995-01-10 00:31:14 +0000922
Tim Petersc32d8242001-04-10 02:48:53 +0000923 if not safe:
Tim Peters2344fae2001-01-15 00:50:52 +0000924 raise UnpicklingError, "%s is not safe for " \
925 "unpickling" % callable
Guido van Rossuma48061a1995-01-10 00:31:14 +0000926
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000927 if arg_tup is None:
Raymond Hettinger97394bc2002-05-21 17:22:02 +0000928 import warnings
929 warnings.warn("The None return argument form of __reduce__ is "
930 "deprecated. Return a tuple of arguments instead.",
Tim Peters8ac14952002-05-23 15:15:30 +0000931 DeprecationWarning)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000932 value = callable.__basicnew__()
933 else:
934 value = apply(callable, arg_tup)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000935 self.append(value)
936 dispatch[REDUCE] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +0000937
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000938 def load_pop(self):
939 del self.stack[-1]
940 dispatch[POP] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +0000941
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000942 def load_pop_mark(self):
943 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000944 del self.stack[k:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000945 dispatch[POP_MARK] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +0000946
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000947 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +0000948 self.append(self.stack[-1])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000949 dispatch[DUP] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +0000950
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000951 def load_get(self):
952 self.append(self.memo[self.readline()[:-1]])
953 dispatch[GET] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +0000954
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000955 def load_binget(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000956 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000957 self.append(self.memo[`i`])
958 dispatch[BINGET] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +0000959
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000960 def load_long_binget(self):
961 i = mloads('i' + self.read(4))
962 self.append(self.memo[`i`])
963 dispatch[LONG_BINGET] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +0000964
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000965 def load_put(self):
966 self.memo[self.readline()[:-1]] = self.stack[-1]
967 dispatch[PUT] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +0000968
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000969 def load_binput(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000970 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000971 self.memo[`i`] = self.stack[-1]
972 dispatch[BINPUT] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +0000973
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000974 def load_long_binput(self):
975 i = mloads('i' + self.read(4))
976 self.memo[`i`] = self.stack[-1]
977 dispatch[LONG_BINPUT] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +0000978
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000979 def load_append(self):
980 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000981 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000982 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
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000998 value = stack.pop()
999 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001000 dict = stack[-1]
1001 dict[key] = value
1002 dispatch[SETITEM] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001003
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001004 def load_setitems(self):
1005 stack = self.stack
1006 mark = self.marker()
1007 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001008 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001009 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001010
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001011 del stack[mark:]
1012 dispatch[SETITEMS] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001013
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001014 def load_build(self):
1015 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001016 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001017 inst = stack[-1]
1018 try:
1019 setstate = inst.__setstate__
1020 except AttributeError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001021 try:
1022 inst.__dict__.update(value)
1023 except RuntimeError:
1024 # XXX In restricted execution, the instance's __dict__ is not
1025 # accessible. Use the old way of unpickling the instance
1026 # variables. This is a semantic different when unpickling in
1027 # restricted vs. unrestricted modes.
1028 for k, v in value.items():
1029 setattr(inst, k, v)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001030 else:
1031 setstate(value)
1032 dispatch[BUILD] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001033
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001034 def load_mark(self):
1035 self.append(self.mark)
1036 dispatch[MARK] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001037
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001038 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001039 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001040 raise _Stop(value)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001041 dispatch[STOP] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001042
Guido van Rossume467be61997-12-05 19:42:42 +00001043# Helper class for load_inst/load_obj
1044
1045class _EmptyClass:
1046 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001047
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001048# Shorthands
1049
Jeremy Hyltonabe2c622001-10-15 21:29:28 +00001050try:
1051 from cStringIO import StringIO
1052except ImportError:
1053 from StringIO import StringIO
Guido van Rossumc7c5e691996-07-22 22:26:07 +00001054
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001055def dump(object, file, bin = 0):
1056 Pickler(file, bin).dump(object)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001057
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001058def dumps(object, bin = 0):
1059 file = StringIO()
1060 Pickler(file, bin).dump(object)
1061 return file.getvalue()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001062
1063def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001064 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001065
1066def loads(str):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001067 file = StringIO(str)
1068 return Unpickler(file).load()