blob: 935228373484e81e7da68ca68b9d61e3c8828df2 [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 Rossumf29d3d62003-01-27 22:47:53 +000039# These are purely informational; no code usues these
40format_version = "2.0" # File format version we write
41compatible_formats = ["1.0", # Original protocol 0
42 "1.1", # Protocol 0 with class supprt added
43 "1.2", # Original protocol 1
44 "1.3", # Protocol 1 with BINFLOAT added
45 "2.0", # Protocol 2
46 ] # Old format versions we can read
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000047
48mdumps = marshal.dumps
49mloads = marshal.loads
Guido van Rossum0c891ce1995-03-14 15:09:05 +000050
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000051class PickleError(Exception):
Neal Norwitzefbb67b2002-05-30 12:12:04 +000052 """A common base class for the other pickling exceptions."""
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000053 pass
54
55class PicklingError(PickleError):
56 """This exception is raised when an unpicklable object is passed to the
57 dump() method.
58
59 """
60 pass
61
62class UnpicklingError(PickleError):
63 """This exception is raised when there is a problem unpickling an object,
64 such as a security violation.
65
66 Note that other exceptions may also be raised during unpickling, including
67 (but not necessarily limited to) AttributeError, EOFError, ImportError,
68 and IndexError.
69
70 """
71 pass
Guido van Rossum7849da81995-03-09 14:08:35 +000072
Guido van Rossumff871742000-12-13 18:11:56 +000073class _Stop(Exception):
74 def __init__(self, value):
75 self.value = value
76
Jeremy Hylton2b9d0291998-05-27 22:38:22 +000077try:
78 from org.python.core import PyStringMap
79except ImportError:
80 PyStringMap = None
81
Guido van Rossumdbb718f2001-09-21 19:22:34 +000082try:
83 UnicodeType
84except NameError:
85 UnicodeType = None
86
Tim Peters22a449a2003-01-27 20:16:36 +000087# Pickle opcodes. See pickletools.py for extensive docs. The listing
88# here is in kind-of alphabetical order of 1-character pickle code.
89# pickletools groups them by purpose.
Guido van Rossumdbb718f2001-09-21 19:22:34 +000090
Tim Peters22a449a2003-01-27 20:16:36 +000091MARK = '(' # push special markobject on stack
92STOP = '.' # every pickle ends with STOP
93POP = '0' # discard topmost stack item
94POP_MARK = '1' # discard stack top through topmost markobject
95DUP = '2' # duplicate top stack item
96FLOAT = 'F' # push float object; decimal string argument
97INT = 'I' # push integer or bool; decimal string argument
98BININT = 'J' # push four-byte signed int
99BININT1 = 'K' # push 1-byte unsigned int
100LONG = 'L' # push long; decimal string argument
101BININT2 = 'M' # push 2-byte unsigned int
102NONE = 'N' # push None
103PERSID = 'P' # push persistent object; id is taken from string arg
104BINPERSID = 'Q' # " " " ; " " " " stack
105REDUCE = 'R' # apply callable to argtuple, both on stack
106STRING = 'S' # push string; NL-terminated string argument
107BINSTRING = 'T' # push string; counted binary string argument
108SHORT_BINSTRING = 'U' # " " ; " " " " < 256 bytes
109UNICODE = 'V' # push Unicode string; raw-unicode-escaped'd argument
110BINUNICODE = 'X' # " " " ; counted UTF-8 string argument
111APPEND = 'a' # append stack top to list below it
112BUILD = 'b' # call __setstate__ or __dict__.update()
113GLOBAL = 'c' # push self.find_class(modname, name); 2 string args
114DICT = 'd' # build a dict from stack items
115EMPTY_DICT = '}' # push empty dict
116APPENDS = 'e' # extend list on stack by topmost stack slice
117GET = 'g' # push item from memo on stack; index is string arg
118BINGET = 'h' # " " " " " " ; " " 1-byte arg
119INST = 'i' # build & push class instance
120LONG_BINGET = 'j' # push item from memo on stack; index is 4-byte arg
121LIST = 'l' # build list from topmost stack items
122EMPTY_LIST = ']' # push empty list
123OBJ = 'o' # build & push class instance
124PUT = 'p' # store stack top in memo; index is string arg
125BINPUT = 'q' # " " " " " ; " " 1-byte arg
126LONG_BINPUT = 'r' # " " " " " ; " " 4-byte arg
127SETITEM = 's' # add key+value pair to dict
128TUPLE = 't' # build tuple from topmost stack items
129EMPTY_TUPLE = ')' # push empty tuple
130SETITEMS = 'u' # modify dict by adding topmost key+value pairs
131BINFLOAT = 'G' # push float; arg is 8-byte float encoding
132
133TRUE = 'I01\n' # not an opcode; see INT docs in pickletools.py
134FALSE = 'I00\n' # not an opcode; see INT docs in pickletools.py
Guido van Rossum77f6a652002-04-03 22:41:51 +0000135
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000136# Protocol 2 (not yet implemented) (XXX comments will be added later)
137
138NEWOBJ = '\x81'
139PROTO = '\x80'
140EXT2 = '\x83'
141EXT1 = '\x82'
142TUPLE1 = '\x85'
143EXT4 = '\x84'
144TUPLE3 = '\x87'
145TUPLE2 = '\x86'
146NEWFALSE = '\x89'
147NEWTRUE = '\x88'
148LONG2 = '\x8b'
149LONG1 = '\x8a'
150LONG4 = '\x8c'
151
Guido van Rossuma48061a1995-01-10 00:31:14 +0000152
Skip Montanaro23bafc62001-02-18 03:10:09 +0000153__all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
Neal Norwitzd5ba4ae2002-02-11 18:12:06 +0000154del x
Skip Montanaro23bafc62001-02-18 03:10:09 +0000155
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000156_quotes = ["'", '"']
157
Guido van Rossuma48061a1995-01-10 00:31:14 +0000158class Pickler:
159
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000160 def __init__(self, file, proto=1):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000161 """This takes a file-like object for writing a pickle data stream.
162
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000163 The optional proto argument tells the pickler to use the given
164 protocol; supported protocols are 0, 1, 2. The default
165 protocol is 1 (in previous Python versions the default was 0).
166
167 Protocol 1 is more efficient than protocol 0; protocol 2 is
168 more efficient than protocol 1. Protocol 2 is not the default
169 because it is not supported by older Python versions.
170
171 XXX Protocol 2 is not yet implemented.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000172
173 The file parameter must have a write() method that accepts a single
174 string argument. It can thus be an open file object, a StringIO
175 object, or any other custom object that meets this interface.
176
177 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000178 self.write = file.write
179 self.memo = {}
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000180 self.proto = proto
181 self.bin = proto >= 1
Guido van Rossuma48061a1995-01-10 00:31:14 +0000182
Fred Drake7f781c92002-05-01 20:33:53 +0000183 def clear_memo(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000184 """Clears the pickler's "memo".
185
186 The memo is the data structure that remembers which objects the
187 pickler has already seen, so that shared or recursive objects pickled
188 by reference and not by value. This method is useful when re-using
189 picklers.
190
191 """
Fred Drake7f781c92002-05-01 20:33:53 +0000192 self.memo.clear()
193
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000194 def dump(self, object):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000195 """Write a pickled representation of object to the open file object.
196
197 Either the binary or ASCII format will be used, depending on the
198 value of the bin flag passed to the constructor.
199
200 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000201 self.save(object)
202 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000203
Jeremy Hylton3422c992003-01-24 19:29:52 +0000204 def memoize(self, obj):
205 """Store an object in the memo."""
206
Tim Peterse46b73f2003-01-27 21:22:10 +0000207 # The Pickler memo is a dictionary mapping object ids to 2-tuples
208 # that contain the Unpickler memo key and the object being memoized.
209 # The memo key is written to the pickle and will become
Jeremy Hylton3422c992003-01-24 19:29:52 +0000210 # the key in the Unpickler's memo. The object is stored in the
Tim Peterse46b73f2003-01-27 21:22:10 +0000211 # Pickler memo so that transient objects are kept alive during
212 # pickling.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000213
Tim Peterse46b73f2003-01-27 21:22:10 +0000214 # The use of the Unpickler memo length as the memo key is just a
215 # convention. The only requirement is that the memo values be unique.
216 # But there appears no advantage to any other scheme, and this
217 # scheme allows the Unpickler memo to implemented as a plain (but
218 # growable) array, indexed by memo key.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000219 d = id(obj)
220 memo_len = len(self.memo)
221 self.write(self.put(memo_len))
222 self.memo[d] = memo_len, obj
223
Tim Petersbb38e302003-01-27 21:25:41 +0000224 # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000225 def put(self, i):
Tim Petersc32d8242001-04-10 02:48:53 +0000226 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000227 s = mdumps(i)[1:]
Tim Petersc32d8242001-04-10 02:48:53 +0000228 if i < 256:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000229 return BINPUT + s[0]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000230
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000231 return LONG_BINPUT + s
Guido van Rossuma48061a1995-01-10 00:31:14 +0000232
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000233 return PUT + `i` + '\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000234
Tim Petersbb38e302003-01-27 21:25:41 +0000235 # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000236 def get(self, i):
Tim Petersc32d8242001-04-10 02:48:53 +0000237 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000238 s = mdumps(i)[1:]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000239
Tim Petersc32d8242001-04-10 02:48:53 +0000240 if i < 256:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000241 return BINGET + s[0]
Guido van Rossuma48061a1995-01-10 00:31:14 +0000242
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000243 return LONG_BINGET + s
Guido van Rossuma48061a1995-01-10 00:31:14 +0000244
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000245 return GET + `i` + '\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000246
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000247 def save(self, object):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000248 memo = self.memo
Guido van Rossuma48061a1995-01-10 00:31:14 +0000249
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000250 pid = self.persistent_id(object)
251 if pid is not None:
252 self.save_pers(pid)
253 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000254
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000255 d = id(object)
Tim Peters2344fae2001-01-15 00:50:52 +0000256
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000257 t = type(object)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000258
Tim Petersc32d8242001-04-10 02:48:53 +0000259 if (t is TupleType) and (len(object) == 0):
260 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000261 self.save_empty_tuple(object)
262 else:
263 self.save_tuple(object)
264 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000265
Raymond Hettinger54f02222002-06-01 14:18:47 +0000266 if d in memo:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000267 self.write(self.get(memo[d][0]))
268 return
269
270 try:
271 f = self.dispatch[t]
272 except KeyError:
Guido van Rossum85ee4912002-03-26 00:51:56 +0000273 try:
274 issc = issubclass(t, TypeType)
275 except TypeError: # t is not a class
276 issc = 0
277 if issc:
Guido van Rossumf048a8f2001-12-19 16:55:02 +0000278 self.save_global(object)
279 return
280
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000281 try:
282 reduce = dispatch_table[t]
283 except KeyError:
284 try:
285 reduce = object.__reduce__
286 except AttributeError:
287 raise PicklingError, \
Guido van Rossum08a92cb1999-10-10 21:14:25 +0000288 "can't pickle %s object: %s" % (`t.__name__`,
289 `object`)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000290 else:
291 tup = reduce()
292 else:
293 tup = reduce(object)
294
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000295 if type(tup) is StringType:
296 self.save_global(object, tup)
297 return
Guido van Rossumd1f49841997-12-10 23:40:18 +0000298
Tim Petersc32d8242001-04-10 02:48:53 +0000299 if type(tup) is not TupleType:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000300 raise PicklingError, "Value returned by %s must be a " \
301 "tuple" % reduce
302
303 l = len(tup)
Tim Peters2344fae2001-01-15 00:50:52 +0000304
Tim Petersc32d8242001-04-10 02:48:53 +0000305 if (l != 2) and (l != 3):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000306 raise PicklingError, "tuple returned by %s must contain " \
307 "only two or three elements" % reduce
308
309 callable = tup[0]
310 arg_tup = tup[1]
Tim Peters2344fae2001-01-15 00:50:52 +0000311
Tim Petersc32d8242001-04-10 02:48:53 +0000312 if l > 2:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000313 state = tup[2]
314 else:
315 state = None
316
Guido van Rossumd1f49841997-12-10 23:40:18 +0000317 if type(arg_tup) is not TupleType and arg_tup is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000318 raise PicklingError, "Second element of tuple returned " \
319 "by %s must be a tuple" % reduce
320
Tim Peters2344fae2001-01-15 00:50:52 +0000321 self.save_reduce(callable, arg_tup, state)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000322 memo_len = len(memo)
323 self.write(self.put(memo_len))
324 memo[d] = (memo_len, object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000325 return
326
327 f(self, object)
328
329 def persistent_id(self, object):
330 return None
331
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000332 def save_pers(self, pid):
Tim Petersc32d8242001-04-10 02:48:53 +0000333 if not self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000334 self.write(PERSID + str(pid) + '\n')
335 else:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000336 self.save(pid)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000337 self.write(BINPERSID)
338
Jeremy Hylton3422c992003-01-24 19:29:52 +0000339 def save_reduce(self, acallable, arg_tup, state = None):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000340 write = self.write
341 save = self.save
342
Jeremy Hylton3422c992003-01-24 19:29:52 +0000343 if not callable(acallable):
344 raise PicklingError("__reduce__() must return callable as "
345 "first argument, not %s" % `acallable`)
Tim Peters22a449a2003-01-27 20:16:36 +0000346
Jeremy Hylton3422c992003-01-24 19:29:52 +0000347 save(acallable)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000348 save(arg_tup)
349 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000350
Tim Petersc32d8242001-04-10 02:48:53 +0000351 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000352 save(state)
353 write(BUILD)
354
355 dispatch = {}
356
357 def save_none(self, object):
358 self.write(NONE)
359 dispatch[NoneType] = save_none
360
Guido van Rossum77f6a652002-04-03 22:41:51 +0000361 def save_bool(self, object):
362 if object:
363 self.write(TRUE)
364 else:
365 self.write(FALSE)
366 dispatch[bool] = save_bool
367
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000368 def save_int(self, object):
Tim Petersc32d8242001-04-10 02:48:53 +0000369 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000370 # If the int is small enough to fit in a signed 4-byte 2's-comp
371 # format, we can store it more efficiently than the general
372 # case.
373 high_bits = object >> 31 # note that Python shift sign-extends
374 if high_bits == 0 or high_bits == -1:
375 # All high bits are copies of bit 2**31, so the value
376 # fits in a 4-byte signed int.
377 i = mdumps(object)[1:]
378 assert len(i) == 4
379 if i[-2:] == '\000\000': # fits in 2-byte unsigned int
380 if i[-3] == '\000': # fits in 1-byte unsigned int
381 self.write(BININT1 + i[0])
382 else:
383 self.write(BININT2 + i[:2])
384 else:
385 self.write(BININT + i)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000386 return
Tim Peters44714002001-04-10 05:02:52 +0000387 # Text pickle, or int too big to fit in signed 4-byte format.
388 self.write(INT + `object` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000389 dispatch[IntType] = save_int
390
391 def save_long(self, object):
392 self.write(LONG + `object` + '\n')
393 dispatch[LongType] = save_long
394
Guido van Rossumd3703791998-10-22 20:15:36 +0000395 def save_float(self, object, pack=struct.pack):
396 if self.bin:
397 self.write(BINFLOAT + pack('>d', object))
398 else:
399 self.write(FLOAT + `object` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000400 dispatch[FloatType] = save_float
401
402 def save_string(self, object):
Tim Petersc32d8242001-04-10 02:48:53 +0000403 if self.bin:
Tim Petersbbf63cd2003-01-27 21:15:36 +0000404 n = len(object)
405 if n < 256:
406 self.write(SHORT_BINSTRING + chr(n) + object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000407 else:
Tim Petersbbf63cd2003-01-27 21:15:36 +0000408 self.write(BINSTRING + mdumps(n)[1:] + object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000409 else:
410 self.write(STRING + `object` + '\n')
Jeremy Hylton3422c992003-01-24 19:29:52 +0000411 self.memoize(object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000412 dispatch[StringType] = save_string
413
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000414 def save_unicode(self, object):
Tim Petersc32d8242001-04-10 02:48:53 +0000415 if self.bin:
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000416 encoding = object.encode('utf-8')
Tim Petersbbf63cd2003-01-27 21:15:36 +0000417 n = len(encoding)
418 s = mdumps(n)[1:]
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000419 self.write(BINUNICODE + s + encoding)
420 else:
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000421 object = object.replace("\\", "\\u005c")
422 object = object.replace("\n", "\\u000a")
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000423 self.write(UNICODE + object.encode('raw-unicode-escape') + '\n')
Jeremy Hylton3422c992003-01-24 19:29:52 +0000424 self.memoize(object)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000425 dispatch[UnicodeType] = save_unicode
426
Guido van Rossum31584cb2001-01-22 14:53:29 +0000427 if StringType == UnicodeType:
428 # This is true for Jython
429 def save_string(self, object):
Guido van Rossum31584cb2001-01-22 14:53:29 +0000430 unicode = object.isunicode()
431
Tim Petersc32d8242001-04-10 02:48:53 +0000432 if self.bin:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000433 if unicode:
434 object = object.encode("utf-8")
435 l = len(object)
436 s = mdumps(l)[1:]
Tim Petersc32d8242001-04-10 02:48:53 +0000437 if l < 256 and not unicode:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000438 self.write(SHORT_BINSTRING + s[0] + object)
439 else:
440 if unicode:
441 self.write(BINUNICODE + s + object)
442 else:
443 self.write(BINSTRING + s + object)
444 else:
Tim Peters658cba62001-02-09 20:06:00 +0000445 if unicode:
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000446 object = object.replace("\\", "\\u005c")
447 object = object.replace("\n", "\\u000a")
Guido van Rossum31584cb2001-01-22 14:53:29 +0000448 object = object.encode('raw-unicode-escape')
449 self.write(UNICODE + object + '\n')
450 else:
451 self.write(STRING + `object` + '\n')
Jeremy Hylton3422c992003-01-24 19:29:52 +0000452 self.memoize(object)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000453 dispatch[StringType] = save_string
Tim Peters658cba62001-02-09 20:06:00 +0000454
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000455 def save_tuple(self, object):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000456 write = self.write
457 save = self.save
458 memo = self.memo
459
460 d = id(object)
461
462 write(MARK)
463
464 for element in object:
465 save(element)
466
Raymond Hettinger54f02222002-06-01 14:18:47 +0000467 if len(object) and d in memo:
Tim Petersc32d8242001-04-10 02:48:53 +0000468 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000469 write(POP_MARK + self.get(memo[d][0]))
470 return
Tim Peters2344fae2001-01-15 00:50:52 +0000471
Guido van Rossum599174f1998-03-31 16:30:28 +0000472 write(POP * (len(object) + 1) + self.get(memo[d][0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000473 return
474
475 memo_len = len(memo)
476 self.write(TUPLE + self.put(memo_len))
477 memo[d] = (memo_len, object)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000478
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000479 dispatch[TupleType] = save_tuple
480
481 def save_empty_tuple(self, object):
482 self.write(EMPTY_TUPLE)
483
484 def save_list(self, object):
485 d = id(object)
486
487 write = self.write
488 save = self.save
489 memo = self.memo
490
Tim Petersc32d8242001-04-10 02:48:53 +0000491 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000492 write(EMPTY_LIST)
493 else:
494 write(MARK + LIST)
495
Jeremy Hylton3422c992003-01-24 19:29:52 +0000496 self.memoize(object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000497
498 using_appends = (self.bin and (len(object) > 1))
499
Tim Petersc32d8242001-04-10 02:48:53 +0000500 if using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000501 write(MARK)
502
503 for element in object:
504 save(element)
Tim Peters2344fae2001-01-15 00:50:52 +0000505
Tim Petersc32d8242001-04-10 02:48:53 +0000506 if not using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000507 write(APPEND)
508
Tim Petersc32d8242001-04-10 02:48:53 +0000509 if using_appends:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000510 write(APPENDS)
511 dispatch[ListType] = save_list
512
513 def save_dict(self, object):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000514 write = self.write
515 save = self.save
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000516
Tim Petersc32d8242001-04-10 02:48:53 +0000517 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000518 write(EMPTY_DICT)
519 else:
520 write(MARK + DICT)
521
Jeremy Hylton3422c992003-01-24 19:29:52 +0000522 self.memoize(object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000523
524 using_setitems = (self.bin and (len(object) > 1))
525
Tim Petersc32d8242001-04-10 02:48:53 +0000526 if using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000527 write(MARK)
528
529 items = object.items()
530 for key, value in items:
531 save(key)
532 save(value)
533
Tim Petersc32d8242001-04-10 02:48:53 +0000534 if not using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000535 write(SETITEM)
536
Tim Petersc32d8242001-04-10 02:48:53 +0000537 if using_setitems:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000538 write(SETITEMS)
539
540 dispatch[DictionaryType] = save_dict
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000541 if not PyStringMap is None:
542 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000543
544 def save_inst(self, object):
545 d = id(object)
546 cls = object.__class__
547
548 memo = self.memo
549 write = self.write
550 save = self.save
551
552 if hasattr(object, '__getinitargs__'):
553 args = object.__getinitargs__()
554 len(args) # XXX Assert it's a sequence
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000555 _keep_alive(args, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000556 else:
557 args = ()
558
559 write(MARK)
560
Tim Petersc32d8242001-04-10 02:48:53 +0000561 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000562 save(cls)
563
564 for arg in args:
565 save(arg)
566
Jeremy Hylton3422c992003-01-24 19:29:52 +0000567 # This method does not use memoize() so that it can handle
568 # the special case for non-binary mode.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000569 memo_len = len(memo)
Tim Petersc32d8242001-04-10 02:48:53 +0000570 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000571 write(OBJ + self.put(memo_len))
572 else:
Guido van Rossum4fb5b281997-09-12 20:07:24 +0000573 write(INST + cls.__module__ + '\n' + cls.__name__ + '\n' +
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000574 self.put(memo_len))
575
576 memo[d] = (memo_len, object)
577
578 try:
579 getstate = object.__getstate__
580 except AttributeError:
581 stuff = object.__dict__
582 else:
583 stuff = getstate()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000584 _keep_alive(stuff, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000585 save(stuff)
586 write(BUILD)
587 dispatch[InstanceType] = save_inst
588
589 def save_global(self, object, name = None):
590 write = self.write
591 memo = self.memo
592
Tim Petersc32d8242001-04-10 02:48:53 +0000593 if name is None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000594 name = object.__name__
595
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000596 try:
597 module = object.__module__
598 except AttributeError:
599 module = whichmodule(object, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000600
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000601 try:
602 __import__(module)
603 mod = sys.modules[module]
604 klass = getattr(mod, name)
605 except (ImportError, KeyError, AttributeError):
606 raise PicklingError(
607 "Can't pickle %r: it's not found as %s.%s" %
608 (object, module, name))
609 else:
610 if klass is not object:
611 raise PicklingError(
612 "Can't pickle %r: it's not the same object as %s.%s" %
613 (object, module, name))
614
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000615 memo_len = len(memo)
616 write(GLOBAL + module + '\n' + name + '\n' +
617 self.put(memo_len))
618 memo[id(object)] = (memo_len, object)
619 dispatch[ClassType] = save_global
620 dispatch[FunctionType] = save_global
621 dispatch[BuiltinFunctionType] = save_global
Tim Peters6d6c1a32001-08-02 04:15:00 +0000622 dispatch[TypeType] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000623
Guido van Rossuma48061a1995-01-10 00:31:14 +0000624
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000625def _keep_alive(x, memo):
626 """Keeps a reference to the object x in the memo.
627
628 Because we remember objects by their id, we have
629 to assure that possibly temporary objects are kept
630 alive by referencing them.
631 We store a reference at the id of the memo, which should
632 normally not be used unless someone tries to deepcopy
633 the memo itself...
634 """
635 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000636 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000637 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000638 # aha, this is the first one :-)
639 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000640
641
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000642classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000643
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000644def whichmodule(func, funcname):
645 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000646
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000647 Search sys.modules for the module.
648 Cache in classmap.
649 Return a module name.
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000650 If the function cannot be found, return __main__.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000651 """
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000652 if func in classmap:
653 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000654
655 for name, module in sys.modules.items():
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000656 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000657 continue # skip dummy package entries
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000658 if name != '__main__' and \
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000659 hasattr(module, funcname) and \
660 getattr(module, funcname) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000661 break
662 else:
663 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000664 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000665 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000666
667
668class Unpickler:
669
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000670 def __init__(self, file):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000671 """This takes a file-like object for reading a pickle data stream.
672
673 This class automatically determines whether the data stream was
674 written in binary mode or not, so it does not need a flag as in
675 the Pickler class factory.
676
677 The file-like object must have two methods, a read() method that
678 takes an integer argument, and a readline() method that requires no
679 arguments. Both methods should return a string. Thus file-like
680 object can be a file object opened for reading, a StringIO object,
681 or any other custom object that meets this interface.
682
683 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000684 self.readline = file.readline
685 self.read = file.read
686 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000687
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000688 def load(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000689 """Read a pickled object representation from the open file object.
690
691 Return the reconstituted object hierarchy specified in the file
692 object.
693
694 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000695 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000696 self.stack = []
697 self.append = self.stack.append
698 read = self.read
699 dispatch = self.dispatch
700 try:
701 while 1:
702 key = read(1)
703 dispatch[key](self)
Guido van Rossumff871742000-12-13 18:11:56 +0000704 except _Stop, stopinst:
705 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000706
707 def marker(self):
708 stack = self.stack
709 mark = self.mark
710 k = len(stack)-1
711 while stack[k] is not mark: k = k-1
712 return k
713
714 dispatch = {}
715
716 def load_eof(self):
717 raise EOFError
718 dispatch[''] = load_eof
719
720 def load_persid(self):
721 pid = self.readline()[:-1]
722 self.append(self.persistent_load(pid))
723 dispatch[PERSID] = load_persid
724
725 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000726 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000727 self.append(self.persistent_load(pid))
728 dispatch[BINPERSID] = load_binpersid
729
730 def load_none(self):
731 self.append(None)
732 dispatch[NONE] = load_none
733
734 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000735 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000736 if data == FALSE[1:]:
737 val = False
738 elif data == TRUE[1:]:
739 val = True
740 else:
741 try:
742 val = int(data)
743 except ValueError:
744 val = long(data)
745 self.append(val)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000746 dispatch[INT] = load_int
747
748 def load_binint(self):
749 self.append(mloads('i' + self.read(4)))
750 dispatch[BININT] = load_binint
751
752 def load_binint1(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000753 self.append(ord(self.read(1)))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000754 dispatch[BININT1] = load_binint1
755
756 def load_binint2(self):
757 self.append(mloads('i' + self.read(2) + '\000\000'))
758 dispatch[BININT2] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000759
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000760 def load_long(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000761 self.append(long(self.readline()[:-1], 0))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000762 dispatch[LONG] = load_long
763
764 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000765 self.append(float(self.readline()[:-1]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000766 dispatch[FLOAT] = load_float
767
Guido van Rossumd3703791998-10-22 20:15:36 +0000768 def load_binfloat(self, unpack=struct.unpack):
769 self.append(unpack('>d', self.read(8))[0])
770 dispatch[BINFLOAT] = load_binfloat
771
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000772 def load_string(self):
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000773 rep = self.readline()[:-1]
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000774 for q in _quotes:
775 if rep.startswith(q):
776 if not rep.endswith(q):
777 raise ValueError, "insecure string pickle"
778 rep = rep[len(q):-len(q)]
779 break
780 else:
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000781 raise ValueError, "insecure string pickle"
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000782 self.append(rep.decode("string-escape"))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000783 dispatch[STRING] = load_string
784
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000785 def _is_string_secure(self, s):
786 """Return true if s contains a string that is safe to eval
787
788 The definition of secure string is based on the implementation
789 in cPickle. s is secure as long as it only contains a quoted
790 string and optional trailing whitespace.
791 """
792 q = s[0]
793 if q not in ("'", '"'):
794 return 0
795 # find the closing quote
796 offset = 1
797 i = None
798 while 1:
799 try:
800 i = s.index(q, offset)
801 except ValueError:
802 # if there is an error the first time, there is no
803 # close quote
804 if offset == 1:
805 return 0
806 if s[i-1] != '\\':
807 break
808 # check to see if this one is escaped
809 nslash = 0
810 j = i - 1
811 while j >= offset and s[j] == '\\':
812 j = j - 1
813 nslash = nslash + 1
814 if nslash % 2 == 0:
815 break
816 offset = i + 1
817 for c in s[i+1:]:
818 if ord(c) > 32:
819 return 0
820 return 1
821
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000822 def load_binstring(self):
823 len = mloads('i' + self.read(4))
824 self.append(self.read(len))
825 dispatch[BINSTRING] = load_binstring
826
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000827 def load_unicode(self):
828 self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
829 dispatch[UNICODE] = load_unicode
830
831 def load_binunicode(self):
832 len = mloads('i' + self.read(4))
833 self.append(unicode(self.read(len),'utf-8'))
834 dispatch[BINUNICODE] = load_binunicode
835
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000836 def load_short_binstring(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000837 len = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000838 self.append(self.read(len))
839 dispatch[SHORT_BINSTRING] = load_short_binstring
840
841 def load_tuple(self):
842 k = self.marker()
843 self.stack[k:] = [tuple(self.stack[k+1:])]
844 dispatch[TUPLE] = load_tuple
845
846 def load_empty_tuple(self):
847 self.stack.append(())
848 dispatch[EMPTY_TUPLE] = load_empty_tuple
849
850 def load_empty_list(self):
851 self.stack.append([])
852 dispatch[EMPTY_LIST] = load_empty_list
853
854 def load_empty_dictionary(self):
855 self.stack.append({})
856 dispatch[EMPTY_DICT] = load_empty_dictionary
857
858 def load_list(self):
859 k = self.marker()
860 self.stack[k:] = [self.stack[k+1:]]
861 dispatch[LIST] = load_list
862
863 def load_dict(self):
864 k = self.marker()
865 d = {}
866 items = self.stack[k+1:]
867 for i in range(0, len(items), 2):
868 key = items[i]
869 value = items[i+1]
870 d[key] = value
871 self.stack[k:] = [d]
872 dispatch[DICT] = load_dict
873
874 def load_inst(self):
875 k = self.marker()
876 args = tuple(self.stack[k+1:])
877 del self.stack[k:]
878 module = self.readline()[:-1]
879 name = self.readline()[:-1]
880 klass = self.find_class(module, name)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000881 instantiated = 0
882 if (not args and type(klass) is ClassType and
883 not hasattr(klass, "__getinitargs__")):
884 try:
885 value = _EmptyClass()
886 value.__class__ = klass
Guido van Rossumb19e2a31998-04-13 18:08:45 +0000887 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000888 except RuntimeError:
889 # In restricted execution, assignment to inst.__class__ is
890 # prohibited
891 pass
892 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +0000893 try:
Barry Warsawbf4d9592001-11-15 23:42:58 +0000894 if not hasattr(klass, '__safe_for_unpickling__'):
895 raise UnpicklingError('%s is not safe for unpickling' %
896 klass)
Guido van Rossum743d17e1998-09-15 20:25:57 +0000897 value = apply(klass, args)
898 except TypeError, err:
899 raise TypeError, "in constructor for %s: %s" % (
900 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000901 self.append(value)
902 dispatch[INST] = load_inst
903
904 def load_obj(self):
905 stack = self.stack
906 k = self.marker()
907 klass = stack[k + 1]
908 del stack[k + 1]
Tim Peters2344fae2001-01-15 00:50:52 +0000909 args = tuple(stack[k + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000910 del stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000911 instantiated = 0
912 if (not args and type(klass) is ClassType and
913 not hasattr(klass, "__getinitargs__")):
914 try:
915 value = _EmptyClass()
916 value.__class__ = klass
917 instantiated = 1
918 except RuntimeError:
919 # In restricted execution, assignment to inst.__class__ is
920 # prohibited
921 pass
922 if not instantiated:
923 value = apply(klass, args)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000924 self.append(value)
Tim Peters2344fae2001-01-15 00:50:52 +0000925 dispatch[OBJ] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000926
927 def load_global(self):
928 module = self.readline()[:-1]
929 name = self.readline()[:-1]
930 klass = self.find_class(module, name)
931 self.append(klass)
932 dispatch[GLOBAL] = load_global
933
934 def find_class(self, module, name):
Barry Warsawbf4d9592001-11-15 23:42:58 +0000935 __import__(module)
936 mod = sys.modules[module]
937 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000938 return klass
939
940 def load_reduce(self):
941 stack = self.stack
942
943 callable = stack[-2]
944 arg_tup = stack[-1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000945 del stack[-2:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000946
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000947 if type(callable) is not ClassType:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000948 if not callable in safe_constructors:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000949 try:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000950 safe = callable.__safe_for_unpickling__
951 except AttributeError:
952 safe = None
Guido van Rossuma48061a1995-01-10 00:31:14 +0000953
Tim Petersc32d8242001-04-10 02:48:53 +0000954 if not safe:
Tim Peters2344fae2001-01-15 00:50:52 +0000955 raise UnpicklingError, "%s is not safe for " \
956 "unpickling" % callable
Guido van Rossuma48061a1995-01-10 00:31:14 +0000957
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000958 if arg_tup is None:
Raymond Hettinger97394bc2002-05-21 17:22:02 +0000959 import warnings
960 warnings.warn("The None return argument form of __reduce__ is "
961 "deprecated. Return a tuple of arguments instead.",
Tim Peters8ac14952002-05-23 15:15:30 +0000962 DeprecationWarning)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000963 value = callable.__basicnew__()
964 else:
965 value = apply(callable, arg_tup)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000966 self.append(value)
967 dispatch[REDUCE] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +0000968
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000969 def load_pop(self):
970 del self.stack[-1]
971 dispatch[POP] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +0000972
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000973 def load_pop_mark(self):
974 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000975 del self.stack[k:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000976 dispatch[POP_MARK] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +0000977
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000978 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +0000979 self.append(self.stack[-1])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000980 dispatch[DUP] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +0000981
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000982 def load_get(self):
983 self.append(self.memo[self.readline()[:-1]])
984 dispatch[GET] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +0000985
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000986 def load_binget(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000987 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000988 self.append(self.memo[`i`])
989 dispatch[BINGET] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +0000990
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000991 def load_long_binget(self):
992 i = mloads('i' + self.read(4))
993 self.append(self.memo[`i`])
994 dispatch[LONG_BINGET] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +0000995
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000996 def load_put(self):
997 self.memo[self.readline()[:-1]] = self.stack[-1]
998 dispatch[PUT] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +0000999
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001000 def load_binput(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001001 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001002 self.memo[`i`] = self.stack[-1]
1003 dispatch[BINPUT] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001004
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001005 def load_long_binput(self):
1006 i = mloads('i' + self.read(4))
1007 self.memo[`i`] = self.stack[-1]
1008 dispatch[LONG_BINPUT] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001009
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001010 def load_append(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 list = stack[-1]
1014 list.append(value)
1015 dispatch[APPEND] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +00001016
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001017 def load_appends(self):
1018 stack = self.stack
1019 mark = self.marker()
1020 list = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001021 for i in range(mark + 1, len(stack)):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001022 list.append(stack[i])
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001023
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001024 del stack[mark:]
1025 dispatch[APPENDS] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +00001026
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001027 def load_setitem(self):
1028 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001029 value = stack.pop()
1030 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001031 dict = stack[-1]
1032 dict[key] = value
1033 dispatch[SETITEM] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001034
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001035 def load_setitems(self):
1036 stack = self.stack
1037 mark = self.marker()
1038 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001039 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001040 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001041
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001042 del stack[mark:]
1043 dispatch[SETITEMS] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001044
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001045 def load_build(self):
1046 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001047 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001048 inst = stack[-1]
1049 try:
1050 setstate = inst.__setstate__
1051 except AttributeError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001052 try:
1053 inst.__dict__.update(value)
1054 except RuntimeError:
1055 # XXX In restricted execution, the instance's __dict__ is not
1056 # accessible. Use the old way of unpickling the instance
1057 # variables. This is a semantic different when unpickling in
1058 # restricted vs. unrestricted modes.
1059 for k, v in value.items():
1060 setattr(inst, k, v)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001061 else:
1062 setstate(value)
1063 dispatch[BUILD] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001064
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001065 def load_mark(self):
1066 self.append(self.mark)
1067 dispatch[MARK] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001068
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001069 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001070 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001071 raise _Stop(value)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001072 dispatch[STOP] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001073
Guido van Rossume467be61997-12-05 19:42:42 +00001074# Helper class for load_inst/load_obj
1075
1076class _EmptyClass:
1077 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001078
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001079# Shorthands
1080
Jeremy Hyltonabe2c622001-10-15 21:29:28 +00001081try:
1082 from cStringIO import StringIO
1083except ImportError:
1084 from StringIO import StringIO
Guido van Rossumc7c5e691996-07-22 22:26:07 +00001085
Guido van Rossumf29d3d62003-01-27 22:47:53 +00001086def dump(object, file, proto=1):
1087 Pickler(file, proto).dump(object)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001088
Guido van Rossumf29d3d62003-01-27 22:47:53 +00001089def dumps(object, proto=1):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001090 file = StringIO()
Guido van Rossumf29d3d62003-01-27 22:47:53 +00001091 Pickler(file, proto).dump(object)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001092 return file.getvalue()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001093
1094def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001095 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001096
1097def loads(str):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001098 file = StringIO(str)
1099 return Unpickler(file).load()