blob: 79ee8af44561d3993dc84f8617a668bc5cacb7d7 [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 Rossum5a2d8f52003-01-27 21:44:25 +0000130# Protocol 2 (not yet implemented) (XXX comments will be added later)
131
132NEWOBJ = '\x81'
133PROTO = '\x80'
134EXT2 = '\x83'
135EXT1 = '\x82'
136TUPLE1 = '\x85'
137EXT4 = '\x84'
138TUPLE3 = '\x87'
139TUPLE2 = '\x86'
140NEWFALSE = '\x89'
141NEWTRUE = '\x88'
142LONG2 = '\x8b'
143LONG1 = '\x8a'
144LONG4 = '\x8c'
145
Guido van Rossuma48061a1995-01-10 00:31:14 +0000146
Skip Montanaro23bafc62001-02-18 03:10:09 +0000147__all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
Neal Norwitzd5ba4ae2002-02-11 18:12:06 +0000148del x
Skip Montanaro23bafc62001-02-18 03:10:09 +0000149
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000150_quotes = ["'", '"']
151
Guido van Rossuma48061a1995-01-10 00:31:14 +0000152class Pickler:
153
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000154 def __init__(self, file, bin = 0):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000155 """This takes a file-like object for writing a pickle data stream.
156
157 The optional bin parameter if true, tells the pickler to use the more
158 efficient binary pickle format, otherwise the ASCII format is used
159 (this is the default).
160
161 The file parameter must have a write() method that accepts a single
162 string argument. It can thus be an open file object, a StringIO
163 object, or any other custom object that meets this interface.
164
165 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000166 self.write = file.write
167 self.memo = {}
168 self.bin = bin
Guido van Rossuma48061a1995-01-10 00:31:14 +0000169
Fred Drake7f781c92002-05-01 20:33:53 +0000170 def clear_memo(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000171 """Clears the pickler's "memo".
172
173 The memo is the data structure that remembers which objects the
174 pickler has already seen, so that shared or recursive objects pickled
175 by reference and not by value. This method is useful when re-using
176 picklers.
177
178 """
Fred Drake7f781c92002-05-01 20:33:53 +0000179 self.memo.clear()
180
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000181 def dump(self, object):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000182 """Write a pickled representation of object to the open file object.
183
184 Either the binary or ASCII format will be used, depending on the
185 value of the bin flag passed to the constructor.
186
187 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000188 self.save(object)
189 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000190
Jeremy Hylton3422c992003-01-24 19:29:52 +0000191 def memoize(self, obj):
192 """Store an object in the memo."""
193
Tim Peterse46b73f2003-01-27 21:22:10 +0000194 # The Pickler memo is a dictionary mapping object ids to 2-tuples
195 # that contain the Unpickler memo key and the object being memoized.
196 # The memo key is written to the pickle and will become
Jeremy Hylton3422c992003-01-24 19:29:52 +0000197 # the key in the Unpickler's memo. The object is stored in the
Tim Peterse46b73f2003-01-27 21:22:10 +0000198 # Pickler memo so that transient objects are kept alive during
199 # pickling.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000200
Tim Peterse46b73f2003-01-27 21:22:10 +0000201 # The use of the Unpickler memo length as the memo key is just a
202 # convention. The only requirement is that the memo values be unique.
203 # But there appears no advantage to any other scheme, and this
204 # scheme allows the Unpickler memo to implemented as a plain (but
205 # growable) array, indexed by memo key.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000206 d = id(obj)
207 memo_len = len(self.memo)
208 self.write(self.put(memo_len))
209 self.memo[d] = memo_len, obj
210
Tim Petersbb38e302003-01-27 21:25:41 +0000211 # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000212 def put(self, i):
Tim Petersc32d8242001-04-10 02:48:53 +0000213 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000214 s = mdumps(i)[1:]
Tim Petersc32d8242001-04-10 02:48:53 +0000215 if i < 256:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000216 return BINPUT + s[0]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000217
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000218 return LONG_BINPUT + s
Guido van Rossuma48061a1995-01-10 00:31:14 +0000219
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000220 return PUT + `i` + '\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000221
Tim Petersbb38e302003-01-27 21:25:41 +0000222 # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000223 def get(self, i):
Tim Petersc32d8242001-04-10 02:48:53 +0000224 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000225 s = mdumps(i)[1:]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000226
Tim Petersc32d8242001-04-10 02:48:53 +0000227 if i < 256:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000228 return BINGET + s[0]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000229
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000230 return LONG_BINGET + s
Guido van Rossuma48061a1995-01-10 00:31:14 +0000231
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000232 return GET + `i` + '\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000233
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000234 def save(self, object):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000235 memo = self.memo
Guido van Rossuma48061a1995-01-10 00:31:14 +0000236
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000237 pid = self.persistent_id(object)
238 if pid is not None:
239 self.save_pers(pid)
240 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000241
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000242 d = id(object)
Tim Peters2344fae2001-01-15 00:50:52 +0000243
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000244 t = type(object)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000245
Tim Petersc32d8242001-04-10 02:48:53 +0000246 if (t is TupleType) and (len(object) == 0):
247 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000248 self.save_empty_tuple(object)
249 else:
250 self.save_tuple(object)
251 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000252
Raymond Hettinger54f02222002-06-01 14:18:47 +0000253 if d in memo:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000254 self.write(self.get(memo[d][0]))
255 return
256
257 try:
258 f = self.dispatch[t]
259 except KeyError:
Guido van Rossum85ee4912002-03-26 00:51:56 +0000260 try:
261 issc = issubclass(t, TypeType)
262 except TypeError: # t is not a class
263 issc = 0
264 if issc:
Guido van Rossumf048a8f2001-12-19 16:55:02 +0000265 self.save_global(object)
266 return
267
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000268 try:
269 reduce = dispatch_table[t]
270 except KeyError:
271 try:
272 reduce = object.__reduce__
273 except AttributeError:
274 raise PicklingError, \
Guido van Rossum08a92cb1999-10-10 21:14:25 +0000275 "can't pickle %s object: %s" % (`t.__name__`,
276 `object`)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000277 else:
278 tup = reduce()
279 else:
280 tup = reduce(object)
281
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000282 if type(tup) is StringType:
283 self.save_global(object, tup)
284 return
Guido van Rossumd1f49841997-12-10 23:40:18 +0000285
Tim Petersc32d8242001-04-10 02:48:53 +0000286 if type(tup) is not TupleType:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000287 raise PicklingError, "Value returned by %s must be a " \
288 "tuple" % reduce
289
290 l = len(tup)
Tim Peters2344fae2001-01-15 00:50:52 +0000291
Tim Petersc32d8242001-04-10 02:48:53 +0000292 if (l != 2) and (l != 3):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000293 raise PicklingError, "tuple returned by %s must contain " \
294 "only two or three elements" % reduce
295
296 callable = tup[0]
297 arg_tup = tup[1]
Tim Peters2344fae2001-01-15 00:50:52 +0000298
Tim Petersc32d8242001-04-10 02:48:53 +0000299 if l > 2:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000300 state = tup[2]
301 else:
302 state = None
303
Guido van Rossumd1f49841997-12-10 23:40:18 +0000304 if type(arg_tup) is not TupleType and arg_tup is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000305 raise PicklingError, "Second element of tuple returned " \
306 "by %s must be a tuple" % reduce
307
Tim Peters2344fae2001-01-15 00:50:52 +0000308 self.save_reduce(callable, arg_tup, state)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000309 memo_len = len(memo)
310 self.write(self.put(memo_len))
311 memo[d] = (memo_len, object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000312 return
313
314 f(self, object)
315
316 def persistent_id(self, object):
317 return None
318
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000319 def save_pers(self, pid):
Tim Petersc32d8242001-04-10 02:48:53 +0000320 if not self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000321 self.write(PERSID + str(pid) + '\n')
322 else:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000323 self.save(pid)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000324 self.write(BINPERSID)
325
Jeremy Hylton3422c992003-01-24 19:29:52 +0000326 def save_reduce(self, acallable, arg_tup, state = None):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000327 write = self.write
328 save = self.save
329
Jeremy Hylton3422c992003-01-24 19:29:52 +0000330 if not callable(acallable):
331 raise PicklingError("__reduce__() must return callable as "
332 "first argument, not %s" % `acallable`)
Tim Peters22a449a2003-01-27 20:16:36 +0000333
Jeremy Hylton3422c992003-01-24 19:29:52 +0000334 save(acallable)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000335 save(arg_tup)
336 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000337
Tim Petersc32d8242001-04-10 02:48:53 +0000338 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000339 save(state)
340 write(BUILD)
341
342 dispatch = {}
343
344 def save_none(self, object):
345 self.write(NONE)
346 dispatch[NoneType] = save_none
347
Guido van Rossum77f6a652002-04-03 22:41:51 +0000348 def save_bool(self, object):
349 if object:
350 self.write(TRUE)
351 else:
352 self.write(FALSE)
353 dispatch[bool] = save_bool
354
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000355 def save_int(self, object):
Tim Petersc32d8242001-04-10 02:48:53 +0000356 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000357 # If the int is small enough to fit in a signed 4-byte 2's-comp
358 # format, we can store it more efficiently than the general
359 # case.
360 high_bits = object >> 31 # note that Python shift sign-extends
361 if high_bits == 0 or high_bits == -1:
362 # All high bits are copies of bit 2**31, so the value
363 # fits in a 4-byte signed int.
364 i = mdumps(object)[1:]
365 assert len(i) == 4
366 if i[-2:] == '\000\000': # fits in 2-byte unsigned int
367 if i[-3] == '\000': # fits in 1-byte unsigned int
368 self.write(BININT1 + i[0])
369 else:
370 self.write(BININT2 + i[:2])
371 else:
372 self.write(BININT + i)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000373 return
Tim Peters44714002001-04-10 05:02:52 +0000374 # Text pickle, or int too big to fit in signed 4-byte format.
375 self.write(INT + `object` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000376 dispatch[IntType] = save_int
377
378 def save_long(self, object):
379 self.write(LONG + `object` + '\n')
380 dispatch[LongType] = save_long
381
Guido van Rossumd3703791998-10-22 20:15:36 +0000382 def save_float(self, object, pack=struct.pack):
383 if self.bin:
384 self.write(BINFLOAT + pack('>d', object))
385 else:
386 self.write(FLOAT + `object` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000387 dispatch[FloatType] = save_float
388
389 def save_string(self, object):
Tim Petersc32d8242001-04-10 02:48:53 +0000390 if self.bin:
Tim Petersbbf63cd2003-01-27 21:15:36 +0000391 n = len(object)
392 if n < 256:
393 self.write(SHORT_BINSTRING + chr(n) + object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000394 else:
Tim Petersbbf63cd2003-01-27 21:15:36 +0000395 self.write(BINSTRING + mdumps(n)[1:] + object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000396 else:
397 self.write(STRING + `object` + '\n')
Jeremy Hylton3422c992003-01-24 19:29:52 +0000398 self.memoize(object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000399 dispatch[StringType] = save_string
400
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000401 def save_unicode(self, object):
Tim Petersc32d8242001-04-10 02:48:53 +0000402 if self.bin:
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000403 encoding = object.encode('utf-8')
Tim Petersbbf63cd2003-01-27 21:15:36 +0000404 n = len(encoding)
405 s = mdumps(n)[1:]
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000406 self.write(BINUNICODE + s + encoding)
407 else:
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000408 object = object.replace("\\", "\\u005c")
409 object = object.replace("\n", "\\u000a")
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000410 self.write(UNICODE + object.encode('raw-unicode-escape') + '\n')
Jeremy Hylton3422c992003-01-24 19:29:52 +0000411 self.memoize(object)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000412 dispatch[UnicodeType] = save_unicode
413
Guido van Rossum31584cb2001-01-22 14:53:29 +0000414 if StringType == UnicodeType:
415 # This is true for Jython
416 def save_string(self, object):
Guido van Rossum31584cb2001-01-22 14:53:29 +0000417 unicode = object.isunicode()
418
Tim Petersc32d8242001-04-10 02:48:53 +0000419 if self.bin:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000420 if unicode:
421 object = object.encode("utf-8")
422 l = len(object)
423 s = mdumps(l)[1:]
Tim Petersc32d8242001-04-10 02:48:53 +0000424 if l < 256 and not unicode:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000425 self.write(SHORT_BINSTRING + s[0] + object)
426 else:
427 if unicode:
428 self.write(BINUNICODE + s + object)
429 else:
430 self.write(BINSTRING + s + object)
431 else:
Tim Peters658cba62001-02-09 20:06:00 +0000432 if unicode:
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000433 object = object.replace("\\", "\\u005c")
434 object = object.replace("\n", "\\u000a")
Guido van Rossum31584cb2001-01-22 14:53:29 +0000435 object = object.encode('raw-unicode-escape')
436 self.write(UNICODE + object + '\n')
437 else:
438 self.write(STRING + `object` + '\n')
Jeremy Hylton3422c992003-01-24 19:29:52 +0000439 self.memoize(object)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000440 dispatch[StringType] = save_string
Tim Peters658cba62001-02-09 20:06:00 +0000441
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000442 def save_tuple(self, object):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000443 write = self.write
444 save = self.save
445 memo = self.memo
446
447 d = id(object)
448
449 write(MARK)
450
451 for element in object:
452 save(element)
453
Raymond Hettinger54f02222002-06-01 14:18:47 +0000454 if len(object) and d in memo:
Tim Petersc32d8242001-04-10 02:48:53 +0000455 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000456 write(POP_MARK + self.get(memo[d][0]))
457 return
Tim Peters2344fae2001-01-15 00:50:52 +0000458
Guido van Rossum599174f1998-03-31 16:30:28 +0000459 write(POP * (len(object) + 1) + self.get(memo[d][0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000460 return
461
462 memo_len = len(memo)
463 self.write(TUPLE + self.put(memo_len))
464 memo[d] = (memo_len, object)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000465
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000466 dispatch[TupleType] = save_tuple
467
468 def save_empty_tuple(self, object):
469 self.write(EMPTY_TUPLE)
470
471 def save_list(self, object):
472 d = id(object)
473
474 write = self.write
475 save = self.save
476 memo = self.memo
477
Tim Petersc32d8242001-04-10 02:48:53 +0000478 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000479 write(EMPTY_LIST)
480 else:
481 write(MARK + LIST)
482
Jeremy Hylton3422c992003-01-24 19:29:52 +0000483 self.memoize(object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000484
485 using_appends = (self.bin and (len(object) > 1))
486
Tim Petersc32d8242001-04-10 02:48:53 +0000487 if using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000488 write(MARK)
489
490 for element in object:
491 save(element)
Tim Peters2344fae2001-01-15 00:50:52 +0000492
Tim Petersc32d8242001-04-10 02:48:53 +0000493 if not using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000494 write(APPEND)
495
Tim Petersc32d8242001-04-10 02:48:53 +0000496 if using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000497 write(APPENDS)
498 dispatch[ListType] = save_list
499
500 def save_dict(self, object):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000501 write = self.write
502 save = self.save
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000503
Tim Petersc32d8242001-04-10 02:48:53 +0000504 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000505 write(EMPTY_DICT)
506 else:
507 write(MARK + DICT)
508
Jeremy Hylton3422c992003-01-24 19:29:52 +0000509 self.memoize(object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000510
511 using_setitems = (self.bin and (len(object) > 1))
512
Tim Petersc32d8242001-04-10 02:48:53 +0000513 if using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000514 write(MARK)
515
516 items = object.items()
517 for key, value in items:
518 save(key)
519 save(value)
520
Tim Petersc32d8242001-04-10 02:48:53 +0000521 if not using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000522 write(SETITEM)
523
Tim Petersc32d8242001-04-10 02:48:53 +0000524 if using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000525 write(SETITEMS)
526
527 dispatch[DictionaryType] = save_dict
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000528 if not PyStringMap is None:
529 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000530
531 def save_inst(self, object):
532 d = id(object)
533 cls = object.__class__
534
535 memo = self.memo
536 write = self.write
537 save = self.save
538
539 if hasattr(object, '__getinitargs__'):
540 args = object.__getinitargs__()
541 len(args) # XXX Assert it's a sequence
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000542 _keep_alive(args, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000543 else:
544 args = ()
545
546 write(MARK)
547
Tim Petersc32d8242001-04-10 02:48:53 +0000548 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000549 save(cls)
550
551 for arg in args:
552 save(arg)
553
Jeremy Hylton3422c992003-01-24 19:29:52 +0000554 # This method does not use memoize() so that it can handle
555 # the special case for non-binary mode.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000556 memo_len = len(memo)
Tim Petersc32d8242001-04-10 02:48:53 +0000557 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000558 write(OBJ + self.put(memo_len))
559 else:
Guido van Rossum4fb5b281997-09-12 20:07:24 +0000560 write(INST + cls.__module__ + '\n' + cls.__name__ + '\n' +
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000561 self.put(memo_len))
562
563 memo[d] = (memo_len, object)
564
565 try:
566 getstate = object.__getstate__
567 except AttributeError:
568 stuff = object.__dict__
569 else:
570 stuff = getstate()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000571 _keep_alive(stuff, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000572 save(stuff)
573 write(BUILD)
574 dispatch[InstanceType] = save_inst
575
576 def save_global(self, object, name = None):
577 write = self.write
578 memo = self.memo
579
Tim Petersc32d8242001-04-10 02:48:53 +0000580 if name is None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000581 name = object.__name__
582
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000583 try:
584 module = object.__module__
585 except AttributeError:
586 module = whichmodule(object, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000587
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000588 try:
589 __import__(module)
590 mod = sys.modules[module]
591 klass = getattr(mod, name)
592 except (ImportError, KeyError, AttributeError):
593 raise PicklingError(
594 "Can't pickle %r: it's not found as %s.%s" %
595 (object, module, name))
596 else:
597 if klass is not object:
598 raise PicklingError(
599 "Can't pickle %r: it's not the same object as %s.%s" %
600 (object, module, name))
601
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000602 memo_len = len(memo)
603 write(GLOBAL + module + '\n' + name + '\n' +
604 self.put(memo_len))
605 memo[id(object)] = (memo_len, object)
606 dispatch[ClassType] = save_global
607 dispatch[FunctionType] = save_global
608 dispatch[BuiltinFunctionType] = save_global
Tim Peters6d6c1a32001-08-02 04:15:00 +0000609 dispatch[TypeType] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000610
Guido van Rossuma48061a1995-01-10 00:31:14 +0000611
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000612def _keep_alive(x, memo):
613 """Keeps a reference to the object x in the memo.
614
615 Because we remember objects by their id, we have
616 to assure that possibly temporary objects are kept
617 alive by referencing them.
618 We store a reference at the id of the memo, which should
619 normally not be used unless someone tries to deepcopy
620 the memo itself...
621 """
622 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000623 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000624 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000625 # aha, this is the first one :-)
626 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000627
628
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000629classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000630
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000631def whichmodule(func, funcname):
632 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000633
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000634 Search sys.modules for the module.
635 Cache in classmap.
636 Return a module name.
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000637 If the function cannot be found, return __main__.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000638 """
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000639 if func in classmap:
640 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000641
642 for name, module in sys.modules.items():
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000643 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000644 continue # skip dummy package entries
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000645 if name != '__main__' and \
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000646 hasattr(module, funcname) and \
647 getattr(module, funcname) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000648 break
649 else:
650 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000651 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000652 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000653
654
655class Unpickler:
656
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000657 def __init__(self, file):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000658 """This takes a file-like object for reading a pickle data stream.
659
660 This class automatically determines whether the data stream was
661 written in binary mode or not, so it does not need a flag as in
662 the Pickler class factory.
663
664 The file-like object must have two methods, a read() method that
665 takes an integer argument, and a readline() method that requires no
666 arguments. Both methods should return a string. Thus file-like
667 object can be a file object opened for reading, a StringIO object,
668 or any other custom object that meets this interface.
669
670 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000671 self.readline = file.readline
672 self.read = file.read
673 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000674
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000675 def load(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000676 """Read a pickled object representation from the open file object.
677
678 Return the reconstituted object hierarchy specified in the file
679 object.
680
681 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000682 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000683 self.stack = []
684 self.append = self.stack.append
685 read = self.read
686 dispatch = self.dispatch
687 try:
688 while 1:
689 key = read(1)
690 dispatch[key](self)
Guido van Rossumff871742000-12-13 18:11:56 +0000691 except _Stop, stopinst:
692 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000693
694 def marker(self):
695 stack = self.stack
696 mark = self.mark
697 k = len(stack)-1
698 while stack[k] is not mark: k = k-1
699 return k
700
701 dispatch = {}
702
703 def load_eof(self):
704 raise EOFError
705 dispatch[''] = load_eof
706
707 def load_persid(self):
708 pid = self.readline()[:-1]
709 self.append(self.persistent_load(pid))
710 dispatch[PERSID] = load_persid
711
712 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000713 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000714 self.append(self.persistent_load(pid))
715 dispatch[BINPERSID] = load_binpersid
716
717 def load_none(self):
718 self.append(None)
719 dispatch[NONE] = load_none
720
721 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000722 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000723 if data == FALSE[1:]:
724 val = False
725 elif data == TRUE[1:]:
726 val = True
727 else:
728 try:
729 val = int(data)
730 except ValueError:
731 val = long(data)
732 self.append(val)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000733 dispatch[INT] = load_int
734
735 def load_binint(self):
736 self.append(mloads('i' + self.read(4)))
737 dispatch[BININT] = load_binint
738
739 def load_binint1(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000740 self.append(ord(self.read(1)))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000741 dispatch[BININT1] = load_binint1
742
743 def load_binint2(self):
744 self.append(mloads('i' + self.read(2) + '\000\000'))
745 dispatch[BININT2] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000746
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000747 def load_long(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000748 self.append(long(self.readline()[:-1], 0))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000749 dispatch[LONG] = load_long
750
751 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000752 self.append(float(self.readline()[:-1]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000753 dispatch[FLOAT] = load_float
754
Guido van Rossumd3703791998-10-22 20:15:36 +0000755 def load_binfloat(self, unpack=struct.unpack):
756 self.append(unpack('>d', self.read(8))[0])
757 dispatch[BINFLOAT] = load_binfloat
758
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000759 def load_string(self):
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000760 rep = self.readline()[:-1]
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000761 for q in _quotes:
762 if rep.startswith(q):
763 if not rep.endswith(q):
764 raise ValueError, "insecure string pickle"
765 rep = rep[len(q):-len(q)]
766 break
767 else:
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000768 raise ValueError, "insecure string pickle"
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000769 self.append(rep.decode("string-escape"))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000770 dispatch[STRING] = load_string
771
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000772 def _is_string_secure(self, s):
773 """Return true if s contains a string that is safe to eval
774
775 The definition of secure string is based on the implementation
776 in cPickle. s is secure as long as it only contains a quoted
777 string and optional trailing whitespace.
778 """
779 q = s[0]
780 if q not in ("'", '"'):
781 return 0
782 # find the closing quote
783 offset = 1
784 i = None
785 while 1:
786 try:
787 i = s.index(q, offset)
788 except ValueError:
789 # if there is an error the first time, there is no
790 # close quote
791 if offset == 1:
792 return 0
793 if s[i-1] != '\\':
794 break
795 # check to see if this one is escaped
796 nslash = 0
797 j = i - 1
798 while j >= offset and s[j] == '\\':
799 j = j - 1
800 nslash = nslash + 1
801 if nslash % 2 == 0:
802 break
803 offset = i + 1
804 for c in s[i+1:]:
805 if ord(c) > 32:
806 return 0
807 return 1
808
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000809 def load_binstring(self):
810 len = mloads('i' + self.read(4))
811 self.append(self.read(len))
812 dispatch[BINSTRING] = load_binstring
813
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000814 def load_unicode(self):
815 self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
816 dispatch[UNICODE] = load_unicode
817
818 def load_binunicode(self):
819 len = mloads('i' + self.read(4))
820 self.append(unicode(self.read(len),'utf-8'))
821 dispatch[BINUNICODE] = load_binunicode
822
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000823 def load_short_binstring(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000824 len = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000825 self.append(self.read(len))
826 dispatch[SHORT_BINSTRING] = load_short_binstring
827
828 def load_tuple(self):
829 k = self.marker()
830 self.stack[k:] = [tuple(self.stack[k+1:])]
831 dispatch[TUPLE] = load_tuple
832
833 def load_empty_tuple(self):
834 self.stack.append(())
835 dispatch[EMPTY_TUPLE] = load_empty_tuple
836
837 def load_empty_list(self):
838 self.stack.append([])
839 dispatch[EMPTY_LIST] = load_empty_list
840
841 def load_empty_dictionary(self):
842 self.stack.append({})
843 dispatch[EMPTY_DICT] = load_empty_dictionary
844
845 def load_list(self):
846 k = self.marker()
847 self.stack[k:] = [self.stack[k+1:]]
848 dispatch[LIST] = load_list
849
850 def load_dict(self):
851 k = self.marker()
852 d = {}
853 items = self.stack[k+1:]
854 for i in range(0, len(items), 2):
855 key = items[i]
856 value = items[i+1]
857 d[key] = value
858 self.stack[k:] = [d]
859 dispatch[DICT] = load_dict
860
861 def load_inst(self):
862 k = self.marker()
863 args = tuple(self.stack[k+1:])
864 del self.stack[k:]
865 module = self.readline()[:-1]
866 name = self.readline()[:-1]
867 klass = self.find_class(module, name)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000868 instantiated = 0
869 if (not args and type(klass) is ClassType and
870 not hasattr(klass, "__getinitargs__")):
871 try:
872 value = _EmptyClass()
873 value.__class__ = klass
Guido van Rossumb19e2a31998-04-13 18:08:45 +0000874 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000875 except RuntimeError:
876 # In restricted execution, assignment to inst.__class__ is
877 # prohibited
878 pass
879 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +0000880 try:
Barry Warsawbf4d9592001-11-15 23:42:58 +0000881 if not hasattr(klass, '__safe_for_unpickling__'):
882 raise UnpicklingError('%s is not safe for unpickling' %
883 klass)
Guido van Rossum743d17e1998-09-15 20:25:57 +0000884 value = apply(klass, args)
885 except TypeError, err:
886 raise TypeError, "in constructor for %s: %s" % (
887 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000888 self.append(value)
889 dispatch[INST] = load_inst
890
891 def load_obj(self):
892 stack = self.stack
893 k = self.marker()
894 klass = stack[k + 1]
895 del stack[k + 1]
Tim Peters2344fae2001-01-15 00:50:52 +0000896 args = tuple(stack[k + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000897 del stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000898 instantiated = 0
899 if (not args and type(klass) is ClassType and
900 not hasattr(klass, "__getinitargs__")):
901 try:
902 value = _EmptyClass()
903 value.__class__ = klass
904 instantiated = 1
905 except RuntimeError:
906 # In restricted execution, assignment to inst.__class__ is
907 # prohibited
908 pass
909 if not instantiated:
910 value = apply(klass, args)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000911 self.append(value)
Tim Peters2344fae2001-01-15 00:50:52 +0000912 dispatch[OBJ] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000913
914 def load_global(self):
915 module = self.readline()[:-1]
916 name = self.readline()[:-1]
917 klass = self.find_class(module, name)
918 self.append(klass)
919 dispatch[GLOBAL] = load_global
920
921 def find_class(self, module, name):
Barry Warsawbf4d9592001-11-15 23:42:58 +0000922 __import__(module)
923 mod = sys.modules[module]
924 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000925 return klass
926
927 def load_reduce(self):
928 stack = self.stack
929
930 callable = stack[-2]
931 arg_tup = stack[-1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000932 del stack[-2:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000933
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000934 if type(callable) is not ClassType:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000935 if not callable in safe_constructors:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000936 try:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000937 safe = callable.__safe_for_unpickling__
938 except AttributeError:
939 safe = None
Guido van Rossuma48061a1995-01-10 00:31:14 +0000940
Tim Petersc32d8242001-04-10 02:48:53 +0000941 if not safe:
Tim Peters2344fae2001-01-15 00:50:52 +0000942 raise UnpicklingError, "%s is not safe for " \
943 "unpickling" % callable
Guido van Rossuma48061a1995-01-10 00:31:14 +0000944
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000945 if arg_tup is None:
Raymond Hettinger97394bc2002-05-21 17:22:02 +0000946 import warnings
947 warnings.warn("The None return argument form of __reduce__ is "
948 "deprecated. Return a tuple of arguments instead.",
Tim Peters8ac14952002-05-23 15:15:30 +0000949 DeprecationWarning)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000950 value = callable.__basicnew__()
951 else:
952 value = apply(callable, arg_tup)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000953 self.append(value)
954 dispatch[REDUCE] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +0000955
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000956 def load_pop(self):
957 del self.stack[-1]
958 dispatch[POP] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +0000959
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000960 def load_pop_mark(self):
961 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000962 del self.stack[k:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000963 dispatch[POP_MARK] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +0000964
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000965 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +0000966 self.append(self.stack[-1])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000967 dispatch[DUP] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +0000968
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000969 def load_get(self):
970 self.append(self.memo[self.readline()[:-1]])
971 dispatch[GET] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +0000972
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000973 def load_binget(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000974 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000975 self.append(self.memo[`i`])
976 dispatch[BINGET] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +0000977
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000978 def load_long_binget(self):
979 i = mloads('i' + self.read(4))
980 self.append(self.memo[`i`])
981 dispatch[LONG_BINGET] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +0000982
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000983 def load_put(self):
984 self.memo[self.readline()[:-1]] = self.stack[-1]
985 dispatch[PUT] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +0000986
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000987 def load_binput(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000988 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000989 self.memo[`i`] = self.stack[-1]
990 dispatch[BINPUT] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +0000991
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000992 def load_long_binput(self):
993 i = mloads('i' + self.read(4))
994 self.memo[`i`] = self.stack[-1]
995 dispatch[LONG_BINPUT] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +0000996
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000997 def load_append(self):
998 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000999 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001000 list = stack[-1]
1001 list.append(value)
1002 dispatch[APPEND] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +00001003
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001004 def load_appends(self):
1005 stack = self.stack
1006 mark = self.marker()
1007 list = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001008 for i in range(mark + 1, len(stack)):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001009 list.append(stack[i])
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001010
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001011 del stack[mark:]
1012 dispatch[APPENDS] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +00001013
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001014 def load_setitem(self):
1015 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001016 value = stack.pop()
1017 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001018 dict = stack[-1]
1019 dict[key] = value
1020 dispatch[SETITEM] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001021
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001022 def load_setitems(self):
1023 stack = self.stack
1024 mark = self.marker()
1025 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001026 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001027 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001028
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001029 del stack[mark:]
1030 dispatch[SETITEMS] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001031
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001032 def load_build(self):
1033 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001034 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001035 inst = stack[-1]
1036 try:
1037 setstate = inst.__setstate__
1038 except AttributeError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001039 try:
1040 inst.__dict__.update(value)
1041 except RuntimeError:
1042 # XXX In restricted execution, the instance's __dict__ is not
1043 # accessible. Use the old way of unpickling the instance
1044 # variables. This is a semantic different when unpickling in
1045 # restricted vs. unrestricted modes.
1046 for k, v in value.items():
1047 setattr(inst, k, v)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001048 else:
1049 setstate(value)
1050 dispatch[BUILD] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001051
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001052 def load_mark(self):
1053 self.append(self.mark)
1054 dispatch[MARK] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001055
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001056 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001057 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001058 raise _Stop(value)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001059 dispatch[STOP] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001060
Guido van Rossume467be61997-12-05 19:42:42 +00001061# Helper class for load_inst/load_obj
1062
1063class _EmptyClass:
1064 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001065
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001066# Shorthands
1067
Jeremy Hyltonabe2c622001-10-15 21:29:28 +00001068try:
1069 from cStringIO import StringIO
1070except ImportError:
1071 from StringIO import StringIO
Guido van Rossumc7c5e691996-07-22 22:26:07 +00001072
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001073def dump(object, file, bin = 0):
1074 Pickler(file, bin).dump(object)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001075
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001076def dumps(object, bin = 0):
1077 file = StringIO()
1078 Pickler(file, bin).dump(object)
1079 return file.getvalue()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001080
1081def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001082 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001083
1084def loads(str):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001085 file = StringIO(str)
1086 return Unpickler(file).load()