blob: 88f03a4373cb354c6bb15e312a42fa02395423da [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
Jeremy Hylton2b9d0291998-05-27 22:38:22 +000080try:
81 from org.python.core import PyStringMap
82except ImportError:
83 PyStringMap = None
84
Guido van Rossumdbb718f2001-09-21 19:22:34 +000085try:
86 UnicodeType
87except NameError:
88 UnicodeType = None
89
Tim Peters22a449a2003-01-27 20:16:36 +000090# Pickle opcodes. See pickletools.py for extensive docs. The listing
91# here is in kind-of alphabetical order of 1-character pickle code.
92# pickletools groups them by purpose.
Guido van Rossumdbb718f2001-09-21 19:22:34 +000093
Tim Peters22a449a2003-01-27 20:16:36 +000094MARK = '(' # push special markobject on stack
95STOP = '.' # every pickle ends with STOP
96POP = '0' # discard topmost stack item
97POP_MARK = '1' # discard stack top through topmost markobject
98DUP = '2' # duplicate top stack item
99FLOAT = 'F' # push float object; decimal string argument
100INT = 'I' # push integer or bool; decimal string argument
101BININT = 'J' # push four-byte signed int
102BININT1 = 'K' # push 1-byte unsigned int
103LONG = 'L' # push long; decimal string argument
104BININT2 = 'M' # push 2-byte unsigned int
105NONE = 'N' # push None
106PERSID = 'P' # push persistent object; id is taken from string arg
107BINPERSID = 'Q' # " " " ; " " " " stack
108REDUCE = 'R' # apply callable to argtuple, both on stack
109STRING = 'S' # push string; NL-terminated string argument
110BINSTRING = 'T' # push string; counted binary string argument
111SHORT_BINSTRING = 'U' # " " ; " " " " < 256 bytes
112UNICODE = 'V' # push Unicode string; raw-unicode-escaped'd argument
113BINUNICODE = 'X' # " " " ; counted UTF-8 string argument
114APPEND = 'a' # append stack top to list below it
115BUILD = 'b' # call __setstate__ or __dict__.update()
116GLOBAL = 'c' # push self.find_class(modname, name); 2 string args
117DICT = 'd' # build a dict from stack items
118EMPTY_DICT = '}' # push empty dict
119APPENDS = 'e' # extend list on stack by topmost stack slice
120GET = 'g' # push item from memo on stack; index is string arg
121BINGET = 'h' # " " " " " " ; " " 1-byte arg
122INST = 'i' # build & push class instance
123LONG_BINGET = 'j' # push item from memo on stack; index is 4-byte arg
124LIST = 'l' # build list from topmost stack items
125EMPTY_LIST = ']' # push empty list
126OBJ = 'o' # build & push class instance
127PUT = 'p' # store stack top in memo; index is string arg
128BINPUT = 'q' # " " " " " ; " " 1-byte arg
129LONG_BINPUT = 'r' # " " " " " ; " " 4-byte arg
130SETITEM = 's' # add key+value pair to dict
131TUPLE = 't' # build tuple from topmost stack items
132EMPTY_TUPLE = ')' # push empty tuple
133SETITEMS = 'u' # modify dict by adding topmost key+value pairs
134BINFLOAT = 'G' # push float; arg is 8-byte float encoding
135
136TRUE = 'I01\n' # not an opcode; see INT docs in pickletools.py
137FALSE = 'I00\n' # not an opcode; see INT docs in pickletools.py
Guido van Rossum77f6a652002-04-03 22:41:51 +0000138
Tim Peterse1054782003-01-28 00:22:12 +0000139# Protocol 2 (not yet implemented).
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000140
Tim Peterse1054782003-01-28 00:22:12 +0000141PROTO = '\x80' # identify pickle protocol
142NEWOBJ = '\x81' # build object by applying cls.__new__ to argtuple
143EXT1 = '\x82' # push object from extension registry; 1-byte index
144EXT2 = '\x83' # ditto, but 2-byte index
145EXT4 = '\x84' # ditto, but 4-byte index
146TUPLE1 = '\x85' # build 1-tuple from stack top
147TUPLE2 = '\x86' # build 2-tuple from two topmost stack items
148TUPLE3 = '\x87' # build 3-tuple from three topmost stack items
149NEWTRUE = '\x88' # push True
150NEWFALSE = '\x89' # push False
151LONG1 = '\x8a' # push long from < 256 bytes
152LONG4 = '\x8b' # push really big long
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000153
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000154_tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3]
155
Guido van Rossuma48061a1995-01-10 00:31:14 +0000156
Skip Montanaro23bafc62001-02-18 03:10:09 +0000157__all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
Neal Norwitzd5ba4ae2002-02-11 18:12:06 +0000158del x
Skip Montanaro23bafc62001-02-18 03:10:09 +0000159
Guido van Rossum1be31752003-01-28 15:19:53 +0000160
161# Pickling machinery
162
Guido van Rossuma48061a1995-01-10 00:31:14 +0000163class Pickler:
164
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000165 def __init__(self, file, proto=1):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000166 """This takes a file-like object for writing a pickle data stream.
167
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000168 The optional proto argument tells the pickler to use the given
169 protocol; supported protocols are 0, 1, 2. The default
170 protocol is 1 (in previous Python versions the default was 0).
171
172 Protocol 1 is more efficient than protocol 0; protocol 2 is
173 more efficient than protocol 1. Protocol 2 is not the default
174 because it is not supported by older Python versions.
175
176 XXX Protocol 2 is not yet implemented.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000177
178 The file parameter must have a write() method that accepts a single
179 string argument. It can thus be an open file object, a StringIO
180 object, or any other custom object that meets this interface.
181
182 """
Guido van Rossum1be31752003-01-28 15:19:53 +0000183 if proto not in (0, 1, 2):
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000184 raise ValueError, "pickle protocol must be 0, 1 or 2"
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000185 self.write = file.write
186 self.memo = {}
Guido van Rossum1be31752003-01-28 15:19:53 +0000187 self.proto = int(proto)
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000188 self.bin = proto >= 1
Guido van Rossuma48061a1995-01-10 00:31:14 +0000189
Fred Drake7f781c92002-05-01 20:33:53 +0000190 def clear_memo(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000191 """Clears the pickler's "memo".
192
193 The memo is the data structure that remembers which objects the
Tim Petersb377f8a2003-01-28 00:23:36 +0000194 pickler has already seen, so that shared or recursive objects are
195 pickled by reference and not by value. This method is useful when
196 re-using picklers.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000197
198 """
Fred Drake7f781c92002-05-01 20:33:53 +0000199 self.memo.clear()
200
Guido van Rossum3a41c612003-01-28 15:10:22 +0000201 def dump(self, obj):
202 """Write a pickled representation of obj to the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000203
204 Either the binary or ASCII format will be used, depending on the
205 value of the bin flag passed to the constructor.
206
207 """
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000208 if self.proto >= 2:
209 self.write(PROTO + chr(self.proto))
Guido van Rossum3a41c612003-01-28 15:10:22 +0000210 self.save(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000211 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000212
Jeremy Hylton3422c992003-01-24 19:29:52 +0000213 def memoize(self, obj):
214 """Store an object in the memo."""
215
Tim Peterse46b73f2003-01-27 21:22:10 +0000216 # The Pickler memo is a dictionary mapping object ids to 2-tuples
217 # that contain the Unpickler memo key and the object being memoized.
218 # The memo key is written to the pickle and will become
Jeremy Hylton3422c992003-01-24 19:29:52 +0000219 # the key in the Unpickler's memo. The object is stored in the
Tim Peterse46b73f2003-01-27 21:22:10 +0000220 # Pickler memo so that transient objects are kept alive during
221 # pickling.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000222
Tim Peterse46b73f2003-01-27 21:22:10 +0000223 # The use of the Unpickler memo length as the memo key is just a
224 # convention. The only requirement is that the memo values be unique.
225 # But there appears no advantage to any other scheme, and this
Tim Peterscbd0a322003-01-28 00:24:43 +0000226 # scheme allows the Unpickler memo to be implemented as a plain (but
Tim Peterse46b73f2003-01-27 21:22:10 +0000227 # growable) array, indexed by memo key.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000228 memo_len = len(self.memo)
229 self.write(self.put(memo_len))
Tim Peters518df0d2003-01-28 01:00:38 +0000230 self.memo[id(obj)] = memo_len, obj
Jeremy Hylton3422c992003-01-24 19:29:52 +0000231
Tim Petersbb38e302003-01-27 21:25:41 +0000232 # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000233 def put(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000234 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000235 if i < 256:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000236 return BINPUT + chr(i)
237 else:
238 return LONG_BINPUT + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000239
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000240 return PUT + `i` + '\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000241
Tim Petersbb38e302003-01-27 21:25:41 +0000242 # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000243 def get(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000244 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000245 if i < 256:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000246 return BINGET + chr(i)
247 else:
248 return LONG_BINGET + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000249
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000250 return GET + `i` + '\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000251
Guido van Rossum3a41c612003-01-28 15:10:22 +0000252 def save(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000253 # Check for persistent id (defined by a subclass)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000254 pid = self.persistent_id(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000255 if pid:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000256 self.save_pers(pid)
257 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000258
Guido van Rossumbc64e222003-01-28 16:34:19 +0000259 # Check the memo
260 x = self.memo.get(id(obj))
261 if x:
262 self.write(self.get(x[0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000263 return
264
Guido van Rossumbc64e222003-01-28 16:34:19 +0000265 # Check the type dispatch table
Guido van Rossum3a41c612003-01-28 15:10:22 +0000266 t = type(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000267 f = self.dispatch.get(t)
268 if f:
269 f(self, obj) # Call unbound method with explicit self
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000270 return
271
Guido van Rossumbc64e222003-01-28 16:34:19 +0000272 # Check for a class with a custom metaclass; treat as regular class
Tim Petersb32a8312003-01-28 00:48:09 +0000273 try:
274 issc = issubclass(t, TypeType)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000275 except TypeError: # t is not a class (old Boost; see SF #502085)
Tim Petersb32a8312003-01-28 00:48:09 +0000276 issc = 0
277 if issc:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000278 self.save_global(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000279 return
280
Guido van Rossumbc64e222003-01-28 16:34:19 +0000281 # Check copy_reg.dispatch_table
282 reduce = dispatch_table.get(t)
283 if reduce:
284 rv = reduce(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000285 else:
Guido van Rossumbc64e222003-01-28 16:34:19 +0000286 # Check for __reduce__ method
287 reduce = getattr(obj, "__reduce__", None)
288 if not reduce:
289 raise PicklingError("Can't pickle %r object: %r" %
290 (t.__name__, obj))
291 rv = reduce()
Tim Petersb32a8312003-01-28 00:48:09 +0000292
Guido van Rossumbc64e222003-01-28 16:34:19 +0000293 # Check for string returned by reduce(), meaning "save as global"
294 if type(rv) is StringType:
295 self.save_global(obj, rv)
Tim Petersb32a8312003-01-28 00:48:09 +0000296 return
297
Guido van Rossumbc64e222003-01-28 16:34:19 +0000298 # Assert that reduce() returned a tuple
299 if type(rv) is not TupleType:
300 raise PicklingError("%s must return string or tuple" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000301
Guido van Rossumbc64e222003-01-28 16:34:19 +0000302 # Assert that it returned a 2-tuple or 3-tuple, and unpack it
303 l = len(rv)
304 if l == 2:
305 func, args = rv
Tim Petersb32a8312003-01-28 00:48:09 +0000306 state = None
Guido van Rossumbc64e222003-01-28 16:34:19 +0000307 elif l == 3:
308 func, args, state = rv
309 else:
310 raise PicklingError("Tuple returned by %s must have "
311 "exactly two or three elements" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000312
Guido van Rossumbc64e222003-01-28 16:34:19 +0000313 # Save the reduce() output and finally memoize the object
314 self.save_reduce(func, args, state)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000315 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000316
Guido van Rossum3a41c612003-01-28 15:10:22 +0000317 def persistent_id(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000318 # This exists so a subclass can override it
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000319 return None
320
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000321 def save_pers(self, pid):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000322 # Save a persistent id reference
Tim Petersbd1cdb92003-01-28 01:03:10 +0000323 if self.bin:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000324 self.save(pid)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000325 self.write(BINPERSID)
Tim Petersbd1cdb92003-01-28 01:03:10 +0000326 else:
327 self.write(PERSID + str(pid) + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000328
Guido van Rossumbc64e222003-01-28 16:34:19 +0000329 def save_reduce(self, func, args, state=None):
330 # This API is be called by some subclasses
331
332 # Assert that args is a tuple or None
333 if not isinstance(args, TupleType):
334 if args is None:
335 # A hack for Jim Fulton's ExtensionClass, now deprecated.
336 # See load_reduce()
337 warnings.warn("__basicnew__ special case is deprecated",
338 DeprecationWarning)
339 else:
340 raise PicklingError(
341 "args from reduce() should be a tuple")
342
343 # Assert that func is callable
344 if not callable(func):
345 raise PicklingError("func from reduce should be callable")
346
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000347 save = self.save
Guido van Rossumbc64e222003-01-28 16:34:19 +0000348 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000349
Guido van Rossumbc64e222003-01-28 16:34:19 +0000350 save(func)
351 save(args)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000352 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000353
Tim Petersc32d8242001-04-10 02:48:53 +0000354 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000355 save(state)
356 write(BUILD)
357
Guido van Rossumbc64e222003-01-28 16:34:19 +0000358 # Methods below this point are dispatched through the dispatch table
359
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000360 dispatch = {}
361
Guido van Rossum3a41c612003-01-28 15:10:22 +0000362 def save_none(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000363 self.write(NONE)
364 dispatch[NoneType] = save_none
365
Guido van Rossum3a41c612003-01-28 15:10:22 +0000366 def save_bool(self, obj):
Guido van Rossum7d97d312003-01-28 04:25:27 +0000367 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000368 self.write(obj and NEWTRUE or NEWFALSE)
Guido van Rossum7d97d312003-01-28 04:25:27 +0000369 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000370 self.write(obj and TRUE or FALSE)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000371 dispatch[bool] = save_bool
372
Guido van Rossum3a41c612003-01-28 15:10:22 +0000373 def save_int(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000374 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000375 # If the int is small enough to fit in a signed 4-byte 2's-comp
376 # format, we can store it more efficiently than the general
377 # case.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000378 # First one- and two-byte unsigned ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000379 if obj >= 0:
380 if obj <= 0xff:
381 self.write(BININT1 + chr(obj))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000382 return
Guido van Rossum3a41c612003-01-28 15:10:22 +0000383 if obj <= 0xffff:
384 self.write(BININT2 + chr(obj&0xff) + chr(obj>>8))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000385 return
386 # Next check for 4-byte signed ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000387 high_bits = obj >> 31 # note that Python shift sign-extends
Tim Petersd95c2df2003-01-28 03:41:54 +0000388 if high_bits == 0 or high_bits == -1:
Tim Peters44714002001-04-10 05:02:52 +0000389 # All high bits are copies of bit 2**31, so the value
390 # fits in a 4-byte signed int.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000391 self.write(BININT + pack("<i", obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000392 return
Tim Peters44714002001-04-10 05:02:52 +0000393 # Text pickle, or int too big to fit in signed 4-byte format.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000394 self.write(INT + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000395 dispatch[IntType] = save_int
396
Guido van Rossum3a41c612003-01-28 15:10:22 +0000397 def save_long(self, obj, pack=struct.pack):
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000398 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000399 bytes = encode_long(obj)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000400 n = len(bytes)
401 if n < 256:
402 self.write(LONG1 + chr(n) + bytes)
403 else:
404 self.write(LONG4 + pack("<i", n) + bytes)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000405 self.write(LONG + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000406 dispatch[LongType] = save_long
407
Guido van Rossum3a41c612003-01-28 15:10:22 +0000408 def save_float(self, obj, pack=struct.pack):
Guido van Rossumd3703791998-10-22 20:15:36 +0000409 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000410 self.write(BINFLOAT + pack('>d', obj))
Guido van Rossumd3703791998-10-22 20:15:36 +0000411 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000412 self.write(FLOAT + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000413 dispatch[FloatType] = save_float
414
Guido van Rossum3a41c612003-01-28 15:10:22 +0000415 def save_string(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000416 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000417 n = len(obj)
Tim Petersbbf63cd2003-01-27 21:15:36 +0000418 if n < 256:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000419 self.write(SHORT_BINSTRING + chr(n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000420 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000421 self.write(BINSTRING + pack("<i", n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000422 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000423 self.write(STRING + `obj` + '\n')
424 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000425 dispatch[StringType] = save_string
426
Guido van Rossum3a41c612003-01-28 15:10:22 +0000427 def save_unicode(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000428 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000429 encoding = obj.encode('utf-8')
Tim Petersbbf63cd2003-01-27 21:15:36 +0000430 n = len(encoding)
Guido van Rossum5c938d02003-01-28 03:03:08 +0000431 self.write(BINUNICODE + pack("<i", n) + encoding)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000432 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000433 obj = obj.replace("\\", "\\u005c")
434 obj = obj.replace("\n", "\\u000a")
435 self.write(UNICODE + obj.encode('raw-unicode-escape') + '\n')
436 self.memoize(obj)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000437 dispatch[UnicodeType] = save_unicode
438
Guido van Rossum31584cb2001-01-22 14:53:29 +0000439 if StringType == UnicodeType:
440 # This is true for Jython
Guido van Rossum3a41c612003-01-28 15:10:22 +0000441 def save_string(self, obj, pack=struct.pack):
442 unicode = obj.isunicode()
Guido van Rossum31584cb2001-01-22 14:53:29 +0000443
Tim Petersc32d8242001-04-10 02:48:53 +0000444 if self.bin:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000445 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000446 obj = obj.encode("utf-8")
447 l = len(obj)
Tim Petersc32d8242001-04-10 02:48:53 +0000448 if l < 256 and not unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000449 self.write(SHORT_BINSTRING + chr(l) + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000450 else:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000451 s = pack("<i", l)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000452 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000453 self.write(BINUNICODE + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000454 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000455 self.write(BINSTRING + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000456 else:
Tim Peters658cba62001-02-09 20:06:00 +0000457 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000458 obj = obj.replace("\\", "\\u005c")
459 obj = obj.replace("\n", "\\u000a")
460 obj = obj.encode('raw-unicode-escape')
461 self.write(UNICODE + obj + '\n')
Guido van Rossum31584cb2001-01-22 14:53:29 +0000462 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000463 self.write(STRING + `obj` + '\n')
464 self.memoize(obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000465 dispatch[StringType] = save_string
Tim Peters658cba62001-02-09 20:06:00 +0000466
Guido van Rossum3a41c612003-01-28 15:10:22 +0000467 def save_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000468 write = self.write
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000469 proto = self.proto
470
Guido van Rossum3a41c612003-01-28 15:10:22 +0000471 n = len(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000472 if n == 0 and proto:
473 write(EMPTY_TUPLE)
474 return
475
476 save = self.save
477 memo = self.memo
478 if n <= 3 and proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000479 for element in obj:
Tim Petersd97da802003-01-28 05:48:29 +0000480 save(element)
481 # Subtle. Same as in the big comment below.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000482 if id(obj) in memo:
483 get = self.get(memo[id(obj)][0])
Tim Petersd97da802003-01-28 05:48:29 +0000484 write(POP * n + get)
485 else:
486 write(_tuplesize2code[n])
Guido van Rossum3a41c612003-01-28 15:10:22 +0000487 self.memoize(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000488 return
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000489
Tim Petersff57bff2003-01-28 05:34:53 +0000490 # proto 0, or proto 1 and tuple isn't empty, or proto > 1 and tuple
491 # has more than 3 elements.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000492 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000493 for element in obj:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000494 save(element)
495
Guido van Rossum3a41c612003-01-28 15:10:22 +0000496 if n and id(obj) in memo:
Tim Petersf558da02003-01-28 02:09:55 +0000497 # Subtle. d was not in memo when we entered save_tuple(), so
498 # the process of saving the tuple's elements must have saved
499 # the tuple itself: the tuple is recursive. The proper action
500 # now is to throw away everything we put on the stack, and
501 # simply GET the tuple (it's already constructed). This check
502 # could have been done in the "for element" loop instead, but
503 # recursive tuples are a rare thing.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000504 get = self.get(memo[id(obj)][0])
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000505 if proto:
Tim Petersf558da02003-01-28 02:09:55 +0000506 write(POP_MARK + get)
507 else: # proto 0 -- POP_MARK not available
Tim Petersd97da802003-01-28 05:48:29 +0000508 write(POP * (n+1) + get)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000509 return
510
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000511 # No recursion (including the empty-tuple case for protocol 0).
Tim Peters518df0d2003-01-28 01:00:38 +0000512 self.write(TUPLE)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000513 if obj: # No need to memoize empty tuple
514 self.memoize(obj)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000515
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000516 dispatch[TupleType] = save_tuple
517
Guido van Rossum3a41c612003-01-28 15:10:22 +0000518 def save_empty_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000519 self.write(EMPTY_TUPLE)
520
Guido van Rossum3a41c612003-01-28 15:10:22 +0000521 def save_list(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000522 write = self.write
523 save = self.save
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000524
Tim Petersc32d8242001-04-10 02:48:53 +0000525 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000526 write(EMPTY_LIST)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000527 self.memoize(obj)
528 n = len(obj)
Tim Peters21c18f02003-01-28 01:15:46 +0000529 if n > 1:
530 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000531 for element in obj:
Tim Peters21c18f02003-01-28 01:15:46 +0000532 save(element)
533 write(APPENDS)
534 elif n:
535 assert n == 1
Guido van Rossum3a41c612003-01-28 15:10:22 +0000536 save(obj[0])
Tim Peters21c18f02003-01-28 01:15:46 +0000537 write(APPEND)
538 # else the list is empty, and we're already done
539
540 else: # proto 0 -- can't use EMPTY_LIST or APPENDS
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000541 write(MARK + LIST)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000542 self.memoize(obj)
543 for element in obj:
Tim Peters21c18f02003-01-28 01:15:46 +0000544 save(element)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000545 write(APPEND)
546
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000547 dispatch[ListType] = save_list
548
Guido van Rossum3a41c612003-01-28 15:10:22 +0000549 def save_dict(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000550 write = self.write
551 save = self.save
Guido van Rossum3a41c612003-01-28 15:10:22 +0000552 items = obj.iteritems()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000553
Tim Petersc32d8242001-04-10 02:48:53 +0000554 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000555 write(EMPTY_DICT)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000556 self.memoize(obj)
557 if len(obj) > 1:
Tim Peters064567e2003-01-28 01:34:43 +0000558 write(MARK)
559 for key, value in items:
560 save(key)
561 save(value)
562 write(SETITEMS)
563 return
Tim Peters82ca59e2003-01-28 16:47:59 +0000564 # else (dict is empty or a singleton), fall through to the
565 # SETITEM code at the end
Tim Peters064567e2003-01-28 01:34:43 +0000566 else: # proto 0 -- can't use EMPTY_DICT or SETITEMS
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000567 write(MARK + DICT)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000568 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000569
Guido van Rossum3a41c612003-01-28 15:10:22 +0000570 # proto 0 or len(obj) < 2
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000571 for key, value in items:
572 save(key)
573 save(value)
Tim Peters064567e2003-01-28 01:34:43 +0000574 write(SETITEM)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000575
576 dispatch[DictionaryType] = save_dict
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000577 if not PyStringMap is None:
578 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000579
Guido van Rossum3a41c612003-01-28 15:10:22 +0000580 def save_inst(self, obj):
581 cls = obj.__class__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000582
583 memo = self.memo
584 write = self.write
585 save = self.save
586
Guido van Rossum3a41c612003-01-28 15:10:22 +0000587 if hasattr(obj, '__getinitargs__'):
588 args = obj.__getinitargs__()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000589 len(args) # XXX Assert it's a sequence
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000590 _keep_alive(args, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000591 else:
592 args = ()
593
594 write(MARK)
595
Tim Petersc32d8242001-04-10 02:48:53 +0000596 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000597 save(cls)
Tim Peters3b769832003-01-28 03:51:36 +0000598 for arg in args:
599 save(arg)
600 write(OBJ)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000601 else:
Tim Peters3b769832003-01-28 03:51:36 +0000602 for arg in args:
603 save(arg)
604 write(INST + cls.__module__ + '\n' + cls.__name__ + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000605
Guido van Rossum3a41c612003-01-28 15:10:22 +0000606 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000607
608 try:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000609 getstate = obj.__getstate__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000610 except AttributeError:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000611 stuff = obj.__dict__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000612 else:
613 stuff = getstate()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000614 _keep_alive(stuff, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000615 save(stuff)
616 write(BUILD)
Tim Peters3b769832003-01-28 03:51:36 +0000617
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000618 dispatch[InstanceType] = save_inst
619
Guido van Rossum3a41c612003-01-28 15:10:22 +0000620 def save_global(self, obj, name = None):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000621 write = self.write
622 memo = self.memo
623
Tim Petersc32d8242001-04-10 02:48:53 +0000624 if name is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000625 name = obj.__name__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000626
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000627 try:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000628 module = obj.__module__
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000629 except AttributeError:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000630 module = whichmodule(obj, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000631
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000632 try:
633 __import__(module)
634 mod = sys.modules[module]
635 klass = getattr(mod, name)
636 except (ImportError, KeyError, AttributeError):
637 raise PicklingError(
638 "Can't pickle %r: it's not found as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000639 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000640 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000641 if klass is not obj:
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000642 raise PicklingError(
643 "Can't pickle %r: it's not the same object as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000644 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000645
Tim Peters518df0d2003-01-28 01:00:38 +0000646 write(GLOBAL + module + '\n' + name + '\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000647 self.memoize(obj)
Tim Peters3b769832003-01-28 03:51:36 +0000648
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000649 dispatch[ClassType] = save_global
650 dispatch[FunctionType] = save_global
651 dispatch[BuiltinFunctionType] = save_global
Tim Peters6d6c1a32001-08-02 04:15:00 +0000652 dispatch[TypeType] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000653
Guido van Rossum1be31752003-01-28 15:19:53 +0000654# Pickling helpers
Guido van Rossuma48061a1995-01-10 00:31:14 +0000655
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000656def _keep_alive(x, memo):
657 """Keeps a reference to the object x in the memo.
658
659 Because we remember objects by their id, we have
660 to assure that possibly temporary objects are kept
661 alive by referencing them.
662 We store a reference at the id of the memo, which should
663 normally not be used unless someone tries to deepcopy
664 the memo itself...
665 """
666 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000667 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000668 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000669 # aha, this is the first one :-)
670 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000671
672
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000673classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000674
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000675def whichmodule(func, funcname):
676 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000677
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000678 Search sys.modules for the module.
679 Cache in classmap.
680 Return a module name.
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000681 If the function cannot be found, return __main__.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000682 """
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000683 if func in classmap:
684 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000685
686 for name, module in sys.modules.items():
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000687 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000688 continue # skip dummy package entries
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000689 if name != '__main__' and \
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000690 hasattr(module, funcname) and \
691 getattr(module, funcname) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000692 break
693 else:
694 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000695 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000696 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000697
698
Guido van Rossum1be31752003-01-28 15:19:53 +0000699# Unpickling machinery
700
Guido van Rossuma48061a1995-01-10 00:31:14 +0000701class Unpickler:
702
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000703 def __init__(self, file):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000704 """This takes a file-like object for reading a pickle data stream.
705
706 This class automatically determines whether the data stream was
707 written in binary mode or not, so it does not need a flag as in
708 the Pickler class factory.
709
710 The file-like object must have two methods, a read() method that
711 takes an integer argument, and a readline() method that requires no
712 arguments. Both methods should return a string. Thus file-like
713 object can be a file object opened for reading, a StringIO object,
714 or any other custom object that meets this interface.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000715 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000716 self.readline = file.readline
717 self.read = file.read
718 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000719
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000720 def load(self):
Guido van Rossum3a41c612003-01-28 15:10:22 +0000721 """Read a pickled object representation from the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000722
Guido van Rossum3a41c612003-01-28 15:10:22 +0000723 Return the reconstituted object hierarchy specified in the file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000724 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000725 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000726 self.stack = []
727 self.append = self.stack.append
728 read = self.read
729 dispatch = self.dispatch
730 try:
731 while 1:
732 key = read(1)
733 dispatch[key](self)
Guido van Rossumff871742000-12-13 18:11:56 +0000734 except _Stop, stopinst:
735 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000736
Tim Petersc23d18a2003-01-28 01:41:51 +0000737 # Return largest index k such that self.stack[k] is self.mark.
738 # If the stack doesn't contain a mark, eventually raises IndexError.
739 # This could be sped by maintaining another stack, of indices at which
740 # the mark appears. For that matter, the latter stack would suffice,
741 # and we wouldn't need to push mark objects on self.stack at all.
742 # Doing so is probably a good thing, though, since if the pickle is
743 # corrupt (or hostile) we may get a clue from finding self.mark embedded
744 # in unpickled objects.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000745 def marker(self):
746 stack = self.stack
747 mark = self.mark
748 k = len(stack)-1
749 while stack[k] is not mark: k = k-1
750 return k
751
752 dispatch = {}
753
754 def load_eof(self):
755 raise EOFError
756 dispatch[''] = load_eof
757
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000758 def load_proto(self):
759 proto = ord(self.read(1))
760 if not 0 <= proto <= 2:
761 raise ValueError, "unsupported pickle protocol: %d" % proto
762 dispatch[PROTO] = load_proto
763
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000764 def load_persid(self):
765 pid = self.readline()[:-1]
766 self.append(self.persistent_load(pid))
767 dispatch[PERSID] = load_persid
768
769 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000770 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000771 self.append(self.persistent_load(pid))
772 dispatch[BINPERSID] = load_binpersid
773
774 def load_none(self):
775 self.append(None)
776 dispatch[NONE] = load_none
777
Guido van Rossum7d97d312003-01-28 04:25:27 +0000778 def load_false(self):
779 self.append(False)
780 dispatch[NEWFALSE] = load_false
781
782 def load_true(self):
783 self.append(True)
784 dispatch[NEWTRUE] = load_true
785
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000786 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000787 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000788 if data == FALSE[1:]:
789 val = False
790 elif data == TRUE[1:]:
791 val = True
792 else:
793 try:
794 val = int(data)
795 except ValueError:
796 val = long(data)
797 self.append(val)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000798 dispatch[INT] = load_int
799
800 def load_binint(self):
801 self.append(mloads('i' + self.read(4)))
802 dispatch[BININT] = load_binint
803
804 def load_binint1(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000805 self.append(ord(self.read(1)))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000806 dispatch[BININT1] = load_binint1
807
808 def load_binint2(self):
809 self.append(mloads('i' + self.read(2) + '\000\000'))
810 dispatch[BININT2] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000811
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000812 def load_long(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000813 self.append(long(self.readline()[:-1], 0))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000814 dispatch[LONG] = load_long
815
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000816 def load_long1(self):
817 n = ord(self.read(1))
818 bytes = self.read(n)
819 return decode_long(bytes)
820 dispatch[LONG1] = load_long1
821
822 def load_long4(self):
823 n = mloads('i' + self.read(4))
824 bytes = self.read(n)
825 return decode_long(bytes)
826 dispatch[LONG4] = load_long4
827
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000828 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000829 self.append(float(self.readline()[:-1]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000830 dispatch[FLOAT] = load_float
831
Guido van Rossumd3703791998-10-22 20:15:36 +0000832 def load_binfloat(self, unpack=struct.unpack):
833 self.append(unpack('>d', self.read(8))[0])
834 dispatch[BINFLOAT] = load_binfloat
835
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000836 def load_string(self):
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000837 rep = self.readline()[:-1]
Tim Petersad5a7712003-01-28 16:23:33 +0000838 for q in "\"'": # double or single quote
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000839 if rep.startswith(q):
840 if not rep.endswith(q):
841 raise ValueError, "insecure string pickle"
842 rep = rep[len(q):-len(q)]
843 break
844 else:
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000845 raise ValueError, "insecure string pickle"
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000846 self.append(rep.decode("string-escape"))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000847 dispatch[STRING] = load_string
848
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000849 def load_binstring(self):
850 len = mloads('i' + self.read(4))
851 self.append(self.read(len))
852 dispatch[BINSTRING] = load_binstring
853
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000854 def load_unicode(self):
855 self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
856 dispatch[UNICODE] = load_unicode
857
858 def load_binunicode(self):
859 len = mloads('i' + self.read(4))
860 self.append(unicode(self.read(len),'utf-8'))
861 dispatch[BINUNICODE] = load_binunicode
862
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000863 def load_short_binstring(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000864 len = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000865 self.append(self.read(len))
866 dispatch[SHORT_BINSTRING] = load_short_binstring
867
868 def load_tuple(self):
869 k = self.marker()
870 self.stack[k:] = [tuple(self.stack[k+1:])]
871 dispatch[TUPLE] = load_tuple
872
873 def load_empty_tuple(self):
874 self.stack.append(())
875 dispatch[EMPTY_TUPLE] = load_empty_tuple
876
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000877 def load_tuple1(self):
878 self.stack[-1] = (self.stack[-1],)
879 dispatch[TUPLE1] = load_tuple1
880
881 def load_tuple2(self):
882 self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
883 dispatch[TUPLE2] = load_tuple2
884
885 def load_tuple3(self):
886 self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
887 dispatch[TUPLE3] = load_tuple3
888
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000889 def load_empty_list(self):
890 self.stack.append([])
891 dispatch[EMPTY_LIST] = load_empty_list
892
893 def load_empty_dictionary(self):
894 self.stack.append({})
895 dispatch[EMPTY_DICT] = load_empty_dictionary
896
897 def load_list(self):
898 k = self.marker()
899 self.stack[k:] = [self.stack[k+1:]]
900 dispatch[LIST] = load_list
901
902 def load_dict(self):
903 k = self.marker()
904 d = {}
905 items = self.stack[k+1:]
906 for i in range(0, len(items), 2):
907 key = items[i]
908 value = items[i+1]
909 d[key] = value
910 self.stack[k:] = [d]
911 dispatch[DICT] = load_dict
912
913 def load_inst(self):
914 k = self.marker()
915 args = tuple(self.stack[k+1:])
916 del self.stack[k:]
917 module = self.readline()[:-1]
918 name = self.readline()[:-1]
919 klass = self.find_class(module, name)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000920 instantiated = 0
921 if (not args and type(klass) is ClassType and
922 not hasattr(klass, "__getinitargs__")):
923 try:
924 value = _EmptyClass()
925 value.__class__ = klass
Guido van Rossumb19e2a31998-04-13 18:08:45 +0000926 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000927 except RuntimeError:
928 # In restricted execution, assignment to inst.__class__ is
929 # prohibited
930 pass
931 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +0000932 try:
Barry Warsawbf4d9592001-11-15 23:42:58 +0000933 if not hasattr(klass, '__safe_for_unpickling__'):
934 raise UnpicklingError('%s is not safe for unpickling' %
935 klass)
Guido van Rossum743d17e1998-09-15 20:25:57 +0000936 value = apply(klass, args)
937 except TypeError, err:
938 raise TypeError, "in constructor for %s: %s" % (
939 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000940 self.append(value)
941 dispatch[INST] = load_inst
942
943 def load_obj(self):
944 stack = self.stack
945 k = self.marker()
946 klass = stack[k + 1]
947 del stack[k + 1]
Tim Peters2344fae2001-01-15 00:50:52 +0000948 args = tuple(stack[k + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000949 del stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000950 instantiated = 0
951 if (not args and type(klass) is ClassType and
952 not hasattr(klass, "__getinitargs__")):
953 try:
954 value = _EmptyClass()
955 value.__class__ = klass
956 instantiated = 1
957 except RuntimeError:
958 # In restricted execution, assignment to inst.__class__ is
959 # prohibited
960 pass
961 if not instantiated:
962 value = apply(klass, args)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000963 self.append(value)
Tim Peters2344fae2001-01-15 00:50:52 +0000964 dispatch[OBJ] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000965
Guido van Rossum3a41c612003-01-28 15:10:22 +0000966 def load_newobj(self):
967 args = self.stack.pop()
968 cls = self.stack[-1]
969 obj = cls.__new__(cls, *args)
970 self.stack[-1:] = obj
971 dispatch[NEWOBJ] = load_newobj
972
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000973 def load_global(self):
974 module = self.readline()[:-1]
975 name = self.readline()[:-1]
976 klass = self.find_class(module, name)
977 self.append(klass)
978 dispatch[GLOBAL] = load_global
979
980 def find_class(self, module, name):
Barry Warsawbf4d9592001-11-15 23:42:58 +0000981 __import__(module)
982 mod = sys.modules[module]
983 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000984 return klass
985
986 def load_reduce(self):
987 stack = self.stack
988
989 callable = stack[-2]
990 arg_tup = stack[-1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000991 del stack[-2:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000992
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000993 if type(callable) is not ClassType:
Raymond Hettinger54f02222002-06-01 14:18:47 +0000994 if not callable in safe_constructors:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000995 try:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000996 safe = callable.__safe_for_unpickling__
997 except AttributeError:
998 safe = None
Guido van Rossuma48061a1995-01-10 00:31:14 +0000999
Tim Petersc32d8242001-04-10 02:48:53 +00001000 if not safe:
Tim Peters2344fae2001-01-15 00:50:52 +00001001 raise UnpicklingError, "%s is not safe for " \
1002 "unpickling" % callable
Guido van Rossuma48061a1995-01-10 00:31:14 +00001003
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001004 if arg_tup is None:
Guido van Rossumbc64e222003-01-28 16:34:19 +00001005 # A hack for Jim Fulton's ExtensionClass, now deprecated
1006 warnings.warn("__basicnew__ special case is deprecated",
Tim Peters8ac14952002-05-23 15:15:30 +00001007 DeprecationWarning)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001008 value = callable.__basicnew__()
1009 else:
1010 value = apply(callable, arg_tup)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001011 self.append(value)
1012 dispatch[REDUCE] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +00001013
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001014 def load_pop(self):
1015 del self.stack[-1]
1016 dispatch[POP] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +00001017
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001018 def load_pop_mark(self):
1019 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001020 del self.stack[k:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001021 dispatch[POP_MARK] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001022
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001023 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +00001024 self.append(self.stack[-1])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001025 dispatch[DUP] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +00001026
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001027 def load_get(self):
1028 self.append(self.memo[self.readline()[:-1]])
1029 dispatch[GET] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +00001030
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001031 def load_binget(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001032 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001033 self.append(self.memo[`i`])
1034 dispatch[BINGET] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001035
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001036 def load_long_binget(self):
1037 i = mloads('i' + self.read(4))
1038 self.append(self.memo[`i`])
1039 dispatch[LONG_BINGET] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001040
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001041 def load_put(self):
1042 self.memo[self.readline()[:-1]] = self.stack[-1]
1043 dispatch[PUT] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +00001044
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001045 def load_binput(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001046 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001047 self.memo[`i`] = self.stack[-1]
1048 dispatch[BINPUT] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001049
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001050 def load_long_binput(self):
1051 i = mloads('i' + self.read(4))
1052 self.memo[`i`] = self.stack[-1]
1053 dispatch[LONG_BINPUT] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001054
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001055 def load_append(self):
1056 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001057 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001058 list = stack[-1]
1059 list.append(value)
1060 dispatch[APPEND] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +00001061
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001062 def load_appends(self):
1063 stack = self.stack
1064 mark = self.marker()
1065 list = stack[mark - 1]
Tim Peters209ad952003-01-28 01:44:45 +00001066 list.extend(stack[mark + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001067 del stack[mark:]
1068 dispatch[APPENDS] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +00001069
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001070 def load_setitem(self):
1071 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001072 value = stack.pop()
1073 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001074 dict = stack[-1]
1075 dict[key] = value
1076 dispatch[SETITEM] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001077
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001078 def load_setitems(self):
1079 stack = self.stack
1080 mark = self.marker()
1081 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001082 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001083 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001084
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001085 del stack[mark:]
1086 dispatch[SETITEMS] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001087
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001088 def load_build(self):
1089 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001090 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001091 inst = stack[-1]
1092 try:
1093 setstate = inst.__setstate__
1094 except AttributeError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001095 try:
1096 inst.__dict__.update(value)
1097 except RuntimeError:
1098 # XXX In restricted execution, the instance's __dict__ is not
1099 # accessible. Use the old way of unpickling the instance
1100 # variables. This is a semantic different when unpickling in
1101 # restricted vs. unrestricted modes.
1102 for k, v in value.items():
1103 setattr(inst, k, v)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001104 else:
1105 setstate(value)
1106 dispatch[BUILD] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001107
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001108 def load_mark(self):
1109 self.append(self.mark)
1110 dispatch[MARK] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001111
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001112 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001113 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001114 raise _Stop(value)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001115 dispatch[STOP] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001116
Guido van Rossume467be61997-12-05 19:42:42 +00001117# Helper class for load_inst/load_obj
1118
1119class _EmptyClass:
1120 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001121
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001122# Encode/decode longs.
1123
1124def encode_long(x):
1125 r"""Encode a long to a two's complement little-ending binary string.
1126 >>> encode_long(255L)
1127 '\xff\x00'
1128 >>> encode_long(32767L)
1129 '\xff\x7f'
1130 >>> encode_long(-256L)
1131 '\x00\xff'
1132 >>> encode_long(-32768L)
1133 '\x00\x80'
1134 >>> encode_long(-128L)
1135 '\x80'
1136 >>> encode_long(127L)
1137 '\x7f'
1138 >>>
1139 """
1140 digits = []
1141 while not -128 <= x < 128:
1142 digits.append(x & 0xff)
1143 x >>= 8
1144 digits.append(x & 0xff)
1145 return "".join(map(chr, digits))
1146
1147def decode_long(data):
1148 r"""Decode a long from a two's complement little-endian binary string.
1149 >>> decode_long("\xff\x00")
1150 255L
1151 >>> decode_long("\xff\x7f")
1152 32767L
1153 >>> decode_long("\x00\xff")
1154 -256L
1155 >>> decode_long("\x00\x80")
1156 -32768L
1157 >>> decode_long("\x80")
1158 -128L
1159 >>> decode_long("\x7f")
1160 127L
1161 """
1162 x = 0L
1163 i = 0L
1164 for c in data:
1165 x |= long(ord(c)) << i
1166 i += 8L
1167 if data and ord(c) >= 0x80:
1168 x -= 1L << i
1169 return x
1170
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001171# Shorthands
1172
Jeremy Hyltonabe2c622001-10-15 21:29:28 +00001173try:
1174 from cStringIO import StringIO
1175except ImportError:
1176 from StringIO import StringIO
Guido van Rossumc7c5e691996-07-22 22:26:07 +00001177
Guido van Rossum3a41c612003-01-28 15:10:22 +00001178def dump(obj, file, proto=1):
1179 Pickler(file, proto).dump(obj)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001180
Guido van Rossum3a41c612003-01-28 15:10:22 +00001181def dumps(obj, proto=1):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001182 file = StringIO()
Guido van Rossum3a41c612003-01-28 15:10:22 +00001183 Pickler(file, proto).dump(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001184 return file.getvalue()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001185
1186def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001187 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001188
1189def loads(str):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001190 file = StringIO(str)
1191 return Unpickler(file).load()
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001192
1193# Doctest
1194
1195def _test():
1196 import doctest
1197 return doctest.testmod()
1198
1199if __name__ == "__main__":
1200 _test()