blob: e4336160c73def4cab08f20521b1015643e2ef56 [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 Rossumbc64e222003-01-28 16:34:19 +000035import warnings
Guido van Rossuma48061a1995-01-10 00:31:14 +000036
Skip Montanaro352674d2001-02-07 23:14:30 +000037__all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler",
38 "Unpickler", "dump", "dumps", "load", "loads"]
39
Guido van Rossumf29d3d62003-01-27 22:47:53 +000040# These are purely informational; no code usues these
41format_version = "2.0" # File format version we write
42compatible_formats = ["1.0", # Original protocol 0
Guido van Rossumbc64e222003-01-28 16:34:19 +000043 "1.1", # Protocol 0 with INST added
Guido van Rossumf29d3d62003-01-27 22:47:53 +000044 "1.2", # Original protocol 1
45 "1.3", # Protocol 1 with BINFLOAT added
46 "2.0", # Protocol 2
47 ] # Old format versions we can read
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000048
Guido van Rossume0b90422003-01-28 03:17:21 +000049# Why use struct.pack() for pickling but marshal.loads() for
50# unpickling? struct.pack() is 40% faster than marshal.loads(), but
51# marshal.loads() is twice as fast as struct.unpack()!
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000052mloads = marshal.loads
Guido van Rossum0c891ce1995-03-14 15:09:05 +000053
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000054class PickleError(Exception):
Neal Norwitzefbb67b2002-05-30 12:12:04 +000055 """A common base class for the other pickling exceptions."""
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000056 pass
57
58class PicklingError(PickleError):
59 """This exception is raised when an unpicklable object is passed to the
60 dump() method.
61
62 """
63 pass
64
65class UnpicklingError(PickleError):
66 """This exception is raised when there is a problem unpickling an object,
67 such as a security violation.
68
69 Note that other exceptions may also be raised during unpickling, including
70 (but not necessarily limited to) AttributeError, EOFError, ImportError,
71 and IndexError.
72
73 """
74 pass
Guido van Rossum7849da81995-03-09 14:08:35 +000075
Guido van Rossumff871742000-12-13 18:11:56 +000076class _Stop(Exception):
77 def __init__(self, value):
78 self.value = value
79
Guido van Rossum533dbcf2003-01-28 17:55:05 +000080# Jython has PyStringMap; it's a dict subclass with string keys
Jeremy Hylton2b9d0291998-05-27 22:38:22 +000081try:
82 from org.python.core import PyStringMap
83except ImportError:
84 PyStringMap = None
85
Guido van Rossum533dbcf2003-01-28 17:55:05 +000086# UnicodeType may or may not be exported (normally imported from types)
Guido van Rossumdbb718f2001-09-21 19:22:34 +000087try:
88 UnicodeType
89except NameError:
90 UnicodeType = None
91
Tim Peters22a449a2003-01-27 20:16:36 +000092# Pickle opcodes. See pickletools.py for extensive docs. The listing
93# here is in kind-of alphabetical order of 1-character pickle code.
94# pickletools groups them by purpose.
Guido van Rossumdbb718f2001-09-21 19:22:34 +000095
Tim Peters22a449a2003-01-27 20:16:36 +000096MARK = '(' # push special markobject on stack
97STOP = '.' # every pickle ends with STOP
98POP = '0' # discard topmost stack item
99POP_MARK = '1' # discard stack top through topmost markobject
100DUP = '2' # duplicate top stack item
101FLOAT = 'F' # push float object; decimal string argument
102INT = 'I' # push integer or bool; decimal string argument
103BININT = 'J' # push four-byte signed int
104BININT1 = 'K' # push 1-byte unsigned int
105LONG = 'L' # push long; decimal string argument
106BININT2 = 'M' # push 2-byte unsigned int
107NONE = 'N' # push None
108PERSID = 'P' # push persistent object; id is taken from string arg
109BINPERSID = 'Q' # " " " ; " " " " stack
110REDUCE = 'R' # apply callable to argtuple, both on stack
111STRING = 'S' # push string; NL-terminated string argument
112BINSTRING = 'T' # push string; counted binary string argument
113SHORT_BINSTRING = 'U' # " " ; " " " " < 256 bytes
114UNICODE = 'V' # push Unicode string; raw-unicode-escaped'd argument
115BINUNICODE = 'X' # " " " ; counted UTF-8 string argument
116APPEND = 'a' # append stack top to list below it
117BUILD = 'b' # call __setstate__ or __dict__.update()
118GLOBAL = 'c' # push self.find_class(modname, name); 2 string args
119DICT = 'd' # build a dict from stack items
120EMPTY_DICT = '}' # push empty dict
121APPENDS = 'e' # extend list on stack by topmost stack slice
122GET = 'g' # push item from memo on stack; index is string arg
123BINGET = 'h' # " " " " " " ; " " 1-byte arg
124INST = 'i' # build & push class instance
125LONG_BINGET = 'j' # push item from memo on stack; index is 4-byte arg
126LIST = 'l' # build list from topmost stack items
127EMPTY_LIST = ']' # push empty list
128OBJ = 'o' # build & push class instance
129PUT = 'p' # store stack top in memo; index is string arg
130BINPUT = 'q' # " " " " " ; " " 1-byte arg
131LONG_BINPUT = 'r' # " " " " " ; " " 4-byte arg
132SETITEM = 's' # add key+value pair to dict
133TUPLE = 't' # build tuple from topmost stack items
134EMPTY_TUPLE = ')' # push empty tuple
135SETITEMS = 'u' # modify dict by adding topmost key+value pairs
136BINFLOAT = 'G' # push float; arg is 8-byte float encoding
137
138TRUE = 'I01\n' # not an opcode; see INT docs in pickletools.py
139FALSE = 'I00\n' # not an opcode; see INT docs in pickletools.py
Guido van Rossum77f6a652002-04-03 22:41:51 +0000140
Tim Peterse1054782003-01-28 00:22:12 +0000141# Protocol 2 (not yet implemented).
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000142
Tim Peterse1054782003-01-28 00:22:12 +0000143PROTO = '\x80' # identify pickle protocol
144NEWOBJ = '\x81' # build object by applying cls.__new__ to argtuple
145EXT1 = '\x82' # push object from extension registry; 1-byte index
146EXT2 = '\x83' # ditto, but 2-byte index
147EXT4 = '\x84' # ditto, but 4-byte index
148TUPLE1 = '\x85' # build 1-tuple from stack top
149TUPLE2 = '\x86' # build 2-tuple from two topmost stack items
150TUPLE3 = '\x87' # build 3-tuple from three topmost stack items
151NEWTRUE = '\x88' # push True
152NEWFALSE = '\x89' # push False
153LONG1 = '\x8a' # push long from < 256 bytes
154LONG4 = '\x8b' # push really big long
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000155
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000156_tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3]
157
Guido van Rossuma48061a1995-01-10 00:31:14 +0000158
Skip Montanaro23bafc62001-02-18 03:10:09 +0000159__all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
Neal Norwitzd5ba4ae2002-02-11 18:12:06 +0000160del x
Skip Montanaro23bafc62001-02-18 03:10:09 +0000161
Guido van Rossum1be31752003-01-28 15:19:53 +0000162
163# Pickling machinery
164
Guido van Rossuma48061a1995-01-10 00:31:14 +0000165class Pickler:
166
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000167 def __init__(self, file, proto=1):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000168 """This takes a file-like object for writing a pickle data stream.
169
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000170 The optional proto argument tells the pickler to use the given
171 protocol; supported protocols are 0, 1, 2. The default
172 protocol is 1 (in previous Python versions the default was 0).
173
174 Protocol 1 is more efficient than protocol 0; protocol 2 is
175 more efficient than protocol 1. Protocol 2 is not the default
176 because it is not supported by older Python versions.
177
178 XXX Protocol 2 is not yet implemented.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000179
180 The file parameter must have a write() method that accepts a single
181 string argument. It can thus be an open file object, a StringIO
182 object, or any other custom object that meets this interface.
183
184 """
Guido van Rossum1be31752003-01-28 15:19:53 +0000185 if proto not in (0, 1, 2):
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000186 raise ValueError, "pickle protocol must be 0, 1 or 2"
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000187 self.write = file.write
188 self.memo = {}
Guido van Rossum1be31752003-01-28 15:19:53 +0000189 self.proto = int(proto)
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000190 self.bin = proto >= 1
Guido van Rossuma48061a1995-01-10 00:31:14 +0000191
Fred Drake7f781c92002-05-01 20:33:53 +0000192 def clear_memo(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000193 """Clears the pickler's "memo".
194
195 The memo is the data structure that remembers which objects the
Tim Petersb377f8a2003-01-28 00:23:36 +0000196 pickler has already seen, so that shared or recursive objects are
197 pickled by reference and not by value. This method is useful when
198 re-using picklers.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000199
200 """
Fred Drake7f781c92002-05-01 20:33:53 +0000201 self.memo.clear()
202
Guido van Rossum3a41c612003-01-28 15:10:22 +0000203 def dump(self, obj):
204 """Write a pickled representation of obj to the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000205
206 Either the binary or ASCII format will be used, depending on the
207 value of the bin flag passed to the constructor.
208
209 """
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000210 if self.proto >= 2:
211 self.write(PROTO + chr(self.proto))
Guido van Rossum3a41c612003-01-28 15:10:22 +0000212 self.save(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000213 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000214
Jeremy Hylton3422c992003-01-24 19:29:52 +0000215 def memoize(self, obj):
216 """Store an object in the memo."""
217
Tim Peterse46b73f2003-01-27 21:22:10 +0000218 # The Pickler memo is a dictionary mapping object ids to 2-tuples
219 # that contain the Unpickler memo key and the object being memoized.
220 # The memo key is written to the pickle and will become
Jeremy Hylton3422c992003-01-24 19:29:52 +0000221 # the key in the Unpickler's memo. The object is stored in the
Tim Peterse46b73f2003-01-27 21:22:10 +0000222 # Pickler memo so that transient objects are kept alive during
223 # pickling.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000224
Tim Peterse46b73f2003-01-27 21:22:10 +0000225 # The use of the Unpickler memo length as the memo key is just a
226 # convention. The only requirement is that the memo values be unique.
227 # But there appears no advantage to any other scheme, and this
Tim Peterscbd0a322003-01-28 00:24:43 +0000228 # scheme allows the Unpickler memo to be implemented as a plain (but
Tim Peterse46b73f2003-01-27 21:22:10 +0000229 # growable) array, indexed by memo key.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000230 memo_len = len(self.memo)
231 self.write(self.put(memo_len))
Tim Peters518df0d2003-01-28 01:00:38 +0000232 self.memo[id(obj)] = memo_len, obj
Jeremy Hylton3422c992003-01-24 19:29:52 +0000233
Tim Petersbb38e302003-01-27 21:25:41 +0000234 # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000235 def put(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000236 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000237 if i < 256:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000238 return BINPUT + chr(i)
239 else:
240 return LONG_BINPUT + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000241
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000242 return PUT + `i` + '\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000243
Tim Petersbb38e302003-01-27 21:25:41 +0000244 # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000245 def get(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000246 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000247 if i < 256:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000248 return BINGET + chr(i)
249 else:
250 return LONG_BINGET + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000251
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000252 return GET + `i` + '\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000253
Guido van Rossum533dbcf2003-01-28 17:55:05 +0000254 def save(self, obj,
255 _builtin_type = (int, long, float, complex, str, unicode,
256 tuple, list, dict),
257 ):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000258 # Check for persistent id (defined by a subclass)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000259 pid = self.persistent_id(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000260 if pid:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000261 self.save_pers(pid)
262 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000263
Guido van Rossumbc64e222003-01-28 16:34:19 +0000264 # Check the memo
265 x = self.memo.get(id(obj))
266 if x:
267 self.write(self.get(x[0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000268 return
269
Guido van Rossumbc64e222003-01-28 16:34:19 +0000270 # Check the type dispatch table
Guido van Rossum3a41c612003-01-28 15:10:22 +0000271 t = type(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000272 f = self.dispatch.get(t)
273 if f:
274 f(self, obj) # Call unbound method with explicit self
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000275 return
276
Guido van Rossumbc64e222003-01-28 16:34:19 +0000277 # Check for a class with a custom metaclass; treat as regular class
Tim Petersb32a8312003-01-28 00:48:09 +0000278 try:
279 issc = issubclass(t, TypeType)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000280 except TypeError: # t is not a class (old Boost; see SF #502085)
Tim Petersb32a8312003-01-28 00:48:09 +0000281 issc = 0
282 if issc:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000283 self.save_global(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000284 return
285
Guido van Rossum533dbcf2003-01-28 17:55:05 +0000286 # Check for instance of subclass of common built-in types
287 # XXX This block is experimental code that will go away!
288 if self.proto >= 2:
289 if isinstance(obj, _builtin_type):
290 assert t not in _builtin_type # Proper subclass
291 args = ()
292 getnewargs = getattr(obj, "__getnewargs__", None)
293 if getnewargs:
294 args = getnewargs() # This better not reference obj
295 self.save_global(t)
296 self.save(args)
297 self.write(NEWOBJ)
298 self.memoize(obj)
299 getstate = getattr(obj, "__getstate__", None)
300 if getstate:
301 state = getstate()
302 else:
303 state = getattr(obj, "__dict__", None)
304 # XXX What about __slots__?
305 if state is not None:
306 self.save(state)
307 self.write(BUILD)
308 return
309
Guido van Rossumbc64e222003-01-28 16:34:19 +0000310 # Check copy_reg.dispatch_table
311 reduce = dispatch_table.get(t)
312 if reduce:
313 rv = reduce(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000314 else:
Guido van Rossumbc64e222003-01-28 16:34:19 +0000315 # Check for __reduce__ method
316 reduce = getattr(obj, "__reduce__", None)
317 if not reduce:
318 raise PicklingError("Can't pickle %r object: %r" %
319 (t.__name__, obj))
320 rv = reduce()
Tim Petersb32a8312003-01-28 00:48:09 +0000321
Guido van Rossumbc64e222003-01-28 16:34:19 +0000322 # Check for string returned by reduce(), meaning "save as global"
323 if type(rv) is StringType:
324 self.save_global(obj, rv)
Tim Petersb32a8312003-01-28 00:48:09 +0000325 return
326
Guido van Rossumbc64e222003-01-28 16:34:19 +0000327 # Assert that reduce() returned a tuple
328 if type(rv) is not TupleType:
329 raise PicklingError("%s must return string or tuple" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000330
Guido van Rossumbc64e222003-01-28 16:34:19 +0000331 # Assert that it returned a 2-tuple or 3-tuple, and unpack it
332 l = len(rv)
333 if l == 2:
334 func, args = rv
Tim Petersb32a8312003-01-28 00:48:09 +0000335 state = None
Guido van Rossumbc64e222003-01-28 16:34:19 +0000336 elif l == 3:
337 func, args, state = rv
338 else:
339 raise PicklingError("Tuple returned by %s must have "
340 "exactly two or three elements" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000341
Guido van Rossumbc64e222003-01-28 16:34:19 +0000342 # Save the reduce() output and finally memoize the object
343 self.save_reduce(func, args, state)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000344 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000345
Guido van Rossum3a41c612003-01-28 15:10:22 +0000346 def persistent_id(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000347 # This exists so a subclass can override it
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000348 return None
349
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000350 def save_pers(self, pid):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000351 # Save a persistent id reference
Tim Petersbd1cdb92003-01-28 01:03:10 +0000352 if self.bin:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000353 self.save(pid)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000354 self.write(BINPERSID)
Tim Petersbd1cdb92003-01-28 01:03:10 +0000355 else:
356 self.write(PERSID + str(pid) + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000357
Guido van Rossumbc64e222003-01-28 16:34:19 +0000358 def save_reduce(self, func, args, state=None):
359 # This API is be called by some subclasses
360
361 # Assert that args is a tuple or None
362 if not isinstance(args, TupleType):
363 if args is None:
364 # A hack for Jim Fulton's ExtensionClass, now deprecated.
365 # See load_reduce()
366 warnings.warn("__basicnew__ special case is deprecated",
367 DeprecationWarning)
368 else:
369 raise PicklingError(
370 "args from reduce() should be a tuple")
371
372 # Assert that func is callable
373 if not callable(func):
374 raise PicklingError("func from reduce should be callable")
375
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000376 save = self.save
Guido van Rossumbc64e222003-01-28 16:34:19 +0000377 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000378
Guido van Rossumbc64e222003-01-28 16:34:19 +0000379 save(func)
380 save(args)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000381 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000382
Tim Petersc32d8242001-04-10 02:48:53 +0000383 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000384 save(state)
385 write(BUILD)
386
Guido van Rossumbc64e222003-01-28 16:34:19 +0000387 # Methods below this point are dispatched through the dispatch table
388
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000389 dispatch = {}
390
Guido van Rossum3a41c612003-01-28 15:10:22 +0000391 def save_none(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000392 self.write(NONE)
393 dispatch[NoneType] = save_none
394
Guido van Rossum3a41c612003-01-28 15:10:22 +0000395 def save_bool(self, obj):
Guido van Rossum7d97d312003-01-28 04:25:27 +0000396 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000397 self.write(obj and NEWTRUE or NEWFALSE)
Guido van Rossum7d97d312003-01-28 04:25:27 +0000398 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000399 self.write(obj and TRUE or FALSE)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000400 dispatch[bool] = save_bool
401
Guido van Rossum3a41c612003-01-28 15:10:22 +0000402 def save_int(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000403 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000404 # If the int is small enough to fit in a signed 4-byte 2's-comp
405 # format, we can store it more efficiently than the general
406 # case.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000407 # First one- and two-byte unsigned ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000408 if obj >= 0:
409 if obj <= 0xff:
410 self.write(BININT1 + chr(obj))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000411 return
Guido van Rossum3a41c612003-01-28 15:10:22 +0000412 if obj <= 0xffff:
413 self.write(BININT2 + chr(obj&0xff) + chr(obj>>8))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000414 return
415 # Next check for 4-byte signed ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000416 high_bits = obj >> 31 # note that Python shift sign-extends
Tim Petersd95c2df2003-01-28 03:41:54 +0000417 if high_bits == 0 or high_bits == -1:
Tim Peters44714002001-04-10 05:02:52 +0000418 # All high bits are copies of bit 2**31, so the value
419 # fits in a 4-byte signed int.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000420 self.write(BININT + pack("<i", obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000421 return
Tim Peters44714002001-04-10 05:02:52 +0000422 # Text pickle, or int too big to fit in signed 4-byte format.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000423 self.write(INT + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000424 dispatch[IntType] = save_int
425
Guido van Rossum3a41c612003-01-28 15:10:22 +0000426 def save_long(self, obj, pack=struct.pack):
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000427 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000428 bytes = encode_long(obj)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000429 n = len(bytes)
430 if n < 256:
431 self.write(LONG1 + chr(n) + bytes)
432 else:
433 self.write(LONG4 + pack("<i", n) + bytes)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000434 self.write(LONG + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000435 dispatch[LongType] = save_long
436
Guido van Rossum3a41c612003-01-28 15:10:22 +0000437 def save_float(self, obj, pack=struct.pack):
Guido van Rossumd3703791998-10-22 20:15:36 +0000438 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000439 self.write(BINFLOAT + pack('>d', obj))
Guido van Rossumd3703791998-10-22 20:15:36 +0000440 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000441 self.write(FLOAT + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000442 dispatch[FloatType] = save_float
443
Guido van Rossum3a41c612003-01-28 15:10:22 +0000444 def save_string(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000445 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000446 n = len(obj)
Tim Petersbbf63cd2003-01-27 21:15:36 +0000447 if n < 256:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000448 self.write(SHORT_BINSTRING + chr(n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000449 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000450 self.write(BINSTRING + pack("<i", n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000451 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000452 self.write(STRING + `obj` + '\n')
453 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000454 dispatch[StringType] = save_string
455
Guido van Rossum3a41c612003-01-28 15:10:22 +0000456 def save_unicode(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000457 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000458 encoding = obj.encode('utf-8')
Tim Petersbbf63cd2003-01-27 21:15:36 +0000459 n = len(encoding)
Guido van Rossum5c938d02003-01-28 03:03:08 +0000460 self.write(BINUNICODE + pack("<i", n) + encoding)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000461 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000462 obj = obj.replace("\\", "\\u005c")
463 obj = obj.replace("\n", "\\u000a")
464 self.write(UNICODE + obj.encode('raw-unicode-escape') + '\n')
465 self.memoize(obj)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000466 dispatch[UnicodeType] = save_unicode
467
Guido van Rossum31584cb2001-01-22 14:53:29 +0000468 if StringType == UnicodeType:
469 # This is true for Jython
Guido van Rossum3a41c612003-01-28 15:10:22 +0000470 def save_string(self, obj, pack=struct.pack):
471 unicode = obj.isunicode()
Guido van Rossum31584cb2001-01-22 14:53:29 +0000472
Tim Petersc32d8242001-04-10 02:48:53 +0000473 if self.bin:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000474 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000475 obj = obj.encode("utf-8")
476 l = len(obj)
Tim Petersc32d8242001-04-10 02:48:53 +0000477 if l < 256 and not unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000478 self.write(SHORT_BINSTRING + chr(l) + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000479 else:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000480 s = pack("<i", l)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000481 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000482 self.write(BINUNICODE + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000483 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000484 self.write(BINSTRING + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000485 else:
Tim Peters658cba62001-02-09 20:06:00 +0000486 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000487 obj = obj.replace("\\", "\\u005c")
488 obj = obj.replace("\n", "\\u000a")
489 obj = obj.encode('raw-unicode-escape')
490 self.write(UNICODE + obj + '\n')
Guido van Rossum31584cb2001-01-22 14:53:29 +0000491 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000492 self.write(STRING + `obj` + '\n')
493 self.memoize(obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000494 dispatch[StringType] = save_string
Tim Peters658cba62001-02-09 20:06:00 +0000495
Guido van Rossum3a41c612003-01-28 15:10:22 +0000496 def save_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000497 write = self.write
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000498 proto = self.proto
499
Guido van Rossum3a41c612003-01-28 15:10:22 +0000500 n = len(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000501 if n == 0 and proto:
502 write(EMPTY_TUPLE)
503 return
504
505 save = self.save
506 memo = self.memo
507 if n <= 3 and proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000508 for element in obj:
Tim Petersd97da802003-01-28 05:48:29 +0000509 save(element)
510 # Subtle. Same as in the big comment below.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000511 if id(obj) in memo:
512 get = self.get(memo[id(obj)][0])
Tim Petersd97da802003-01-28 05:48:29 +0000513 write(POP * n + get)
514 else:
515 write(_tuplesize2code[n])
Guido van Rossum3a41c612003-01-28 15:10:22 +0000516 self.memoize(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000517 return
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000518
Tim Petersff57bff2003-01-28 05:34:53 +0000519 # proto 0, or proto 1 and tuple isn't empty, or proto > 1 and tuple
520 # has more than 3 elements.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000521 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000522 for element in obj:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000523 save(element)
524
Guido van Rossum3a41c612003-01-28 15:10:22 +0000525 if n and id(obj) in memo:
Tim Petersf558da02003-01-28 02:09:55 +0000526 # Subtle. d was not in memo when we entered save_tuple(), so
527 # the process of saving the tuple's elements must have saved
528 # the tuple itself: the tuple is recursive. The proper action
529 # now is to throw away everything we put on the stack, and
530 # simply GET the tuple (it's already constructed). This check
531 # could have been done in the "for element" loop instead, but
532 # recursive tuples are a rare thing.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000533 get = self.get(memo[id(obj)][0])
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000534 if proto:
Tim Petersf558da02003-01-28 02:09:55 +0000535 write(POP_MARK + get)
536 else: # proto 0 -- POP_MARK not available
Tim Petersd97da802003-01-28 05:48:29 +0000537 write(POP * (n+1) + get)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000538 return
539
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000540 # No recursion (including the empty-tuple case for protocol 0).
Tim Peters518df0d2003-01-28 01:00:38 +0000541 self.write(TUPLE)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000542 if obj: # No need to memoize empty tuple
543 self.memoize(obj)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000544
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000545 dispatch[TupleType] = save_tuple
546
Tim Petersa6ae9a22003-01-28 16:58:41 +0000547 # save_empty_tuple() isn't used by anything in Python 2.3. However, I
548 # found a Pickler subclass in Zope3 that calls it, so it's not harmless
549 # to remove it.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000550 def save_empty_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000551 self.write(EMPTY_TUPLE)
552
Guido van Rossum3a41c612003-01-28 15:10:22 +0000553 def save_list(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000554 write = self.write
555 save = self.save
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000556
Tim Petersc32d8242001-04-10 02:48:53 +0000557 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000558 write(EMPTY_LIST)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000559 self.memoize(obj)
560 n = len(obj)
Tim Peters21c18f02003-01-28 01:15:46 +0000561 if n > 1:
562 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000563 for element in obj:
Tim Peters21c18f02003-01-28 01:15:46 +0000564 save(element)
565 write(APPENDS)
566 elif n:
567 assert n == 1
Guido van Rossum3a41c612003-01-28 15:10:22 +0000568 save(obj[0])
Tim Peters21c18f02003-01-28 01:15:46 +0000569 write(APPEND)
570 # else the list is empty, and we're already done
571
572 else: # proto 0 -- can't use EMPTY_LIST or APPENDS
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000573 write(MARK + LIST)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000574 self.memoize(obj)
575 for element in obj:
Tim Peters21c18f02003-01-28 01:15:46 +0000576 save(element)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000577 write(APPEND)
578
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000579 dispatch[ListType] = save_list
580
Guido van Rossum3a41c612003-01-28 15:10:22 +0000581 def save_dict(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000582 write = self.write
583 save = self.save
Guido van Rossum3a41c612003-01-28 15:10:22 +0000584 items = obj.iteritems()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000585
Tim Petersc32d8242001-04-10 02:48:53 +0000586 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000587 write(EMPTY_DICT)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000588 self.memoize(obj)
589 if len(obj) > 1:
Tim Peters064567e2003-01-28 01:34:43 +0000590 write(MARK)
591 for key, value in items:
592 save(key)
593 save(value)
594 write(SETITEMS)
595 return
Tim Peters82ca59e2003-01-28 16:47:59 +0000596 # else (dict is empty or a singleton), fall through to the
597 # SETITEM code at the end
Tim Peters064567e2003-01-28 01:34:43 +0000598 else: # proto 0 -- can't use EMPTY_DICT or SETITEMS
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000599 write(MARK + DICT)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000600 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000601
Guido van Rossum3a41c612003-01-28 15:10:22 +0000602 # proto 0 or len(obj) < 2
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000603 for key, value in items:
604 save(key)
605 save(value)
Tim Peters064567e2003-01-28 01:34:43 +0000606 write(SETITEM)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000607
608 dispatch[DictionaryType] = save_dict
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000609 if not PyStringMap is None:
610 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000611
Guido van Rossum3a41c612003-01-28 15:10:22 +0000612 def save_inst(self, obj):
613 cls = obj.__class__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000614
615 memo = self.memo
616 write = self.write
617 save = self.save
618
Guido van Rossum3a41c612003-01-28 15:10:22 +0000619 if hasattr(obj, '__getinitargs__'):
620 args = obj.__getinitargs__()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000621 len(args) # XXX Assert it's a sequence
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000622 _keep_alive(args, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000623 else:
624 args = ()
625
626 write(MARK)
627
Tim Petersc32d8242001-04-10 02:48:53 +0000628 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000629 save(cls)
Tim Peters3b769832003-01-28 03:51:36 +0000630 for arg in args:
631 save(arg)
632 write(OBJ)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000633 else:
Tim Peters3b769832003-01-28 03:51:36 +0000634 for arg in args:
635 save(arg)
636 write(INST + cls.__module__ + '\n' + cls.__name__ + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000637
Guido van Rossum3a41c612003-01-28 15:10:22 +0000638 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000639
640 try:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000641 getstate = obj.__getstate__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000642 except AttributeError:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000643 stuff = obj.__dict__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000644 else:
645 stuff = getstate()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000646 _keep_alive(stuff, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000647 save(stuff)
648 write(BUILD)
Tim Peters3b769832003-01-28 03:51:36 +0000649
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000650 dispatch[InstanceType] = save_inst
651
Guido van Rossum3a41c612003-01-28 15:10:22 +0000652 def save_global(self, obj, name = None):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000653 write = self.write
654 memo = self.memo
655
Tim Petersc32d8242001-04-10 02:48:53 +0000656 if name is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000657 name = obj.__name__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000658
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000659 try:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000660 module = obj.__module__
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000661 except AttributeError:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000662 module = whichmodule(obj, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000663
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000664 try:
665 __import__(module)
666 mod = sys.modules[module]
667 klass = getattr(mod, name)
668 except (ImportError, KeyError, AttributeError):
669 raise PicklingError(
670 "Can't pickle %r: it's not found as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000671 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000672 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000673 if klass is not obj:
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000674 raise PicklingError(
675 "Can't pickle %r: it's not the same object as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000676 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000677
Tim Peters518df0d2003-01-28 01:00:38 +0000678 write(GLOBAL + module + '\n' + name + '\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000679 self.memoize(obj)
Tim Peters3b769832003-01-28 03:51:36 +0000680
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000681 dispatch[ClassType] = save_global
682 dispatch[FunctionType] = save_global
683 dispatch[BuiltinFunctionType] = save_global
Tim Peters6d6c1a32001-08-02 04:15:00 +0000684 dispatch[TypeType] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000685
Guido van Rossum1be31752003-01-28 15:19:53 +0000686# Pickling helpers
Guido van Rossuma48061a1995-01-10 00:31:14 +0000687
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000688def _keep_alive(x, memo):
689 """Keeps a reference to the object x in the memo.
690
691 Because we remember objects by their id, we have
692 to assure that possibly temporary objects are kept
693 alive by referencing them.
694 We store a reference at the id of the memo, which should
695 normally not be used unless someone tries to deepcopy
696 the memo itself...
697 """
698 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000699 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000700 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000701 # aha, this is the first one :-)
702 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000703
704
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000705classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000706
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000707def whichmodule(func, funcname):
708 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000709
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000710 Search sys.modules for the module.
711 Cache in classmap.
712 Return a module name.
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000713 If the function cannot be found, return __main__.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000714 """
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000715 if func in classmap:
716 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000717
718 for name, module in sys.modules.items():
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000719 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000720 continue # skip dummy package entries
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000721 if name != '__main__' and \
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000722 hasattr(module, funcname) and \
723 getattr(module, funcname) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000724 break
725 else:
726 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000727 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000728 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000729
730
Guido van Rossum1be31752003-01-28 15:19:53 +0000731# Unpickling machinery
732
Guido van Rossuma48061a1995-01-10 00:31:14 +0000733class Unpickler:
734
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000735 def __init__(self, file):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000736 """This takes a file-like object for reading a pickle data stream.
737
738 This class automatically determines whether the data stream was
739 written in binary mode or not, so it does not need a flag as in
740 the Pickler class factory.
741
742 The file-like object must have two methods, a read() method that
743 takes an integer argument, and a readline() method that requires no
744 arguments. Both methods should return a string. Thus file-like
745 object can be a file object opened for reading, a StringIO object,
746 or any other custom object that meets this interface.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000747 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000748 self.readline = file.readline
749 self.read = file.read
750 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000751
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000752 def load(self):
Guido van Rossum3a41c612003-01-28 15:10:22 +0000753 """Read a pickled object representation from the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000754
Guido van Rossum3a41c612003-01-28 15:10:22 +0000755 Return the reconstituted object hierarchy specified in the file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000756 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000757 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000758 self.stack = []
759 self.append = self.stack.append
760 read = self.read
761 dispatch = self.dispatch
762 try:
763 while 1:
764 key = read(1)
765 dispatch[key](self)
Guido van Rossumff871742000-12-13 18:11:56 +0000766 except _Stop, stopinst:
767 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000768
Tim Petersc23d18a2003-01-28 01:41:51 +0000769 # Return largest index k such that self.stack[k] is self.mark.
770 # If the stack doesn't contain a mark, eventually raises IndexError.
771 # This could be sped by maintaining another stack, of indices at which
772 # the mark appears. For that matter, the latter stack would suffice,
773 # and we wouldn't need to push mark objects on self.stack at all.
774 # Doing so is probably a good thing, though, since if the pickle is
775 # corrupt (or hostile) we may get a clue from finding self.mark embedded
776 # in unpickled objects.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000777 def marker(self):
778 stack = self.stack
779 mark = self.mark
780 k = len(stack)-1
781 while stack[k] is not mark: k = k-1
782 return k
783
784 dispatch = {}
785
786 def load_eof(self):
787 raise EOFError
788 dispatch[''] = load_eof
789
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000790 def load_proto(self):
791 proto = ord(self.read(1))
792 if not 0 <= proto <= 2:
793 raise ValueError, "unsupported pickle protocol: %d" % proto
794 dispatch[PROTO] = load_proto
795
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000796 def load_persid(self):
797 pid = self.readline()[:-1]
798 self.append(self.persistent_load(pid))
799 dispatch[PERSID] = load_persid
800
801 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000802 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000803 self.append(self.persistent_load(pid))
804 dispatch[BINPERSID] = load_binpersid
805
806 def load_none(self):
807 self.append(None)
808 dispatch[NONE] = load_none
809
Guido van Rossum7d97d312003-01-28 04:25:27 +0000810 def load_false(self):
811 self.append(False)
812 dispatch[NEWFALSE] = load_false
813
814 def load_true(self):
815 self.append(True)
816 dispatch[NEWTRUE] = load_true
817
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000818 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000819 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000820 if data == FALSE[1:]:
821 val = False
822 elif data == TRUE[1:]:
823 val = True
824 else:
825 try:
826 val = int(data)
827 except ValueError:
828 val = long(data)
829 self.append(val)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000830 dispatch[INT] = load_int
831
832 def load_binint(self):
833 self.append(mloads('i' + self.read(4)))
834 dispatch[BININT] = load_binint
835
836 def load_binint1(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000837 self.append(ord(self.read(1)))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000838 dispatch[BININT1] = load_binint1
839
840 def load_binint2(self):
841 self.append(mloads('i' + self.read(2) + '\000\000'))
842 dispatch[BININT2] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000843
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000844 def load_long(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000845 self.append(long(self.readline()[:-1], 0))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000846 dispatch[LONG] = load_long
847
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000848 def load_long1(self):
849 n = ord(self.read(1))
850 bytes = self.read(n)
851 return decode_long(bytes)
852 dispatch[LONG1] = load_long1
853
854 def load_long4(self):
855 n = mloads('i' + self.read(4))
856 bytes = self.read(n)
857 return decode_long(bytes)
858 dispatch[LONG4] = load_long4
859
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000860 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000861 self.append(float(self.readline()[:-1]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000862 dispatch[FLOAT] = load_float
863
Guido van Rossumd3703791998-10-22 20:15:36 +0000864 def load_binfloat(self, unpack=struct.unpack):
865 self.append(unpack('>d', self.read(8))[0])
866 dispatch[BINFLOAT] = load_binfloat
867
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000868 def load_string(self):
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000869 rep = self.readline()[:-1]
Tim Petersad5a7712003-01-28 16:23:33 +0000870 for q in "\"'": # double or single quote
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000871 if rep.startswith(q):
872 if not rep.endswith(q):
873 raise ValueError, "insecure string pickle"
874 rep = rep[len(q):-len(q)]
875 break
876 else:
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000877 raise ValueError, "insecure string pickle"
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000878 self.append(rep.decode("string-escape"))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000879 dispatch[STRING] = load_string
880
881 def load_binstring(self):
882 len = mloads('i' + self.read(4))
883 self.append(self.read(len))
884 dispatch[BINSTRING] = load_binstring
885
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000886 def load_unicode(self):
887 self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
888 dispatch[UNICODE] = load_unicode
889
890 def load_binunicode(self):
891 len = mloads('i' + self.read(4))
892 self.append(unicode(self.read(len),'utf-8'))
893 dispatch[BINUNICODE] = load_binunicode
894
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000895 def load_short_binstring(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000896 len = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000897 self.append(self.read(len))
898 dispatch[SHORT_BINSTRING] = load_short_binstring
899
900 def load_tuple(self):
901 k = self.marker()
902 self.stack[k:] = [tuple(self.stack[k+1:])]
903 dispatch[TUPLE] = load_tuple
904
905 def load_empty_tuple(self):
906 self.stack.append(())
907 dispatch[EMPTY_TUPLE] = load_empty_tuple
908
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000909 def load_tuple1(self):
910 self.stack[-1] = (self.stack[-1],)
911 dispatch[TUPLE1] = load_tuple1
912
913 def load_tuple2(self):
914 self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
915 dispatch[TUPLE2] = load_tuple2
916
917 def load_tuple3(self):
918 self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
919 dispatch[TUPLE3] = load_tuple3
920
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000921 def load_empty_list(self):
922 self.stack.append([])
923 dispatch[EMPTY_LIST] = load_empty_list
924
925 def load_empty_dictionary(self):
926 self.stack.append({})
927 dispatch[EMPTY_DICT] = load_empty_dictionary
928
929 def load_list(self):
930 k = self.marker()
931 self.stack[k:] = [self.stack[k+1:]]
932 dispatch[LIST] = load_list
933
934 def load_dict(self):
935 k = self.marker()
936 d = {}
937 items = self.stack[k+1:]
938 for i in range(0, len(items), 2):
939 key = items[i]
940 value = items[i+1]
941 d[key] = value
942 self.stack[k:] = [d]
943 dispatch[DICT] = load_dict
944
945 def load_inst(self):
946 k = self.marker()
947 args = tuple(self.stack[k+1:])
948 del self.stack[k:]
949 module = self.readline()[:-1]
950 name = self.readline()[:-1]
951 klass = self.find_class(module, name)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000952 instantiated = 0
953 if (not args and type(klass) is ClassType and
954 not hasattr(klass, "__getinitargs__")):
955 try:
956 value = _EmptyClass()
957 value.__class__ = klass
Guido van Rossumb19e2a31998-04-13 18:08:45 +0000958 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000959 except RuntimeError:
960 # In restricted execution, assignment to inst.__class__ is
961 # prohibited
962 pass
963 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +0000964 try:
Barry Warsawbf4d9592001-11-15 23:42:58 +0000965 if not hasattr(klass, '__safe_for_unpickling__'):
966 raise UnpicklingError('%s is not safe for unpickling' %
967 klass)
Guido van Rossum743d17e1998-09-15 20:25:57 +0000968 value = apply(klass, args)
969 except TypeError, err:
970 raise TypeError, "in constructor for %s: %s" % (
971 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000972 self.append(value)
973 dispatch[INST] = load_inst
974
975 def load_obj(self):
976 stack = self.stack
977 k = self.marker()
978 klass = stack[k + 1]
979 del stack[k + 1]
Tim Peters2344fae2001-01-15 00:50:52 +0000980 args = tuple(stack[k + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000981 del stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000982 instantiated = 0
983 if (not args and type(klass) is ClassType and
984 not hasattr(klass, "__getinitargs__")):
985 try:
986 value = _EmptyClass()
987 value.__class__ = klass
988 instantiated = 1
989 except RuntimeError:
990 # In restricted execution, assignment to inst.__class__ is
991 # prohibited
992 pass
993 if not instantiated:
994 value = apply(klass, args)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000995 self.append(value)
Tim Peters2344fae2001-01-15 00:50:52 +0000996 dispatch[OBJ] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000997
Guido van Rossum3a41c612003-01-28 15:10:22 +0000998 def load_newobj(self):
999 args = self.stack.pop()
1000 cls = self.stack[-1]
1001 obj = cls.__new__(cls, *args)
Guido van Rossum533dbcf2003-01-28 17:55:05 +00001002 self.stack[-1] = obj
Guido van Rossum3a41c612003-01-28 15:10:22 +00001003 dispatch[NEWOBJ] = load_newobj
1004
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001005 def load_global(self):
1006 module = self.readline()[:-1]
1007 name = self.readline()[:-1]
1008 klass = self.find_class(module, name)
1009 self.append(klass)
1010 dispatch[GLOBAL] = load_global
1011
1012 def find_class(self, module, name):
Barry Warsawbf4d9592001-11-15 23:42:58 +00001013 __import__(module)
1014 mod = sys.modules[module]
1015 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001016 return klass
1017
1018 def load_reduce(self):
1019 stack = self.stack
1020
1021 callable = stack[-2]
1022 arg_tup = stack[-1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001023 del stack[-2:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001024
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001025 if type(callable) is not ClassType:
Raymond Hettinger54f02222002-06-01 14:18:47 +00001026 if not callable in safe_constructors:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001027 try:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001028 safe = callable.__safe_for_unpickling__
1029 except AttributeError:
1030 safe = None
Guido van Rossuma48061a1995-01-10 00:31:14 +00001031
Tim Petersc32d8242001-04-10 02:48:53 +00001032 if not safe:
Tim Peters2344fae2001-01-15 00:50:52 +00001033 raise UnpicklingError, "%s is not safe for " \
1034 "unpickling" % callable
Guido van Rossuma48061a1995-01-10 00:31:14 +00001035
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001036 if arg_tup is None:
Guido van Rossumbc64e222003-01-28 16:34:19 +00001037 # A hack for Jim Fulton's ExtensionClass, now deprecated
1038 warnings.warn("__basicnew__ special case is deprecated",
Tim Peters8ac14952002-05-23 15:15:30 +00001039 DeprecationWarning)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001040 value = callable.__basicnew__()
1041 else:
1042 value = apply(callable, arg_tup)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001043 self.append(value)
1044 dispatch[REDUCE] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +00001045
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001046 def load_pop(self):
1047 del self.stack[-1]
1048 dispatch[POP] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +00001049
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001050 def load_pop_mark(self):
1051 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001052 del self.stack[k:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001053 dispatch[POP_MARK] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001054
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001055 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +00001056 self.append(self.stack[-1])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001057 dispatch[DUP] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +00001058
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001059 def load_get(self):
1060 self.append(self.memo[self.readline()[:-1]])
1061 dispatch[GET] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +00001062
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001063 def load_binget(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001064 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001065 self.append(self.memo[`i`])
1066 dispatch[BINGET] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001067
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001068 def load_long_binget(self):
1069 i = mloads('i' + self.read(4))
1070 self.append(self.memo[`i`])
1071 dispatch[LONG_BINGET] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001072
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001073 def load_put(self):
1074 self.memo[self.readline()[:-1]] = self.stack[-1]
1075 dispatch[PUT] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +00001076
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001077 def load_binput(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001078 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001079 self.memo[`i`] = self.stack[-1]
1080 dispatch[BINPUT] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001081
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001082 def load_long_binput(self):
1083 i = mloads('i' + self.read(4))
1084 self.memo[`i`] = self.stack[-1]
1085 dispatch[LONG_BINPUT] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001086
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001087 def load_append(self):
1088 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001089 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001090 list = stack[-1]
1091 list.append(value)
1092 dispatch[APPEND] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +00001093
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001094 def load_appends(self):
1095 stack = self.stack
1096 mark = self.marker()
1097 list = stack[mark - 1]
Tim Peters209ad952003-01-28 01:44:45 +00001098 list.extend(stack[mark + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001099 del stack[mark:]
1100 dispatch[APPENDS] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +00001101
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001102 def load_setitem(self):
1103 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001104 value = stack.pop()
1105 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001106 dict = stack[-1]
1107 dict[key] = value
1108 dispatch[SETITEM] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001109
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001110 def load_setitems(self):
1111 stack = self.stack
1112 mark = self.marker()
1113 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001114 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001115 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001116
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001117 del stack[mark:]
1118 dispatch[SETITEMS] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001119
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001120 def load_build(self):
1121 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001122 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001123 inst = stack[-1]
1124 try:
1125 setstate = inst.__setstate__
1126 except AttributeError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001127 try:
1128 inst.__dict__.update(value)
1129 except RuntimeError:
1130 # XXX In restricted execution, the instance's __dict__ is not
1131 # accessible. Use the old way of unpickling the instance
1132 # variables. This is a semantic different when unpickling in
1133 # restricted vs. unrestricted modes.
1134 for k, v in value.items():
1135 setattr(inst, k, v)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001136 else:
1137 setstate(value)
1138 dispatch[BUILD] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001139
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001140 def load_mark(self):
1141 self.append(self.mark)
1142 dispatch[MARK] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001143
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001144 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001145 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001146 raise _Stop(value)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001147 dispatch[STOP] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001148
Guido van Rossume467be61997-12-05 19:42:42 +00001149# Helper class for load_inst/load_obj
1150
1151class _EmptyClass:
1152 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001153
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001154# Encode/decode longs.
1155
1156def encode_long(x):
1157 r"""Encode a long to a two's complement little-ending binary string.
1158 >>> encode_long(255L)
1159 '\xff\x00'
1160 >>> encode_long(32767L)
1161 '\xff\x7f'
1162 >>> encode_long(-256L)
1163 '\x00\xff'
1164 >>> encode_long(-32768L)
1165 '\x00\x80'
1166 >>> encode_long(-128L)
1167 '\x80'
1168 >>> encode_long(127L)
1169 '\x7f'
1170 >>>
1171 """
1172 digits = []
1173 while not -128 <= x < 128:
1174 digits.append(x & 0xff)
1175 x >>= 8
1176 digits.append(x & 0xff)
1177 return "".join(map(chr, digits))
1178
1179def decode_long(data):
1180 r"""Decode a long from a two's complement little-endian binary string.
1181 >>> decode_long("\xff\x00")
1182 255L
1183 >>> decode_long("\xff\x7f")
1184 32767L
1185 >>> decode_long("\x00\xff")
1186 -256L
1187 >>> decode_long("\x00\x80")
1188 -32768L
1189 >>> decode_long("\x80")
1190 -128L
1191 >>> decode_long("\x7f")
1192 127L
1193 """
1194 x = 0L
1195 i = 0L
1196 for c in data:
1197 x |= long(ord(c)) << i
1198 i += 8L
1199 if data and ord(c) >= 0x80:
1200 x -= 1L << i
1201 return x
1202
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001203# Shorthands
1204
Jeremy Hyltonabe2c622001-10-15 21:29:28 +00001205try:
1206 from cStringIO import StringIO
1207except ImportError:
1208 from StringIO import StringIO
Guido van Rossumc7c5e691996-07-22 22:26:07 +00001209
Guido van Rossum3a41c612003-01-28 15:10:22 +00001210def dump(obj, file, proto=1):
1211 Pickler(file, proto).dump(obj)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001212
Guido van Rossum3a41c612003-01-28 15:10:22 +00001213def dumps(obj, proto=1):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001214 file = StringIO()
Guido van Rossum3a41c612003-01-28 15:10:22 +00001215 Pickler(file, proto).dump(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001216 return file.getvalue()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001217
1218def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001219 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001220
1221def loads(str):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001222 file = StringIO(str)
1223 return Unpickler(file).load()
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001224
1225# Doctest
1226
1227def _test():
1228 import doctest
1229 return doctest.testmod()
1230
1231if __name__ == "__main__":
1232 _test()