blob: dffdc2c4105dded7bfd5a82077ef4fee923627a0 [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
Guido van Rossume0b90422003-01-28 03:17:21 +000048# Why use struct.pack() for pickling but marshal.loads() for
49# unpickling? struct.pack() is 40% faster than marshal.loads(), but
50# marshal.loads() is twice as fast as struct.unpack()!
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000051mloads = marshal.loads
Guido van Rossum0c891ce1995-03-14 15:09:05 +000052
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000053class PickleError(Exception):
Neal Norwitzefbb67b2002-05-30 12:12:04 +000054 """A common base class for the other pickling exceptions."""
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000055 pass
56
57class PicklingError(PickleError):
58 """This exception is raised when an unpicklable object is passed to the
59 dump() method.
60
61 """
62 pass
63
64class UnpicklingError(PickleError):
65 """This exception is raised when there is a problem unpickling an object,
66 such as a security violation.
67
68 Note that other exceptions may also be raised during unpickling, including
69 (but not necessarily limited to) AttributeError, EOFError, ImportError,
70 and IndexError.
71
72 """
73 pass
Guido van Rossum7849da81995-03-09 14:08:35 +000074
Guido van Rossumff871742000-12-13 18:11:56 +000075class _Stop(Exception):
76 def __init__(self, value):
77 self.value = value
78
Jeremy Hylton2b9d0291998-05-27 22:38:22 +000079try:
80 from org.python.core import PyStringMap
81except ImportError:
82 PyStringMap = None
83
Guido van Rossumdbb718f2001-09-21 19:22:34 +000084try:
85 UnicodeType
86except NameError:
87 UnicodeType = None
88
Tim Peters22a449a2003-01-27 20:16:36 +000089# Pickle opcodes. See pickletools.py for extensive docs. The listing
90# here is in kind-of alphabetical order of 1-character pickle code.
91# pickletools groups them by purpose.
Guido van Rossumdbb718f2001-09-21 19:22:34 +000092
Tim Peters22a449a2003-01-27 20:16:36 +000093MARK = '(' # push special markobject on stack
94STOP = '.' # every pickle ends with STOP
95POP = '0' # discard topmost stack item
96POP_MARK = '1' # discard stack top through topmost markobject
97DUP = '2' # duplicate top stack item
98FLOAT = 'F' # push float object; decimal string argument
99INT = 'I' # push integer or bool; decimal string argument
100BININT = 'J' # push four-byte signed int
101BININT1 = 'K' # push 1-byte unsigned int
102LONG = 'L' # push long; decimal string argument
103BININT2 = 'M' # push 2-byte unsigned int
104NONE = 'N' # push None
105PERSID = 'P' # push persistent object; id is taken from string arg
106BINPERSID = 'Q' # " " " ; " " " " stack
107REDUCE = 'R' # apply callable to argtuple, both on stack
108STRING = 'S' # push string; NL-terminated string argument
109BINSTRING = 'T' # push string; counted binary string argument
110SHORT_BINSTRING = 'U' # " " ; " " " " < 256 bytes
111UNICODE = 'V' # push Unicode string; raw-unicode-escaped'd argument
112BINUNICODE = 'X' # " " " ; counted UTF-8 string argument
113APPEND = 'a' # append stack top to list below it
114BUILD = 'b' # call __setstate__ or __dict__.update()
115GLOBAL = 'c' # push self.find_class(modname, name); 2 string args
116DICT = 'd' # build a dict from stack items
117EMPTY_DICT = '}' # push empty dict
118APPENDS = 'e' # extend list on stack by topmost stack slice
119GET = 'g' # push item from memo on stack; index is string arg
120BINGET = 'h' # " " " " " " ; " " 1-byte arg
121INST = 'i' # build & push class instance
122LONG_BINGET = 'j' # push item from memo on stack; index is 4-byte arg
123LIST = 'l' # build list from topmost stack items
124EMPTY_LIST = ']' # push empty list
125OBJ = 'o' # build & push class instance
126PUT = 'p' # store stack top in memo; index is string arg
127BINPUT = 'q' # " " " " " ; " " 1-byte arg
128LONG_BINPUT = 'r' # " " " " " ; " " 4-byte arg
129SETITEM = 's' # add key+value pair to dict
130TUPLE = 't' # build tuple from topmost stack items
131EMPTY_TUPLE = ')' # push empty tuple
132SETITEMS = 'u' # modify dict by adding topmost key+value pairs
133BINFLOAT = 'G' # push float; arg is 8-byte float encoding
134
135TRUE = 'I01\n' # not an opcode; see INT docs in pickletools.py
136FALSE = 'I00\n' # not an opcode; see INT docs in pickletools.py
Guido van Rossum77f6a652002-04-03 22:41:51 +0000137
Tim Peterse1054782003-01-28 00:22:12 +0000138# Protocol 2 (not yet implemented).
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000139
Tim Peterse1054782003-01-28 00:22:12 +0000140PROTO = '\x80' # identify pickle protocol
141NEWOBJ = '\x81' # build object by applying cls.__new__ to argtuple
142EXT1 = '\x82' # push object from extension registry; 1-byte index
143EXT2 = '\x83' # ditto, but 2-byte index
144EXT4 = '\x84' # ditto, but 4-byte index
145TUPLE1 = '\x85' # build 1-tuple from stack top
146TUPLE2 = '\x86' # build 2-tuple from two topmost stack items
147TUPLE3 = '\x87' # build 3-tuple from three topmost stack items
148NEWTRUE = '\x88' # push True
149NEWFALSE = '\x89' # push False
150LONG1 = '\x8a' # push long from < 256 bytes
151LONG4 = '\x8b' # push really big long
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000152
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000153_tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3]
154
Guido van Rossuma48061a1995-01-10 00:31:14 +0000155
Skip Montanaro23bafc62001-02-18 03:10:09 +0000156__all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
Neal Norwitzd5ba4ae2002-02-11 18:12:06 +0000157del x
Skip Montanaro23bafc62001-02-18 03:10:09 +0000158
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000159_quotes = ["'", '"']
160
Guido van Rossuma48061a1995-01-10 00:31:14 +0000161class Pickler:
162
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000163 def __init__(self, file, proto=1):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000164 """This takes a file-like object for writing a pickle data stream.
165
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000166 The optional proto argument tells the pickler to use the given
167 protocol; supported protocols are 0, 1, 2. The default
168 protocol is 1 (in previous Python versions the default was 0).
169
170 Protocol 1 is more efficient than protocol 0; protocol 2 is
171 more efficient than protocol 1. Protocol 2 is not the default
172 because it is not supported by older Python versions.
173
174 XXX Protocol 2 is not yet implemented.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000175
176 The file parameter must have a write() method that accepts a single
177 string argument. It can thus be an open file object, a StringIO
178 object, or any other custom object that meets this interface.
179
180 """
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000181 if not 0 <= proto <= 2:
182 raise ValueError, "pickle protocol must be 0, 1 or 2"
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000183 self.write = file.write
184 self.memo = {}
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000185 self.proto = proto
186 self.bin = proto >= 1
Guido van Rossuma48061a1995-01-10 00:31:14 +0000187
Fred Drake7f781c92002-05-01 20:33:53 +0000188 def clear_memo(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000189 """Clears the pickler's "memo".
190
191 The memo is the data structure that remembers which objects the
Tim Petersb377f8a2003-01-28 00:23:36 +0000192 pickler has already seen, so that shared or recursive objects are
193 pickled by reference and not by value. This method is useful when
194 re-using picklers.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000195
196 """
Fred Drake7f781c92002-05-01 20:33:53 +0000197 self.memo.clear()
198
Guido van Rossum3a41c612003-01-28 15:10:22 +0000199 def dump(self, obj):
200 """Write a pickled representation of obj to the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000201
202 Either the binary or ASCII format will be used, depending on the
203 value of the bin flag passed to the constructor.
204
205 """
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000206 if self.proto >= 2:
207 self.write(PROTO + chr(self.proto))
Guido van Rossum3a41c612003-01-28 15:10:22 +0000208 self.save(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000209 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000210
Jeremy Hylton3422c992003-01-24 19:29:52 +0000211 def memoize(self, obj):
212 """Store an object in the memo."""
213
Tim Peterse46b73f2003-01-27 21:22:10 +0000214 # The Pickler memo is a dictionary mapping object ids to 2-tuples
215 # that contain the Unpickler memo key and the object being memoized.
216 # The memo key is written to the pickle and will become
Jeremy Hylton3422c992003-01-24 19:29:52 +0000217 # the key in the Unpickler's memo. The object is stored in the
Tim Peterse46b73f2003-01-27 21:22:10 +0000218 # Pickler memo so that transient objects are kept alive during
219 # pickling.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000220
Tim Peterse46b73f2003-01-27 21:22:10 +0000221 # The use of the Unpickler memo length as the memo key is just a
222 # convention. The only requirement is that the memo values be unique.
223 # But there appears no advantage to any other scheme, and this
Tim Peterscbd0a322003-01-28 00:24:43 +0000224 # scheme allows the Unpickler memo to be implemented as a plain (but
Tim Peterse46b73f2003-01-27 21:22:10 +0000225 # growable) array, indexed by memo key.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000226 memo_len = len(self.memo)
227 self.write(self.put(memo_len))
Tim Peters518df0d2003-01-28 01:00:38 +0000228 self.memo[id(obj)] = memo_len, obj
Jeremy Hylton3422c992003-01-24 19:29:52 +0000229
Tim Petersbb38e302003-01-27 21:25:41 +0000230 # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000231 def put(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000232 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000233 if i < 256:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000234 return BINPUT + chr(i)
235 else:
236 return LONG_BINPUT + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000237
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000238 return PUT + `i` + '\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000239
Tim Petersbb38e302003-01-27 21:25:41 +0000240 # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000241 def get(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000242 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000243 if i < 256:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000244 return BINGET + chr(i)
245 else:
246 return LONG_BINGET + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000247
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000248 return GET + `i` + '\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000249
Guido van Rossum3a41c612003-01-28 15:10:22 +0000250 def save(self, obj):
251 pid = self.persistent_id(obj)
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000252 if pid is not None:
253 self.save_pers(pid)
254 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000255
Guido van Rossum3a41c612003-01-28 15:10:22 +0000256 memo = self.memo
257 d = id(obj)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000258 if d in memo:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000259 self.write(self.get(memo[d][0]))
260 return
261
Guido van Rossum3a41c612003-01-28 15:10:22 +0000262 t = type(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000263 try:
264 f = self.dispatch[t]
265 except KeyError:
Tim Petersb32a8312003-01-28 00:48:09 +0000266 pass
267 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000268 f(self, obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000269 return
270
Tim Petersb32a8312003-01-28 00:48:09 +0000271 # The dispatch table doesn't know about type t.
272 try:
273 issc = issubclass(t, TypeType)
274 except TypeError: # t is not a class
275 issc = 0
276 if issc:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000277 self.save_global(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000278 return
279
280 try:
281 reduce = dispatch_table[t]
282 except KeyError:
283 try:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000284 reduce = obj.__reduce__
Tim Petersb32a8312003-01-28 00:48:09 +0000285 except AttributeError:
286 raise PicklingError, \
287 "can't pickle %s object: %s" % (`t.__name__`,
Guido van Rossum3a41c612003-01-28 15:10:22 +0000288 `obj`)
Tim Petersb32a8312003-01-28 00:48:09 +0000289 else:
290 tup = reduce()
291 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000292 tup = reduce(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000293
294 if type(tup) is StringType:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000295 self.save_global(obj, tup)
Tim Petersb32a8312003-01-28 00:48:09 +0000296 return
297
298 if type(tup) is not TupleType:
299 raise PicklingError, "Value returned by %s must be a " \
300 "tuple" % reduce
301
302 l = len(tup)
303
304 if (l != 2) and (l != 3):
305 raise PicklingError, "tuple returned by %s must contain " \
306 "only two or three elements" % reduce
307
308 callable = tup[0]
309 arg_tup = tup[1]
310
311 if l > 2:
312 state = tup[2]
313 else:
314 state = None
315
316 if type(arg_tup) is not TupleType and arg_tup is not None:
317 raise PicklingError, "Second element of tuple returned " \
318 "by %s must be a tuple" % reduce
319
320 self.save_reduce(callable, arg_tup, state)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000321 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000322
Guido van Rossum3a41c612003-01-28 15:10:22 +0000323 def persistent_id(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000324 return None
325
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000326 def save_pers(self, pid):
Tim Petersbd1cdb92003-01-28 01:03:10 +0000327 if self.bin:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000328 self.save(pid)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000329 self.write(BINPERSID)
Tim Petersbd1cdb92003-01-28 01:03:10 +0000330 else:
331 self.write(PERSID + str(pid) + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000332
Jeremy Hylton3422c992003-01-24 19:29:52 +0000333 def save_reduce(self, acallable, arg_tup, state = None):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000334 write = self.write
335 save = self.save
336
Jeremy Hylton3422c992003-01-24 19:29:52 +0000337 if not callable(acallable):
338 raise PicklingError("__reduce__() must return callable as "
339 "first argument, not %s" % `acallable`)
Tim Peters22a449a2003-01-27 20:16:36 +0000340
Jeremy Hylton3422c992003-01-24 19:29:52 +0000341 save(acallable)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000342 save(arg_tup)
343 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000344
Tim Petersc32d8242001-04-10 02:48:53 +0000345 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000346 save(state)
347 write(BUILD)
348
349 dispatch = {}
350
Guido van Rossum3a41c612003-01-28 15:10:22 +0000351 def save_none(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000352 self.write(NONE)
353 dispatch[NoneType] = save_none
354
Guido van Rossum3a41c612003-01-28 15:10:22 +0000355 def save_bool(self, obj):
Guido van Rossum7d97d312003-01-28 04:25:27 +0000356 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000357 self.write(obj and NEWTRUE or NEWFALSE)
Guido van Rossum7d97d312003-01-28 04:25:27 +0000358 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000359 self.write(obj and TRUE or FALSE)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000360 dispatch[bool] = save_bool
361
Guido van Rossum3a41c612003-01-28 15:10:22 +0000362 def save_int(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000363 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000364 # If the int is small enough to fit in a signed 4-byte 2's-comp
365 # format, we can store it more efficiently than the general
366 # case.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000367 # First one- and two-byte unsigned ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000368 if obj >= 0:
369 if obj <= 0xff:
370 self.write(BININT1 + chr(obj))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000371 return
Guido van Rossum3a41c612003-01-28 15:10:22 +0000372 if obj <= 0xffff:
373 self.write(BININT2 + chr(obj&0xff) + chr(obj>>8))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000374 return
375 # Next check for 4-byte signed ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000376 high_bits = obj >> 31 # note that Python shift sign-extends
Tim Petersd95c2df2003-01-28 03:41:54 +0000377 if high_bits == 0 or high_bits == -1:
Tim Peters44714002001-04-10 05:02:52 +0000378 # All high bits are copies of bit 2**31, so the value
379 # fits in a 4-byte signed int.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000380 self.write(BININT + pack("<i", obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000381 return
Tim Peters44714002001-04-10 05:02:52 +0000382 # Text pickle, or int too big to fit in signed 4-byte format.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000383 self.write(INT + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000384 dispatch[IntType] = save_int
385
Guido van Rossum3a41c612003-01-28 15:10:22 +0000386 def save_long(self, obj, pack=struct.pack):
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000387 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000388 bytes = encode_long(obj)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000389 n = len(bytes)
390 if n < 256:
391 self.write(LONG1 + chr(n) + bytes)
392 else:
393 self.write(LONG4 + pack("<i", n) + bytes)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000394 self.write(LONG + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000395 dispatch[LongType] = save_long
396
Guido van Rossum3a41c612003-01-28 15:10:22 +0000397 def save_float(self, obj, pack=struct.pack):
Guido van Rossumd3703791998-10-22 20:15:36 +0000398 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000399 self.write(BINFLOAT + pack('>d', obj))
Guido van Rossumd3703791998-10-22 20:15:36 +0000400 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000401 self.write(FLOAT + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000402 dispatch[FloatType] = save_float
403
Guido van Rossum3a41c612003-01-28 15:10:22 +0000404 def save_string(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000405 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000406 n = len(obj)
Tim Petersbbf63cd2003-01-27 21:15:36 +0000407 if n < 256:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000408 self.write(SHORT_BINSTRING + chr(n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000409 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000410 self.write(BINSTRING + pack("<i", n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000411 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000412 self.write(STRING + `obj` + '\n')
413 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000414 dispatch[StringType] = save_string
415
Guido van Rossum3a41c612003-01-28 15:10:22 +0000416 def save_unicode(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000417 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000418 encoding = obj.encode('utf-8')
Tim Petersbbf63cd2003-01-27 21:15:36 +0000419 n = len(encoding)
Guido van Rossum5c938d02003-01-28 03:03:08 +0000420 self.write(BINUNICODE + pack("<i", n) + encoding)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000421 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000422 obj = obj.replace("\\", "\\u005c")
423 obj = obj.replace("\n", "\\u000a")
424 self.write(UNICODE + obj.encode('raw-unicode-escape') + '\n')
425 self.memoize(obj)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000426 dispatch[UnicodeType] = save_unicode
427
Guido van Rossum31584cb2001-01-22 14:53:29 +0000428 if StringType == UnicodeType:
429 # This is true for Jython
Guido van Rossum3a41c612003-01-28 15:10:22 +0000430 def save_string(self, obj, pack=struct.pack):
431 unicode = obj.isunicode()
Guido van Rossum31584cb2001-01-22 14:53:29 +0000432
Tim Petersc32d8242001-04-10 02:48:53 +0000433 if self.bin:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000434 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000435 obj = obj.encode("utf-8")
436 l = len(obj)
Tim Petersc32d8242001-04-10 02:48:53 +0000437 if l < 256 and not unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000438 self.write(SHORT_BINSTRING + chr(l) + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000439 else:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000440 s = pack("<i", l)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000441 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000442 self.write(BINUNICODE + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000443 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000444 self.write(BINSTRING + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000445 else:
Tim Peters658cba62001-02-09 20:06:00 +0000446 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000447 obj = obj.replace("\\", "\\u005c")
448 obj = obj.replace("\n", "\\u000a")
449 obj = obj.encode('raw-unicode-escape')
450 self.write(UNICODE + obj + '\n')
Guido van Rossum31584cb2001-01-22 14:53:29 +0000451 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000452 self.write(STRING + `obj` + '\n')
453 self.memoize(obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000454 dispatch[StringType] = save_string
Tim Peters658cba62001-02-09 20:06:00 +0000455
Guido van Rossum3a41c612003-01-28 15:10:22 +0000456 def save_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000457 write = self.write
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000458 proto = self.proto
459
Guido van Rossum3a41c612003-01-28 15:10:22 +0000460 n = len(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000461 if n == 0 and proto:
462 write(EMPTY_TUPLE)
463 return
464
465 save = self.save
466 memo = self.memo
467 if n <= 3 and proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000468 for element in obj:
Tim Petersd97da802003-01-28 05:48:29 +0000469 save(element)
470 # Subtle. Same as in the big comment below.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000471 if id(obj) in memo:
472 get = self.get(memo[id(obj)][0])
Tim Petersd97da802003-01-28 05:48:29 +0000473 write(POP * n + get)
474 else:
475 write(_tuplesize2code[n])
Guido van Rossum3a41c612003-01-28 15:10:22 +0000476 self.memoize(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000477 return
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000478
Tim Petersff57bff2003-01-28 05:34:53 +0000479 # proto 0, or proto 1 and tuple isn't empty, or proto > 1 and tuple
480 # has more than 3 elements.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000481 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000482 for element in obj:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000483 save(element)
484
Guido van Rossum3a41c612003-01-28 15:10:22 +0000485 if n and id(obj) in memo:
Tim Petersf558da02003-01-28 02:09:55 +0000486 # Subtle. d was not in memo when we entered save_tuple(), so
487 # the process of saving the tuple's elements must have saved
488 # the tuple itself: the tuple is recursive. The proper action
489 # now is to throw away everything we put on the stack, and
490 # simply GET the tuple (it's already constructed). This check
491 # could have been done in the "for element" loop instead, but
492 # recursive tuples are a rare thing.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000493 get = self.get(memo[id(obj)][0])
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000494 if proto:
Tim Petersf558da02003-01-28 02:09:55 +0000495 write(POP_MARK + get)
496 else: # proto 0 -- POP_MARK not available
Tim Petersd97da802003-01-28 05:48:29 +0000497 write(POP * (n+1) + get)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000498 return
499
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000500 # No recursion (including the empty-tuple case for protocol 0).
Tim Peters518df0d2003-01-28 01:00:38 +0000501 self.write(TUPLE)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000502 if obj: # No need to memoize empty tuple
503 self.memoize(obj)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000504
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000505 dispatch[TupleType] = save_tuple
506
Guido van Rossum3a41c612003-01-28 15:10:22 +0000507 def save_empty_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000508 self.write(EMPTY_TUPLE)
509
Guido van Rossum3a41c612003-01-28 15:10:22 +0000510 def save_list(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000511 write = self.write
512 save = self.save
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000513
Tim Petersc32d8242001-04-10 02:48:53 +0000514 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000515 write(EMPTY_LIST)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000516 self.memoize(obj)
517 n = len(obj)
Tim Peters21c18f02003-01-28 01:15:46 +0000518 if n > 1:
519 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000520 for element in obj:
Tim Peters21c18f02003-01-28 01:15:46 +0000521 save(element)
522 write(APPENDS)
523 elif n:
524 assert n == 1
Guido van Rossum3a41c612003-01-28 15:10:22 +0000525 save(obj[0])
Tim Peters21c18f02003-01-28 01:15:46 +0000526 write(APPEND)
527 # else the list is empty, and we're already done
528
529 else: # proto 0 -- can't use EMPTY_LIST or APPENDS
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000530 write(MARK + LIST)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000531 self.memoize(obj)
532 for element in obj:
Tim Peters21c18f02003-01-28 01:15:46 +0000533 save(element)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000534 write(APPEND)
535
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000536 dispatch[ListType] = save_list
537
Guido van Rossum3a41c612003-01-28 15:10:22 +0000538 def save_dict(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000539 write = self.write
540 save = self.save
Guido van Rossum3a41c612003-01-28 15:10:22 +0000541 items = obj.iteritems()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000542
Tim Petersc32d8242001-04-10 02:48:53 +0000543 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000544 write(EMPTY_DICT)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000545 self.memoize(obj)
546 if len(obj) > 1:
Tim Peters064567e2003-01-28 01:34:43 +0000547 write(MARK)
548 for key, value in items:
549 save(key)
550 save(value)
551 write(SETITEMS)
552 return
553
554 else: # proto 0 -- can't use EMPTY_DICT or SETITEMS
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000555 write(MARK + DICT)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000556 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000557
Guido van Rossum3a41c612003-01-28 15:10:22 +0000558 # proto 0 or len(obj) < 2
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000559 for key, value in items:
560 save(key)
561 save(value)
Tim Peters064567e2003-01-28 01:34:43 +0000562 write(SETITEM)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000563
564 dispatch[DictionaryType] = save_dict
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000565 if not PyStringMap is None:
566 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000567
Guido van Rossum3a41c612003-01-28 15:10:22 +0000568 def save_inst(self, obj):
569 cls = obj.__class__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000570
571 memo = self.memo
572 write = self.write
573 save = self.save
574
Guido van Rossum3a41c612003-01-28 15:10:22 +0000575 if hasattr(obj, '__getinitargs__'):
576 args = obj.__getinitargs__()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000577 len(args) # XXX Assert it's a sequence
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000578 _keep_alive(args, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000579 else:
580 args = ()
581
582 write(MARK)
583
Tim Petersc32d8242001-04-10 02:48:53 +0000584 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000585 save(cls)
Tim Peters3b769832003-01-28 03:51:36 +0000586 for arg in args:
587 save(arg)
588 write(OBJ)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000589 else:
Tim Peters3b769832003-01-28 03:51:36 +0000590 for arg in args:
591 save(arg)
592 write(INST + cls.__module__ + '\n' + cls.__name__ + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000593
Guido van Rossum3a41c612003-01-28 15:10:22 +0000594 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000595
596 try:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000597 getstate = obj.__getstate__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000598 except AttributeError:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000599 stuff = obj.__dict__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000600 else:
601 stuff = getstate()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000602 _keep_alive(stuff, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000603 save(stuff)
604 write(BUILD)
Tim Peters3b769832003-01-28 03:51:36 +0000605
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000606 dispatch[InstanceType] = save_inst
607
Guido van Rossum3a41c612003-01-28 15:10:22 +0000608 def save_global(self, obj, name = None):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000609 write = self.write
610 memo = self.memo
611
Tim Petersc32d8242001-04-10 02:48:53 +0000612 if name is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000613 name = obj.__name__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000614
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000615 try:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000616 module = obj.__module__
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000617 except AttributeError:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000618 module = whichmodule(obj, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000619
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000620 try:
621 __import__(module)
622 mod = sys.modules[module]
623 klass = getattr(mod, name)
624 except (ImportError, KeyError, AttributeError):
625 raise PicklingError(
626 "Can't pickle %r: it's not found as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000627 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000628 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000629 if klass is not obj:
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000630 raise PicklingError(
631 "Can't pickle %r: it's not the same object as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000632 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000633
Tim Peters518df0d2003-01-28 01:00:38 +0000634 write(GLOBAL + module + '\n' + name + '\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000635 self.memoize(obj)
Tim Peters3b769832003-01-28 03:51:36 +0000636
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000637 dispatch[ClassType] = save_global
638 dispatch[FunctionType] = save_global
639 dispatch[BuiltinFunctionType] = save_global
Tim Peters6d6c1a32001-08-02 04:15:00 +0000640 dispatch[TypeType] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000641
Guido van Rossuma48061a1995-01-10 00:31:14 +0000642
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000643def _keep_alive(x, memo):
644 """Keeps a reference to the object x in the memo.
645
646 Because we remember objects by their id, we have
647 to assure that possibly temporary objects are kept
648 alive by referencing them.
649 We store a reference at the id of the memo, which should
650 normally not be used unless someone tries to deepcopy
651 the memo itself...
652 """
653 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000654 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000655 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000656 # aha, this is the first one :-)
657 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000658
659
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000660classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000661
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000662def whichmodule(func, funcname):
663 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000664
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000665 Search sys.modules for the module.
666 Cache in classmap.
667 Return a module name.
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000668 If the function cannot be found, return __main__.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000669 """
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000670 if func in classmap:
671 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000672
673 for name, module in sys.modules.items():
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000674 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000675 continue # skip dummy package entries
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000676 if name != '__main__' and \
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000677 hasattr(module, funcname) and \
678 getattr(module, funcname) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000679 break
680 else:
681 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000682 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000683 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000684
685
686class Unpickler:
687
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000688 def __init__(self, file):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000689 """This takes a file-like object for reading a pickle data stream.
690
691 This class automatically determines whether the data stream was
692 written in binary mode or not, so it does not need a flag as in
693 the Pickler class factory.
694
695 The file-like object must have two methods, a read() method that
696 takes an integer argument, and a readline() method that requires no
697 arguments. Both methods should return a string. Thus file-like
698 object can be a file object opened for reading, a StringIO object,
699 or any other custom object that meets this interface.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000700 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000701 self.readline = file.readline
702 self.read = file.read
703 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000704
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000705 def load(self):
Guido van Rossum3a41c612003-01-28 15:10:22 +0000706 """Read a pickled object representation from the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000707
Guido van Rossum3a41c612003-01-28 15:10:22 +0000708 Return the reconstituted object hierarchy specified in the file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000709 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000710 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000711 self.stack = []
712 self.append = self.stack.append
713 read = self.read
714 dispatch = self.dispatch
715 try:
716 while 1:
717 key = read(1)
718 dispatch[key](self)
Guido van Rossumff871742000-12-13 18:11:56 +0000719 except _Stop, stopinst:
720 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000721
Tim Petersc23d18a2003-01-28 01:41:51 +0000722 # Return largest index k such that self.stack[k] is self.mark.
723 # If the stack doesn't contain a mark, eventually raises IndexError.
724 # This could be sped by maintaining another stack, of indices at which
725 # the mark appears. For that matter, the latter stack would suffice,
726 # and we wouldn't need to push mark objects on self.stack at all.
727 # Doing so is probably a good thing, though, since if the pickle is
728 # corrupt (or hostile) we may get a clue from finding self.mark embedded
729 # in unpickled objects.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000730 def marker(self):
731 stack = self.stack
732 mark = self.mark
733 k = len(stack)-1
734 while stack[k] is not mark: k = k-1
735 return k
736
737 dispatch = {}
738
739 def load_eof(self):
740 raise EOFError
741 dispatch[''] = load_eof
742
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000743 def load_proto(self):
744 proto = ord(self.read(1))
745 if not 0 <= proto <= 2:
746 raise ValueError, "unsupported pickle protocol: %d" % proto
747 dispatch[PROTO] = load_proto
748
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000749 def load_persid(self):
750 pid = self.readline()[:-1]
751 self.append(self.persistent_load(pid))
752 dispatch[PERSID] = load_persid
753
754 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000755 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000756 self.append(self.persistent_load(pid))
757 dispatch[BINPERSID] = load_binpersid
758
759 def load_none(self):
760 self.append(None)
761 dispatch[NONE] = load_none
762
Guido van Rossum7d97d312003-01-28 04:25:27 +0000763 def load_false(self):
764 self.append(False)
765 dispatch[NEWFALSE] = load_false
766
767 def load_true(self):
768 self.append(True)
769 dispatch[NEWTRUE] = load_true
770
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000771 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000772 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000773 if data == FALSE[1:]:
774 val = False
775 elif data == TRUE[1:]:
776 val = True
777 else:
778 try:
779 val = int(data)
780 except ValueError:
781 val = long(data)
782 self.append(val)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000783 dispatch[INT] = load_int
784
785 def load_binint(self):
786 self.append(mloads('i' + self.read(4)))
787 dispatch[BININT] = load_binint
788
789 def load_binint1(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000790 self.append(ord(self.read(1)))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000791 dispatch[BININT1] = load_binint1
792
793 def load_binint2(self):
794 self.append(mloads('i' + self.read(2) + '\000\000'))
795 dispatch[BININT2] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000796
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000797 def load_long(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000798 self.append(long(self.readline()[:-1], 0))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000799 dispatch[LONG] = load_long
800
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000801 def load_long1(self):
802 n = ord(self.read(1))
803 bytes = self.read(n)
804 return decode_long(bytes)
805 dispatch[LONG1] = load_long1
806
807 def load_long4(self):
808 n = mloads('i' + self.read(4))
809 bytes = self.read(n)
810 return decode_long(bytes)
811 dispatch[LONG4] = load_long4
812
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000813 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000814 self.append(float(self.readline()[:-1]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000815 dispatch[FLOAT] = load_float
816
Guido van Rossumd3703791998-10-22 20:15:36 +0000817 def load_binfloat(self, unpack=struct.unpack):
818 self.append(unpack('>d', self.read(8))[0])
819 dispatch[BINFLOAT] = load_binfloat
820
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000821 def load_string(self):
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000822 rep = self.readline()[:-1]
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000823 for q in _quotes:
824 if rep.startswith(q):
825 if not rep.endswith(q):
826 raise ValueError, "insecure string pickle"
827 rep = rep[len(q):-len(q)]
828 break
829 else:
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000830 raise ValueError, "insecure string pickle"
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000831 self.append(rep.decode("string-escape"))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000832 dispatch[STRING] = load_string
833
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000834 def _is_string_secure(self, s):
835 """Return true if s contains a string that is safe to eval
836
837 The definition of secure string is based on the implementation
838 in cPickle. s is secure as long as it only contains a quoted
839 string and optional trailing whitespace.
840 """
841 q = s[0]
842 if q not in ("'", '"'):
843 return 0
844 # find the closing quote
845 offset = 1
846 i = None
847 while 1:
848 try:
849 i = s.index(q, offset)
850 except ValueError:
851 # if there is an error the first time, there is no
852 # close quote
853 if offset == 1:
854 return 0
855 if s[i-1] != '\\':
856 break
857 # check to see if this one is escaped
858 nslash = 0
859 j = i - 1
860 while j >= offset and s[j] == '\\':
861 j = j - 1
862 nslash = nslash + 1
863 if nslash % 2 == 0:
864 break
865 offset = i + 1
866 for c in s[i+1:]:
867 if ord(c) > 32:
868 return 0
869 return 1
870
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000871 def load_binstring(self):
872 len = mloads('i' + self.read(4))
873 self.append(self.read(len))
874 dispatch[BINSTRING] = load_binstring
875
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000876 def load_unicode(self):
877 self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
878 dispatch[UNICODE] = load_unicode
879
880 def load_binunicode(self):
881 len = mloads('i' + self.read(4))
882 self.append(unicode(self.read(len),'utf-8'))
883 dispatch[BINUNICODE] = load_binunicode
884
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000885 def load_short_binstring(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000886 len = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000887 self.append(self.read(len))
888 dispatch[SHORT_BINSTRING] = load_short_binstring
889
890 def load_tuple(self):
891 k = self.marker()
892 self.stack[k:] = [tuple(self.stack[k+1:])]
893 dispatch[TUPLE] = load_tuple
894
895 def load_empty_tuple(self):
896 self.stack.append(())
897 dispatch[EMPTY_TUPLE] = load_empty_tuple
898
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000899 def load_tuple1(self):
900 self.stack[-1] = (self.stack[-1],)
901 dispatch[TUPLE1] = load_tuple1
902
903 def load_tuple2(self):
904 self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
905 dispatch[TUPLE2] = load_tuple2
906
907 def load_tuple3(self):
908 self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
909 dispatch[TUPLE3] = load_tuple3
910
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000911 def load_empty_list(self):
912 self.stack.append([])
913 dispatch[EMPTY_LIST] = load_empty_list
914
915 def load_empty_dictionary(self):
916 self.stack.append({})
917 dispatch[EMPTY_DICT] = load_empty_dictionary
918
919 def load_list(self):
920 k = self.marker()
921 self.stack[k:] = [self.stack[k+1:]]
922 dispatch[LIST] = load_list
923
924 def load_dict(self):
925 k = self.marker()
926 d = {}
927 items = self.stack[k+1:]
928 for i in range(0, len(items), 2):
929 key = items[i]
930 value = items[i+1]
931 d[key] = value
932 self.stack[k:] = [d]
933 dispatch[DICT] = load_dict
934
935 def load_inst(self):
936 k = self.marker()
937 args = tuple(self.stack[k+1:])
938 del self.stack[k:]
939 module = self.readline()[:-1]
940 name = self.readline()[:-1]
941 klass = self.find_class(module, name)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000942 instantiated = 0
943 if (not args and type(klass) is ClassType and
944 not hasattr(klass, "__getinitargs__")):
945 try:
946 value = _EmptyClass()
947 value.__class__ = klass
Guido van Rossumb19e2a31998-04-13 18:08:45 +0000948 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000949 except RuntimeError:
950 # In restricted execution, assignment to inst.__class__ is
951 # prohibited
952 pass
953 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +0000954 try:
Barry Warsawbf4d9592001-11-15 23:42:58 +0000955 if not hasattr(klass, '__safe_for_unpickling__'):
956 raise UnpicklingError('%s is not safe for unpickling' %
957 klass)
Guido van Rossum743d17e1998-09-15 20:25:57 +0000958 value = apply(klass, args)
959 except TypeError, err:
960 raise TypeError, "in constructor for %s: %s" % (
961 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000962 self.append(value)
963 dispatch[INST] = load_inst
964
965 def load_obj(self):
966 stack = self.stack
967 k = self.marker()
968 klass = stack[k + 1]
969 del stack[k + 1]
Tim Peters2344fae2001-01-15 00:50:52 +0000970 args = tuple(stack[k + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000971 del stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000972 instantiated = 0
973 if (not args and type(klass) is ClassType and
974 not hasattr(klass, "__getinitargs__")):
975 try:
976 value = _EmptyClass()
977 value.__class__ = klass
978 instantiated = 1
979 except RuntimeError:
980 # In restricted execution, assignment to inst.__class__ is
981 # prohibited
982 pass
983 if not instantiated:
984 value = apply(klass, args)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000985 self.append(value)
Tim Peters2344fae2001-01-15 00:50:52 +0000986 dispatch[OBJ] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000987
Guido van Rossum3a41c612003-01-28 15:10:22 +0000988 def load_newobj(self):
989 args = self.stack.pop()
990 cls = self.stack[-1]
991 obj = cls.__new__(cls, *args)
992 self.stack[-1:] = obj
993 dispatch[NEWOBJ] = load_newobj
994
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000995 def load_global(self):
996 module = self.readline()[:-1]
997 name = self.readline()[:-1]
998 klass = self.find_class(module, name)
999 self.append(klass)
1000 dispatch[GLOBAL] = load_global
1001
1002 def find_class(self, module, name):
Barry Warsawbf4d9592001-11-15 23:42:58 +00001003 __import__(module)
1004 mod = sys.modules[module]
1005 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001006 return klass
1007
1008 def load_reduce(self):
1009 stack = self.stack
1010
1011 callable = stack[-2]
1012 arg_tup = stack[-1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001013 del stack[-2:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001014
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001015 if type(callable) is not ClassType:
Raymond Hettinger54f02222002-06-01 14:18:47 +00001016 if not callable in safe_constructors:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001017 try:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001018 safe = callable.__safe_for_unpickling__
1019 except AttributeError:
1020 safe = None
Guido van Rossuma48061a1995-01-10 00:31:14 +00001021
Tim Petersc32d8242001-04-10 02:48:53 +00001022 if not safe:
Tim Peters2344fae2001-01-15 00:50:52 +00001023 raise UnpicklingError, "%s is not safe for " \
1024 "unpickling" % callable
Guido van Rossuma48061a1995-01-10 00:31:14 +00001025
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001026 if arg_tup is None:
Raymond Hettinger97394bc2002-05-21 17:22:02 +00001027 import warnings
1028 warnings.warn("The None return argument form of __reduce__ is "
1029 "deprecated. Return a tuple of arguments instead.",
Tim Peters8ac14952002-05-23 15:15:30 +00001030 DeprecationWarning)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001031 value = callable.__basicnew__()
1032 else:
1033 value = apply(callable, arg_tup)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001034 self.append(value)
1035 dispatch[REDUCE] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +00001036
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001037 def load_pop(self):
1038 del self.stack[-1]
1039 dispatch[POP] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +00001040
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001041 def load_pop_mark(self):
1042 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001043 del self.stack[k:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001044 dispatch[POP_MARK] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001045
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001046 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +00001047 self.append(self.stack[-1])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001048 dispatch[DUP] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +00001049
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001050 def load_get(self):
1051 self.append(self.memo[self.readline()[:-1]])
1052 dispatch[GET] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +00001053
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001054 def load_binget(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001055 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001056 self.append(self.memo[`i`])
1057 dispatch[BINGET] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001058
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001059 def load_long_binget(self):
1060 i = mloads('i' + self.read(4))
1061 self.append(self.memo[`i`])
1062 dispatch[LONG_BINGET] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001063
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001064 def load_put(self):
1065 self.memo[self.readline()[:-1]] = self.stack[-1]
1066 dispatch[PUT] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +00001067
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001068 def load_binput(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001069 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001070 self.memo[`i`] = self.stack[-1]
1071 dispatch[BINPUT] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001072
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001073 def load_long_binput(self):
1074 i = mloads('i' + self.read(4))
1075 self.memo[`i`] = self.stack[-1]
1076 dispatch[LONG_BINPUT] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001077
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001078 def load_append(self):
1079 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001080 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001081 list = stack[-1]
1082 list.append(value)
1083 dispatch[APPEND] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +00001084
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001085 def load_appends(self):
1086 stack = self.stack
1087 mark = self.marker()
1088 list = stack[mark - 1]
Tim Peters209ad952003-01-28 01:44:45 +00001089 list.extend(stack[mark + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001090 del stack[mark:]
1091 dispatch[APPENDS] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +00001092
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001093 def load_setitem(self):
1094 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001095 value = stack.pop()
1096 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001097 dict = stack[-1]
1098 dict[key] = value
1099 dispatch[SETITEM] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001100
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001101 def load_setitems(self):
1102 stack = self.stack
1103 mark = self.marker()
1104 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001105 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001106 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001107
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001108 del stack[mark:]
1109 dispatch[SETITEMS] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001110
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001111 def load_build(self):
1112 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001113 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001114 inst = stack[-1]
1115 try:
1116 setstate = inst.__setstate__
1117 except AttributeError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001118 try:
1119 inst.__dict__.update(value)
1120 except RuntimeError:
1121 # XXX In restricted execution, the instance's __dict__ is not
1122 # accessible. Use the old way of unpickling the instance
1123 # variables. This is a semantic different when unpickling in
1124 # restricted vs. unrestricted modes.
1125 for k, v in value.items():
1126 setattr(inst, k, v)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001127 else:
1128 setstate(value)
1129 dispatch[BUILD] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001130
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001131 def load_mark(self):
1132 self.append(self.mark)
1133 dispatch[MARK] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001134
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001135 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001136 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001137 raise _Stop(value)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001138 dispatch[STOP] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001139
Guido van Rossume467be61997-12-05 19:42:42 +00001140# Helper class for load_inst/load_obj
1141
1142class _EmptyClass:
1143 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001144
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001145# Encode/decode longs.
1146
1147def encode_long(x):
1148 r"""Encode a long to a two's complement little-ending binary string.
1149 >>> encode_long(255L)
1150 '\xff\x00'
1151 >>> encode_long(32767L)
1152 '\xff\x7f'
1153 >>> encode_long(-256L)
1154 '\x00\xff'
1155 >>> encode_long(-32768L)
1156 '\x00\x80'
1157 >>> encode_long(-128L)
1158 '\x80'
1159 >>> encode_long(127L)
1160 '\x7f'
1161 >>>
1162 """
1163 digits = []
1164 while not -128 <= x < 128:
1165 digits.append(x & 0xff)
1166 x >>= 8
1167 digits.append(x & 0xff)
1168 return "".join(map(chr, digits))
1169
1170def decode_long(data):
1171 r"""Decode a long from a two's complement little-endian binary string.
1172 >>> decode_long("\xff\x00")
1173 255L
1174 >>> decode_long("\xff\x7f")
1175 32767L
1176 >>> decode_long("\x00\xff")
1177 -256L
1178 >>> decode_long("\x00\x80")
1179 -32768L
1180 >>> decode_long("\x80")
1181 -128L
1182 >>> decode_long("\x7f")
1183 127L
1184 """
1185 x = 0L
1186 i = 0L
1187 for c in data:
1188 x |= long(ord(c)) << i
1189 i += 8L
1190 if data and ord(c) >= 0x80:
1191 x -= 1L << i
1192 return x
1193
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001194# Shorthands
1195
Jeremy Hyltonabe2c622001-10-15 21:29:28 +00001196try:
1197 from cStringIO import StringIO
1198except ImportError:
1199 from StringIO import StringIO
Guido van Rossumc7c5e691996-07-22 22:26:07 +00001200
Guido van Rossum3a41c612003-01-28 15:10:22 +00001201def dump(obj, file, proto=1):
1202 Pickler(file, proto).dump(obj)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001203
Guido van Rossum3a41c612003-01-28 15:10:22 +00001204def dumps(obj, proto=1):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001205 file = StringIO()
Guido van Rossum3a41c612003-01-28 15:10:22 +00001206 Pickler(file, proto).dump(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001207 return file.getvalue()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001208
1209def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001210 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001211
1212def loads(str):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001213 file = StringIO(str)
1214 return Unpickler(file).load()
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001215
1216# Doctest
1217
1218def _test():
1219 import doctest
1220 return doctest.testmod()
1221
1222if __name__ == "__main__":
1223 _test()