blob: 1fc1a65759f645a7e7b84b48c38dc8194cc4c80f [file] [log] [blame]
Guido van Rossum54f22ed2000-02-04 15:10:34 +00001"""Create portable serialized representations of Python objects.
Guido van Rossuma48061a1995-01-10 00:31:14 +00002
Guido van Rossume467be61997-12-05 19:42:42 +00003See module cPickle for a (much) faster implementation.
4See module copy_reg for a mechanism for registering custom picklers.
Tim Peters22a449a2003-01-27 20:16:36 +00005See module pickletools source for extensive comments.
Guido van Rossuma48061a1995-01-10 00:31:14 +00006
Guido van Rossume467be61997-12-05 19:42:42 +00007Classes:
Guido van Rossuma48061a1995-01-10 00:31:14 +00008
Guido van Rossume467be61997-12-05 19:42:42 +00009 Pickler
10 Unpickler
Guido van Rossuma48061a1995-01-10 00:31:14 +000011
Guido van Rossume467be61997-12-05 19:42:42 +000012Functions:
Guido van Rossuma48061a1995-01-10 00:31:14 +000013
Guido van Rossume467be61997-12-05 19:42:42 +000014 dump(object, file)
15 dumps(object) -> string
16 load(file) -> object
17 loads(string) -> object
Guido van Rossuma48061a1995-01-10 00:31:14 +000018
Guido van Rossume467be61997-12-05 19:42:42 +000019Misc variables:
Guido van Rossuma48061a1995-01-10 00:31:14 +000020
Fred Drakefe82acc1998-02-13 03:24:48 +000021 __version__
Guido van Rossume467be61997-12-05 19:42:42 +000022 format_version
23 compatible_formats
Guido van Rossuma48061a1995-01-10 00:31:14 +000024
Guido van Rossuma48061a1995-01-10 00:31:14 +000025"""
26
Guido van Rossum743d17e1998-09-15 20:25:57 +000027__version__ = "$Revision$" # Code version
Guido van Rossuma48061a1995-01-10 00:31:14 +000028
29from types import *
Guido van Rossum4fb5b281997-09-12 20:07:24 +000030from copy_reg import dispatch_table, safe_constructors
Guido van Rossumd3703791998-10-22 20:15:36 +000031import marshal
32import sys
33import struct
Skip Montanaro23bafc62001-02-18 03:10:09 +000034import re
Guido van Rossuma48061a1995-01-10 00:31:14 +000035
Skip Montanaro352674d2001-02-07 23:14:30 +000036__all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler",
37 "Unpickler", "dump", "dumps", "load", "loads"]
38
Guido van Rossumd3703791998-10-22 20:15:36 +000039format_version = "1.3" # File format version we write
40compatible_formats = ["1.0", "1.1", "1.2"] # Old format versions we can read
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000041
42mdumps = marshal.dumps
43mloads = marshal.loads
Guido van Rossum0c891ce1995-03-14 15:09:05 +000044
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000045class PickleError(Exception):
Neal Norwitzefbb67b2002-05-30 12:12:04 +000046 """A common base class for the other pickling exceptions."""
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000047 pass
48
49class PicklingError(PickleError):
50 """This exception is raised when an unpicklable object is passed to the
51 dump() method.
52
53 """
54 pass
55
56class UnpicklingError(PickleError):
57 """This exception is raised when there is a problem unpickling an object,
58 such as a security violation.
59
60 Note that other exceptions may also be raised during unpickling, including
61 (but not necessarily limited to) AttributeError, EOFError, ImportError,
62 and IndexError.
63
64 """
65 pass
Guido van Rossum7849da81995-03-09 14:08:35 +000066
Guido van Rossumff871742000-12-13 18:11:56 +000067class _Stop(Exception):
68 def __init__(self, value):
69 self.value = value
70
Jeremy Hylton2b9d0291998-05-27 22:38:22 +000071try:
72 from org.python.core import PyStringMap
73except ImportError:
74 PyStringMap = None
75
Guido van Rossumdbb718f2001-09-21 19:22:34 +000076try:
77 UnicodeType
78except NameError:
79 UnicodeType = None
80
Tim Peters22a449a2003-01-27 20:16:36 +000081# Pickle opcodes. See pickletools.py for extensive docs. The listing
82# here is in kind-of alphabetical order of 1-character pickle code.
83# pickletools groups them by purpose.
Guido van Rossumdbb718f2001-09-21 19:22:34 +000084
Tim Peters22a449a2003-01-27 20:16:36 +000085MARK = '(' # push special markobject on stack
86STOP = '.' # every pickle ends with STOP
87POP = '0' # discard topmost stack item
88POP_MARK = '1' # discard stack top through topmost markobject
89DUP = '2' # duplicate top stack item
90FLOAT = 'F' # push float object; decimal string argument
91INT = 'I' # push integer or bool; decimal string argument
92BININT = 'J' # push four-byte signed int
93BININT1 = 'K' # push 1-byte unsigned int
94LONG = 'L' # push long; decimal string argument
95BININT2 = 'M' # push 2-byte unsigned int
96NONE = 'N' # push None
97PERSID = 'P' # push persistent object; id is taken from string arg
98BINPERSID = 'Q' # " " " ; " " " " stack
99REDUCE = 'R' # apply callable to argtuple, both on stack
100STRING = 'S' # push string; NL-terminated string argument
101BINSTRING = 'T' # push string; counted binary string argument
102SHORT_BINSTRING = 'U' # " " ; " " " " < 256 bytes
103UNICODE = 'V' # push Unicode string; raw-unicode-escaped'd argument
104BINUNICODE = 'X' # " " " ; counted UTF-8 string argument
105APPEND = 'a' # append stack top to list below it
106BUILD = 'b' # call __setstate__ or __dict__.update()
107GLOBAL = 'c' # push self.find_class(modname, name); 2 string args
108DICT = 'd' # build a dict from stack items
109EMPTY_DICT = '}' # push empty dict
110APPENDS = 'e' # extend list on stack by topmost stack slice
111GET = 'g' # push item from memo on stack; index is string arg
112BINGET = 'h' # " " " " " " ; " " 1-byte arg
113INST = 'i' # build & push class instance
114LONG_BINGET = 'j' # push item from memo on stack; index is 4-byte arg
115LIST = 'l' # build list from topmost stack items
116EMPTY_LIST = ']' # push empty list
117OBJ = 'o' # build & push class instance
118PUT = 'p' # store stack top in memo; index is string arg
119BINPUT = 'q' # " " " " " ; " " 1-byte arg
120LONG_BINPUT = 'r' # " " " " " ; " " 4-byte arg
121SETITEM = 's' # add key+value pair to dict
122TUPLE = 't' # build tuple from topmost stack items
123EMPTY_TUPLE = ')' # push empty tuple
124SETITEMS = 'u' # modify dict by adding topmost key+value pairs
125BINFLOAT = 'G' # push float; arg is 8-byte float encoding
126
127TRUE = 'I01\n' # not an opcode; see INT docs in pickletools.py
128FALSE = 'I00\n' # not an opcode; see INT docs in pickletools.py
Guido van Rossum77f6a652002-04-03 22:41:51 +0000129
Guido van Rossuma48061a1995-01-10 00:31:14 +0000130
Skip Montanaro23bafc62001-02-18 03:10:09 +0000131__all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
Neal Norwitzd5ba4ae2002-02-11 18:12:06 +0000132del x
Skip Montanaro23bafc62001-02-18 03:10:09 +0000133
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000134_quotes = ["'", '"']
135
Guido van Rossuma48061a1995-01-10 00:31:14 +0000136class Pickler:
137
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000138 def __init__(self, file, bin = 0):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000139 """This takes a file-like object for writing a pickle data stream.
140
141 The optional bin parameter if true, tells the pickler to use the more
142 efficient binary pickle format, otherwise the ASCII format is used
143 (this is the default).
144
145 The file parameter must have a write() method that accepts a single
146 string argument. It can thus be an open file object, a StringIO
147 object, or any other custom object that meets this interface.
148
149 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000150 self.write = file.write
151 self.memo = {}
152 self.bin = bin
Guido van Rossuma48061a1995-01-10 00:31:14 +0000153
Fred Drake7f781c92002-05-01 20:33:53 +0000154 def clear_memo(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000155 """Clears the pickler's "memo".
156
157 The memo is the data structure that remembers which objects the
158 pickler has already seen, so that shared or recursive objects pickled
159 by reference and not by value. This method is useful when re-using
160 picklers.
161
162 """
Fred Drake7f781c92002-05-01 20:33:53 +0000163 self.memo.clear()
164
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000165 def dump(self, object):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000166 """Write a pickled representation of object to the open file object.
167
168 Either the binary or ASCII format will be used, depending on the
169 value of the bin flag passed to the constructor.
170
171 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000172 self.save(object)
173 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000174
Jeremy Hylton3422c992003-01-24 19:29:52 +0000175 def memoize(self, obj):
176 """Store an object in the memo."""
177
178 # The memo is a dictionary mapping object ids to 2-tuples
179 # that contains the memo value and the object being memoized.
180 # The memo value is written to the pickle and will become
181 # the key in the Unpickler's memo. The object is stored in the
182 # memo so that transient objects are kept alive during pickling.
183
184 # The use of the memo length as the memo value is just a convention.
185 # The only requirement is that the memo values by unique.
186 d = id(obj)
187 memo_len = len(self.memo)
188 self.write(self.put(memo_len))
189 self.memo[d] = memo_len, obj
190
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000191 def put(self, i):
Tim Petersc32d8242001-04-10 02:48:53 +0000192 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000193 s = mdumps(i)[1:]
Tim Petersc32d8242001-04-10 02:48:53 +0000194 if i < 256:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000195 return BINPUT + s[0]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000196
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000197 return LONG_BINPUT + s
Guido van Rossuma48061a1995-01-10 00:31:14 +0000198
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000199 return PUT + `i` + '\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000200
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000201 def get(self, i):
Tim Petersc32d8242001-04-10 02:48:53 +0000202 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000203 s = mdumps(i)[1:]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000204
Tim Petersc32d8242001-04-10 02:48:53 +0000205 if i < 256:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000206 return BINGET + s[0]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000207
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000208 return LONG_BINGET + s
Guido van Rossuma48061a1995-01-10 00:31:14 +0000209
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000210 return GET + `i` + '\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000211
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000212 def save(self, object):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000213 memo = self.memo
Guido van Rossuma48061a1995-01-10 00:31:14 +0000214
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000215 pid = self.persistent_id(object)
216 if pid is not None:
217 self.save_pers(pid)
218 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000219
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000220 d = id(object)
Tim Peters2344fae2001-01-15 00:50:52 +0000221
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000222 t = type(object)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000223
Tim Petersc32d8242001-04-10 02:48:53 +0000224 if (t is TupleType) and (len(object) == 0):
225 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000226 self.save_empty_tuple(object)
227 else:
228 self.save_tuple(object)
229 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000230
Raymond Hettinger54f02222002-06-01 14:18:47 +0000231 if d in memo:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000232 self.write(self.get(memo[d][0]))
233 return
234
235 try:
236 f = self.dispatch[t]
237 except KeyError:
Guido van Rossum85ee4912002-03-26 00:51:56 +0000238 try:
239 issc = issubclass(t, TypeType)
240 except TypeError: # t is not a class
241 issc = 0
242 if issc:
Guido van Rossumf048a8f2001-12-19 16:55:02 +0000243 self.save_global(object)
244 return
245
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000246 try:
247 reduce = dispatch_table[t]
248 except KeyError:
249 try:
250 reduce = object.__reduce__
251 except AttributeError:
252 raise PicklingError, \
Guido van Rossum08a92cb1999-10-10 21:14:25 +0000253 "can't pickle %s object: %s" % (`t.__name__`,
254 `object`)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000255 else:
256 tup = reduce()
257 else:
258 tup = reduce(object)
259
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000260 if type(tup) is StringType:
261 self.save_global(object, tup)
262 return
Guido van Rossumd1f49841997-12-10 23:40:18 +0000263
Tim Petersc32d8242001-04-10 02:48:53 +0000264 if type(tup) is not TupleType:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000265 raise PicklingError, "Value returned by %s must be a " \
266 "tuple" % reduce
267
268 l = len(tup)
Tim Peters2344fae2001-01-15 00:50:52 +0000269
Tim Petersc32d8242001-04-10 02:48:53 +0000270 if (l != 2) and (l != 3):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000271 raise PicklingError, "tuple returned by %s must contain " \
272 "only two or three elements" % reduce
273
274 callable = tup[0]
275 arg_tup = tup[1]
Tim Peters2344fae2001-01-15 00:50:52 +0000276
Tim Petersc32d8242001-04-10 02:48:53 +0000277 if l > 2:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000278 state = tup[2]
279 else:
280 state = None
281
Guido van Rossumd1f49841997-12-10 23:40:18 +0000282 if type(arg_tup) is not TupleType and arg_tup is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000283 raise PicklingError, "Second element of tuple returned " \
284 "by %s must be a tuple" % reduce
285
Tim Peters2344fae2001-01-15 00:50:52 +0000286 self.save_reduce(callable, arg_tup, state)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000287 memo_len = len(memo)
288 self.write(self.put(memo_len))
289 memo[d] = (memo_len, object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000290 return
291
292 f(self, object)
293
294 def persistent_id(self, object):
295 return None
296
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000297 def save_pers(self, pid):
Tim Petersc32d8242001-04-10 02:48:53 +0000298 if not self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000299 self.write(PERSID + str(pid) + '\n')
300 else:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000301 self.save(pid)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000302 self.write(BINPERSID)
303
Jeremy Hylton3422c992003-01-24 19:29:52 +0000304 def save_reduce(self, acallable, arg_tup, state = None):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000305 write = self.write
306 save = self.save
307
Jeremy Hylton3422c992003-01-24 19:29:52 +0000308 if not callable(acallable):
309 raise PicklingError("__reduce__() must return callable as "
310 "first argument, not %s" % `acallable`)
Tim Peters22a449a2003-01-27 20:16:36 +0000311
Jeremy Hylton3422c992003-01-24 19:29:52 +0000312 save(acallable)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000313 save(arg_tup)
314 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000315
Tim Petersc32d8242001-04-10 02:48:53 +0000316 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000317 save(state)
318 write(BUILD)
319
320 dispatch = {}
321
322 def save_none(self, object):
323 self.write(NONE)
324 dispatch[NoneType] = save_none
325
Guido van Rossum77f6a652002-04-03 22:41:51 +0000326 def save_bool(self, object):
327 if object:
328 self.write(TRUE)
329 else:
330 self.write(FALSE)
331 dispatch[bool] = save_bool
332
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000333 def save_int(self, object):
Tim Petersc32d8242001-04-10 02:48:53 +0000334 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000335 # If the int is small enough to fit in a signed 4-byte 2's-comp
336 # format, we can store it more efficiently than the general
337 # case.
338 high_bits = object >> 31 # note that Python shift sign-extends
339 if high_bits == 0 or high_bits == -1:
340 # All high bits are copies of bit 2**31, so the value
341 # fits in a 4-byte signed int.
342 i = mdumps(object)[1:]
343 assert len(i) == 4
344 if i[-2:] == '\000\000': # fits in 2-byte unsigned int
345 if i[-3] == '\000': # fits in 1-byte unsigned int
346 self.write(BININT1 + i[0])
347 else:
348 self.write(BININT2 + i[:2])
349 else:
350 self.write(BININT + i)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000351 return
Tim Peters44714002001-04-10 05:02:52 +0000352 # Text pickle, or int too big to fit in signed 4-byte format.
353 self.write(INT + `object` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000354 dispatch[IntType] = save_int
355
356 def save_long(self, object):
357 self.write(LONG + `object` + '\n')
358 dispatch[LongType] = save_long
359
Guido van Rossumd3703791998-10-22 20:15:36 +0000360 def save_float(self, object, pack=struct.pack):
361 if self.bin:
362 self.write(BINFLOAT + pack('>d', object))
363 else:
364 self.write(FLOAT + `object` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000365 dispatch[FloatType] = save_float
366
367 def save_string(self, object):
Tim Petersc32d8242001-04-10 02:48:53 +0000368 if self.bin:
Tim Petersbbf63cd2003-01-27 21:15:36 +0000369 n = len(object)
370 if n < 256:
371 self.write(SHORT_BINSTRING + chr(n) + object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000372 else:
Tim Petersbbf63cd2003-01-27 21:15:36 +0000373 self.write(BINSTRING + mdumps(n)[1:] + object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000374 else:
375 self.write(STRING + `object` + '\n')
Jeremy Hylton3422c992003-01-24 19:29:52 +0000376 self.memoize(object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000377 dispatch[StringType] = save_string
378
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000379 def save_unicode(self, object):
Tim Petersc32d8242001-04-10 02:48:53 +0000380 if self.bin:
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000381 encoding = object.encode('utf-8')
Tim Petersbbf63cd2003-01-27 21:15:36 +0000382 n = len(encoding)
383 s = mdumps(n)[1:]
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000384 self.write(BINUNICODE + s + encoding)
385 else:
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000386 object = object.replace("\\", "\\u005c")
387 object = object.replace("\n", "\\u000a")
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000388 self.write(UNICODE + object.encode('raw-unicode-escape') + '\n')
Jeremy Hylton3422c992003-01-24 19:29:52 +0000389 self.memoize(object)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000390 dispatch[UnicodeType] = save_unicode
391
Guido van Rossum31584cb2001-01-22 14:53:29 +0000392 if StringType == UnicodeType:
393 # This is true for Jython
394 def save_string(self, object):
Guido van Rossum31584cb2001-01-22 14:53:29 +0000395 unicode = object.isunicode()
396
Tim Petersc32d8242001-04-10 02:48:53 +0000397 if self.bin:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000398 if unicode:
399 object = object.encode("utf-8")
400 l = len(object)
401 s = mdumps(l)[1:]
Tim Petersc32d8242001-04-10 02:48:53 +0000402 if l < 256 and not unicode:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000403 self.write(SHORT_BINSTRING + s[0] + object)
404 else:
405 if unicode:
406 self.write(BINUNICODE + s + object)
407 else:
408 self.write(BINSTRING + s + object)
409 else:
Tim Peters658cba62001-02-09 20:06:00 +0000410 if unicode:
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000411 object = object.replace("\\", "\\u005c")
412 object = object.replace("\n", "\\u000a")
Guido van Rossum31584cb2001-01-22 14:53:29 +0000413 object = object.encode('raw-unicode-escape')
414 self.write(UNICODE + object + '\n')
415 else:
416 self.write(STRING + `object` + '\n')
Jeremy Hylton3422c992003-01-24 19:29:52 +0000417 self.memoize(object)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000418 dispatch[StringType] = save_string
Tim Peters658cba62001-02-09 20:06:00 +0000419
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000420 def save_tuple(self, object):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000421 write = self.write
422 save = self.save
423 memo = self.memo
424
425 d = id(object)
426
427 write(MARK)
428
429 for element in object:
430 save(element)
431
Raymond Hettinger54f02222002-06-01 14:18:47 +0000432 if len(object) and d in memo:
Tim Petersc32d8242001-04-10 02:48:53 +0000433 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000434 write(POP_MARK + self.get(memo[d][0]))
435 return
Tim Peters2344fae2001-01-15 00:50:52 +0000436
Guido van Rossum599174f1998-03-31 16:30:28 +0000437 write(POP * (len(object) + 1) + self.get(memo[d][0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000438 return
439
440 memo_len = len(memo)
441 self.write(TUPLE + self.put(memo_len))
442 memo[d] = (memo_len, object)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000443
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000444 dispatch[TupleType] = save_tuple
445
446 def save_empty_tuple(self, object):
447 self.write(EMPTY_TUPLE)
448
449 def save_list(self, object):
450 d = id(object)
451
452 write = self.write
453 save = self.save
454 memo = self.memo
455
Tim Petersc32d8242001-04-10 02:48:53 +0000456 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000457 write(EMPTY_LIST)
458 else:
459 write(MARK + LIST)
460
Jeremy Hylton3422c992003-01-24 19:29:52 +0000461 self.memoize(object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000462
463 using_appends = (self.bin and (len(object) > 1))
464
Tim Petersc32d8242001-04-10 02:48:53 +0000465 if using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000466 write(MARK)
467
468 for element in object:
469 save(element)
Tim Peters2344fae2001-01-15 00:50:52 +0000470
Tim Petersc32d8242001-04-10 02:48:53 +0000471 if not using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000472 write(APPEND)
473
Tim Petersc32d8242001-04-10 02:48:53 +0000474 if using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000475 write(APPENDS)
476 dispatch[ListType] = save_list
477
478 def save_dict(self, object):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000479 write = self.write
480 save = self.save
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000481
Tim Petersc32d8242001-04-10 02:48:53 +0000482 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000483 write(EMPTY_DICT)
484 else:
485 write(MARK + DICT)
486
Jeremy Hylton3422c992003-01-24 19:29:52 +0000487 self.memoize(object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000488
489 using_setitems = (self.bin and (len(object) > 1))
490
Tim Petersc32d8242001-04-10 02:48:53 +0000491 if using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000492 write(MARK)
493
494 items = object.items()
495 for key, value in items:
496 save(key)
497 save(value)
498
Tim Petersc32d8242001-04-10 02:48:53 +0000499 if not using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000500 write(SETITEM)
501
Tim Petersc32d8242001-04-10 02:48:53 +0000502 if using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000503 write(SETITEMS)
504
505 dispatch[DictionaryType] = save_dict
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000506 if not PyStringMap is None:
507 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000508
509 def save_inst(self, object):
510 d = id(object)
511 cls = object.__class__
512
513 memo = self.memo
514 write = self.write
515 save = self.save
516
517 if hasattr(object, '__getinitargs__'):
518 args = object.__getinitargs__()
519 len(args) # XXX Assert it's a sequence
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000520 _keep_alive(args, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000521 else:
522 args = ()
523
524 write(MARK)
525
Tim Petersc32d8242001-04-10 02:48:53 +0000526 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000527 save(cls)
528
529 for arg in args:
530 save(arg)
531
Jeremy Hylton3422c992003-01-24 19:29:52 +0000532 # This method does not use memoize() so that it can handle
533 # the special case for non-binary mode.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000534 memo_len = len(memo)
Tim Petersc32d8242001-04-10 02:48:53 +0000535 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000536 write(OBJ + self.put(memo_len))
537 else:
Guido van Rossum4fb5b281997-09-12 20:07:24 +0000538 write(INST + cls.__module__ + '\n' + cls.__name__ + '\n' +
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000539 self.put(memo_len))
540
541 memo[d] = (memo_len, object)
542
543 try:
544 getstate = object.__getstate__
545 except AttributeError:
546 stuff = object.__dict__
547 else:
548 stuff = getstate()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000549 _keep_alive(stuff, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000550 save(stuff)
551 write(BUILD)
552 dispatch[InstanceType] = save_inst
553
554 def save_global(self, object, name = None):
555 write = self.write
556 memo = self.memo
557
Tim Petersc32d8242001-04-10 02:48:53 +0000558 if name is None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000559 name = object.__name__
560
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000561 try:
562 module = object.__module__
563 except AttributeError:
564 module = whichmodule(object, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000565
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000566 try:
567 __import__(module)
568 mod = sys.modules[module]
569 klass = getattr(mod, name)
570 except (ImportError, KeyError, AttributeError):
571 raise PicklingError(
572 "Can't pickle %r: it's not found as %s.%s" %
573 (object, module, name))
574 else:
575 if klass is not object:
576 raise PicklingError(
577 "Can't pickle %r: it's not the same object as %s.%s" %
578 (object, module, name))
579
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000580 memo_len = len(memo)
581 write(GLOBAL + module + '\n' + name + '\n' +
582 self.put(memo_len))
583 memo[id(object)] = (memo_len, object)
584 dispatch[ClassType] = save_global
585 dispatch[FunctionType] = save_global
586 dispatch[BuiltinFunctionType] = save_global
Tim Peters6d6c1a32001-08-02 04:15:00 +0000587 dispatch[TypeType] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000588
Guido van Rossuma48061a1995-01-10 00:31:14 +0000589
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000590def _keep_alive(x, memo):
591 """Keeps a reference to the object x in the memo.
592
593 Because we remember objects by their id, we have
594 to assure that possibly temporary objects are kept
595 alive by referencing them.
596 We store a reference at the id of the memo, which should
597 normally not be used unless someone tries to deepcopy
598 the memo itself...
599 """
600 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000601 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000602 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000603 # aha, this is the first one :-)
604 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000605
606
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000607classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000608
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000609def whichmodule(func, funcname):
610 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000611
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000612 Search sys.modules for the module.
613 Cache in classmap.
614 Return a module name.
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000615 If the function cannot be found, return __main__.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000616 """
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000617 if func in classmap:
618 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000619
620 for name, module in sys.modules.items():
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000621 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000622 continue # skip dummy package entries
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000623 if name != '__main__' and \
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000624 hasattr(module, funcname) and \
625 getattr(module, funcname) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000626 break
627 else:
628 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000629 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000630 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000631
632
633class Unpickler:
634
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000635 def __init__(self, file):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000636 """This takes a file-like object for reading a pickle data stream.
637
638 This class automatically determines whether the data stream was
639 written in binary mode or not, so it does not need a flag as in
640 the Pickler class factory.
641
642 The file-like object must have two methods, a read() method that
643 takes an integer argument, and a readline() method that requires no
644 arguments. Both methods should return a string. Thus file-like
645 object can be a file object opened for reading, a StringIO object,
646 or any other custom object that meets this interface.
647
648 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000649 self.readline = file.readline
650 self.read = file.read
651 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000652
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000653 def load(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000654 """Read a pickled object representation from the open file object.
655
656 Return the reconstituted object hierarchy specified in the file
657 object.
658
659 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000660 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000661 self.stack = []
662 self.append = self.stack.append
663 read = self.read
664 dispatch = self.dispatch
665 try:
666 while 1:
667 key = read(1)
668 dispatch[key](self)
Guido van Rossumff871742000-12-13 18:11:56 +0000669 except _Stop, stopinst:
670 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000671
672 def marker(self):
673 stack = self.stack
674 mark = self.mark
675 k = len(stack)-1
676 while stack[k] is not mark: k = k-1
677 return k
678
679 dispatch = {}
680
681 def load_eof(self):
682 raise EOFError
683 dispatch[''] = load_eof
684
685 def load_persid(self):
686 pid = self.readline()[:-1]
687 self.append(self.persistent_load(pid))
688 dispatch[PERSID] = load_persid
689
690 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000691 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000692 self.append(self.persistent_load(pid))
693 dispatch[BINPERSID] = load_binpersid
694
695 def load_none(self):
696 self.append(None)
697 dispatch[NONE] = load_none
698
699 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000700 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000701 if data == FALSE[1:]:
702 val = False
703 elif data == TRUE[1:]:
704 val = True
705 else:
706 try:
707 val = int(data)
708 except ValueError:
709 val = long(data)
710 self.append(val)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000711 dispatch[INT] = load_int
712
713 def load_binint(self):
714 self.append(mloads('i' + self.read(4)))
715 dispatch[BININT] = load_binint
716
717 def load_binint1(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000718 self.append(ord(self.read(1)))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000719 dispatch[BININT1] = load_binint1
720
721 def load_binint2(self):
722 self.append(mloads('i' + self.read(2) + '\000\000'))
723 dispatch[BININT2] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000724
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000725 def load_long(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000726 self.append(long(self.readline()[:-1], 0))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000727 dispatch[LONG] = load_long
728
729 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000730 self.append(float(self.readline()[:-1]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000731 dispatch[FLOAT] = load_float
732
Guido van Rossumd3703791998-10-22 20:15:36 +0000733 def load_binfloat(self, unpack=struct.unpack):
734 self.append(unpack('>d', self.read(8))[0])
735 dispatch[BINFLOAT] = load_binfloat
736
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000737 def load_string(self):
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000738 rep = self.readline()[:-1]
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000739 for q in _quotes:
740 if rep.startswith(q):
741 if not rep.endswith(q):
742 raise ValueError, "insecure string pickle"
743 rep = rep[len(q):-len(q)]
744 break
745 else:
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000746 raise ValueError, "insecure string pickle"
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000747 self.append(rep.decode("string-escape"))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000748 dispatch[STRING] = load_string
749
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000750 def _is_string_secure(self, s):
751 """Return true if s contains a string that is safe to eval
752
753 The definition of secure string is based on the implementation
754 in cPickle. s is secure as long as it only contains a quoted
755 string and optional trailing whitespace.
756 """
757 q = s[0]
758 if q not in ("'", '"'):
759 return 0
760 # find the closing quote
761 offset = 1
762 i = None
763 while 1:
764 try:
765 i = s.index(q, offset)
766 except ValueError:
767 # if there is an error the first time, there is no
768 # close quote
769 if offset == 1:
770 return 0
771 if s[i-1] != '\\':
772 break
773 # check to see if this one is escaped
774 nslash = 0
775 j = i - 1
776 while j >= offset and s[j] == '\\':
777 j = j - 1
778 nslash = nslash + 1
779 if nslash % 2 == 0:
780 break
781 offset = i + 1
782 for c in s[i+1:]:
783 if ord(c) > 32:
784 return 0
785 return 1
786
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000787 def load_binstring(self):
788 len = mloads('i' + self.read(4))
789 self.append(self.read(len))
790 dispatch[BINSTRING] = load_binstring
791
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000792 def load_unicode(self):
793 self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
794 dispatch[UNICODE] = load_unicode
795
796 def load_binunicode(self):
797 len = mloads('i' + self.read(4))
798 self.append(unicode(self.read(len),'utf-8'))
799 dispatch[BINUNICODE] = load_binunicode
800
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000801 def load_short_binstring(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000802 len = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000803 self.append(self.read(len))
804 dispatch[SHORT_BINSTRING] = load_short_binstring
805
806 def load_tuple(self):
807 k = self.marker()
808 self.stack[k:] = [tuple(self.stack[k+1:])]
809 dispatch[TUPLE] = load_tuple
810
811 def load_empty_tuple(self):
812 self.stack.append(())
813 dispatch[EMPTY_TUPLE] = load_empty_tuple
814
815 def load_empty_list(self):
816 self.stack.append([])
817 dispatch[EMPTY_LIST] = load_empty_list
818
819 def load_empty_dictionary(self):
820 self.stack.append({})
821 dispatch[EMPTY_DICT] = load_empty_dictionary
822
823 def load_list(self):
824 k = self.marker()
825 self.stack[k:] = [self.stack[k+1:]]
826 dispatch[LIST] = load_list
827
828 def load_dict(self):
829 k = self.marker()
830 d = {}
831 items = self.stack[k+1:]
832 for i in range(0, len(items), 2):
833 key = items[i]
834 value = items[i+1]
835 d[key] = value
836 self.stack[k:] = [d]
837 dispatch[DICT] = load_dict
838
839 def load_inst(self):
840 k = self.marker()
841 args = tuple(self.stack[k+1:])
842 del self.stack[k:]
843 module = self.readline()[:-1]
844 name = self.readline()[:-1]
845 klass = self.find_class(module, name)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000846 instantiated = 0
847 if (not args and type(klass) is ClassType and
848 not hasattr(klass, "__getinitargs__")):
849 try:
850 value = _EmptyClass()
851 value.__class__ = klass
Guido van Rossumb19e2a31998-04-13 18:08:45 +0000852 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000853 except RuntimeError:
854 # In restricted execution, assignment to inst.__class__ is
855 # prohibited
856 pass
857 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +0000858 try:
Barry Warsawbf4d9592001-11-15 23:42:58 +0000859 if not hasattr(klass, '__safe_for_unpickling__'):
860 raise UnpicklingError('%s is not safe for unpickling' %
861 klass)
Guido van Rossum743d17e1998-09-15 20:25:57 +0000862 value = apply(klass, args)
863 except TypeError, err:
864 raise TypeError, "in constructor for %s: %s" % (
865 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000866 self.append(value)
867 dispatch[INST] = load_inst
868
869 def load_obj(self):
870 stack = self.stack
871 k = self.marker()
872 klass = stack[k + 1]
873 del stack[k + 1]
Tim Peters2344fae2001-01-15 00:50:52 +0000874 args = tuple(stack[k + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000875 del stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000876 instantiated = 0
877 if (not args and type(klass) is ClassType and
878 not hasattr(klass, "__getinitargs__")):
879 try:
880 value = _EmptyClass()
881 value.__class__ = klass
882 instantiated = 1
883 except RuntimeError:
884 # In restricted execution, assignment to inst.__class__ is
885 # prohibited
886 pass
887 if not instantiated:
888 value = apply(klass, args)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000889 self.append(value)
Tim Peters2344fae2001-01-15 00:50:52 +0000890 dispatch[OBJ] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000891
892 def load_global(self):
893 module = self.readline()[:-1]
894 name = self.readline()[:-1]
895 klass = self.find_class(module, name)
896 self.append(klass)
897 dispatch[GLOBAL] = load_global
898
899 def find_class(self, module, name):
Barry Warsawbf4d9592001-11-15 23:42:58 +0000900 __import__(module)
901 mod = sys.modules[module]
902 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000903 return klass
904
905 def load_reduce(self):
906 stack = self.stack
907
908 callable = stack[-2]
909 arg_tup = stack[-1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000910 del stack[-2:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000911
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000912 if type(callable) is not ClassType:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000913 if not callable in safe_constructors:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000914 try:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000915 safe = callable.__safe_for_unpickling__
916 except AttributeError:
917 safe = None
Guido van Rossuma48061a1995-01-10 00:31:14 +0000918
Tim Petersc32d8242001-04-10 02:48:53 +0000919 if not safe:
Tim Peters2344fae2001-01-15 00:50:52 +0000920 raise UnpicklingError, "%s is not safe for " \
921 "unpickling" % callable
Guido van Rossuma48061a1995-01-10 00:31:14 +0000922
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000923 if arg_tup is None:
Raymond Hettinger97394bc2002-05-21 17:22:02 +0000924 import warnings
925 warnings.warn("The None return argument form of __reduce__ is "
926 "deprecated. Return a tuple of arguments instead.",
Tim Peters8ac14952002-05-23 15:15:30 +0000927 DeprecationWarning)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000928 value = callable.__basicnew__()
929 else:
930 value = apply(callable, arg_tup)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000931 self.append(value)
932 dispatch[REDUCE] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +0000933
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000934 def load_pop(self):
935 del self.stack[-1]
936 dispatch[POP] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +0000937
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000938 def load_pop_mark(self):
939 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000940 del self.stack[k:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000941 dispatch[POP_MARK] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +0000942
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000943 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +0000944 self.append(self.stack[-1])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000945 dispatch[DUP] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +0000946
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000947 def load_get(self):
948 self.append(self.memo[self.readline()[:-1]])
949 dispatch[GET] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +0000950
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000951 def load_binget(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000952 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000953 self.append(self.memo[`i`])
954 dispatch[BINGET] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +0000955
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000956 def load_long_binget(self):
957 i = mloads('i' + self.read(4))
958 self.append(self.memo[`i`])
959 dispatch[LONG_BINGET] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +0000960
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000961 def load_put(self):
962 self.memo[self.readline()[:-1]] = self.stack[-1]
963 dispatch[PUT] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +0000964
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000965 def load_binput(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000966 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000967 self.memo[`i`] = self.stack[-1]
968 dispatch[BINPUT] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +0000969
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000970 def load_long_binput(self):
971 i = mloads('i' + self.read(4))
972 self.memo[`i`] = self.stack[-1]
973 dispatch[LONG_BINPUT] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +0000974
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000975 def load_append(self):
976 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000977 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000978 list = stack[-1]
979 list.append(value)
980 dispatch[APPEND] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +0000981
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000982 def load_appends(self):
983 stack = self.stack
984 mark = self.marker()
985 list = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000986 for i in range(mark + 1, len(stack)):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000987 list.append(stack[i])
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000988
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000989 del stack[mark:]
990 dispatch[APPENDS] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +0000991
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000992 def load_setitem(self):
993 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000994 value = stack.pop()
995 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000996 dict = stack[-1]
997 dict[key] = value
998 dispatch[SETITEM] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000999
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001000 def load_setitems(self):
1001 stack = self.stack
1002 mark = self.marker()
1003 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001004 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001005 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001006
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001007 del stack[mark:]
1008 dispatch[SETITEMS] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001009
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001010 def load_build(self):
1011 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001012 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001013 inst = stack[-1]
1014 try:
1015 setstate = inst.__setstate__
1016 except AttributeError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001017 try:
1018 inst.__dict__.update(value)
1019 except RuntimeError:
1020 # XXX In restricted execution, the instance's __dict__ is not
1021 # accessible. Use the old way of unpickling the instance
1022 # variables. This is a semantic different when unpickling in
1023 # restricted vs. unrestricted modes.
1024 for k, v in value.items():
1025 setattr(inst, k, v)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001026 else:
1027 setstate(value)
1028 dispatch[BUILD] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001029
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001030 def load_mark(self):
1031 self.append(self.mark)
1032 dispatch[MARK] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001033
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001034 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001035 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001036 raise _Stop(value)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001037 dispatch[STOP] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001038
Guido van Rossume467be61997-12-05 19:42:42 +00001039# Helper class for load_inst/load_obj
1040
1041class _EmptyClass:
1042 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001043
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001044# Shorthands
1045
Jeremy Hyltonabe2c622001-10-15 21:29:28 +00001046try:
1047 from cStringIO import StringIO
1048except ImportError:
1049 from StringIO import StringIO
Guido van Rossumc7c5e691996-07-22 22:26:07 +00001050
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001051def dump(object, file, bin = 0):
1052 Pickler(file, bin).dump(object)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001053
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001054def dumps(object, bin = 0):
1055 file = StringIO()
1056 Pickler(file, bin).dump(object)
1057 return file.getvalue()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001058
1059def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001060 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001061
1062def loads(str):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001063 file = StringIO(str)
1064 return Unpickler(file).load()