blob: 74748f8ca97d5cba291bbba0588ed6476c97ac2b [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 Rossum5aac4e62003-02-06 22:57:00 +000030from copy_reg import dispatch_table, _reconstructor, _better_reduce
Guido van Rossumd4b920c2003-02-04 01:54:49 +000031from copy_reg import _extension_registry, _inverted_registry, _extension_cache
Guido van Rossumd3703791998-10-22 20:15:36 +000032import marshal
33import sys
34import struct
Skip Montanaro23bafc62001-02-18 03:10:09 +000035import re
Guido van Rossumbc64e222003-01-28 16:34:19 +000036import warnings
Guido van Rossuma48061a1995-01-10 00:31:14 +000037
Skip Montanaro352674d2001-02-07 23:14:30 +000038__all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler",
39 "Unpickler", "dump", "dumps", "load", "loads"]
40
Tim Petersc0c12b52003-01-29 00:56:17 +000041# These are purely informational; no code uses these.
Guido van Rossumf29d3d62003-01-27 22:47:53 +000042format_version = "2.0" # File format version we write
43compatible_formats = ["1.0", # Original protocol 0
Guido van Rossumbc64e222003-01-28 16:34:19 +000044 "1.1", # Protocol 0 with INST added
Guido van Rossumf29d3d62003-01-27 22:47:53 +000045 "1.2", # Original protocol 1
46 "1.3", # Protocol 1 with BINFLOAT added
47 "2.0", # Protocol 2
48 ] # Old format versions we can read
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000049
Tim Peters8587b3c2003-02-13 15:44:41 +000050# Keep in synch with cPickle. This is the highest protocol number we
51# know how to read.
52HIGHEST_PROTOCOL = 2
53
Guido van Rossume0b90422003-01-28 03:17:21 +000054# Why use struct.pack() for pickling but marshal.loads() for
Tim Petersc0c12b52003-01-29 00:56:17 +000055# unpickling? struct.pack() is 40% faster than marshal.dumps(), but
Guido van Rossume0b90422003-01-28 03:17:21 +000056# marshal.loads() is twice as fast as struct.unpack()!
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000057mloads = marshal.loads
Guido van Rossum0c891ce1995-03-14 15:09:05 +000058
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000059class PickleError(Exception):
Neal Norwitzefbb67b2002-05-30 12:12:04 +000060 """A common base class for the other pickling exceptions."""
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000061 pass
62
63class PicklingError(PickleError):
64 """This exception is raised when an unpicklable object is passed to the
65 dump() method.
66
67 """
68 pass
69
70class UnpicklingError(PickleError):
71 """This exception is raised when there is a problem unpickling an object,
72 such as a security violation.
73
74 Note that other exceptions may also be raised during unpickling, including
75 (but not necessarily limited to) AttributeError, EOFError, ImportError,
76 and IndexError.
77
78 """
79 pass
Guido van Rossum7849da81995-03-09 14:08:35 +000080
Tim Petersc0c12b52003-01-29 00:56:17 +000081# An instance of _Stop is raised by Unpickler.load_stop() in response to
82# the STOP opcode, passing the object that is the result of unpickling.
Guido van Rossumff871742000-12-13 18:11:56 +000083class _Stop(Exception):
84 def __init__(self, value):
85 self.value = value
86
Guido van Rossum533dbcf2003-01-28 17:55:05 +000087# Jython has PyStringMap; it's a dict subclass with string keys
Jeremy Hylton2b9d0291998-05-27 22:38:22 +000088try:
89 from org.python.core import PyStringMap
90except ImportError:
91 PyStringMap = None
92
Guido van Rossum533dbcf2003-01-28 17:55:05 +000093# UnicodeType may or may not be exported (normally imported from types)
Guido van Rossumdbb718f2001-09-21 19:22:34 +000094try:
95 UnicodeType
96except NameError:
97 UnicodeType = None
98
Tim Peters22a449a2003-01-27 20:16:36 +000099# Pickle opcodes. See pickletools.py for extensive docs. The listing
100# here is in kind-of alphabetical order of 1-character pickle code.
101# pickletools groups them by purpose.
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000102
Tim Peters22a449a2003-01-27 20:16:36 +0000103MARK = '(' # push special markobject on stack
104STOP = '.' # every pickle ends with STOP
105POP = '0' # discard topmost stack item
106POP_MARK = '1' # discard stack top through topmost markobject
107DUP = '2' # duplicate top stack item
108FLOAT = 'F' # push float object; decimal string argument
109INT = 'I' # push integer or bool; decimal string argument
110BININT = 'J' # push four-byte signed int
111BININT1 = 'K' # push 1-byte unsigned int
112LONG = 'L' # push long; decimal string argument
113BININT2 = 'M' # push 2-byte unsigned int
114NONE = 'N' # push None
115PERSID = 'P' # push persistent object; id is taken from string arg
116BINPERSID = 'Q' # " " " ; " " " " stack
117REDUCE = 'R' # apply callable to argtuple, both on stack
118STRING = 'S' # push string; NL-terminated string argument
119BINSTRING = 'T' # push string; counted binary string argument
120SHORT_BINSTRING = 'U' # " " ; " " " " < 256 bytes
121UNICODE = 'V' # push Unicode string; raw-unicode-escaped'd argument
122BINUNICODE = 'X' # " " " ; counted UTF-8 string argument
123APPEND = 'a' # append stack top to list below it
124BUILD = 'b' # call __setstate__ or __dict__.update()
125GLOBAL = 'c' # push self.find_class(modname, name); 2 string args
126DICT = 'd' # build a dict from stack items
127EMPTY_DICT = '}' # push empty dict
128APPENDS = 'e' # extend list on stack by topmost stack slice
129GET = 'g' # push item from memo on stack; index is string arg
130BINGET = 'h' # " " " " " " ; " " 1-byte arg
131INST = 'i' # build & push class instance
132LONG_BINGET = 'j' # push item from memo on stack; index is 4-byte arg
133LIST = 'l' # build list from topmost stack items
134EMPTY_LIST = ']' # push empty list
135OBJ = 'o' # build & push class instance
136PUT = 'p' # store stack top in memo; index is string arg
137BINPUT = 'q' # " " " " " ; " " 1-byte arg
138LONG_BINPUT = 'r' # " " " " " ; " " 4-byte arg
139SETITEM = 's' # add key+value pair to dict
140TUPLE = 't' # build tuple from topmost stack items
141EMPTY_TUPLE = ')' # push empty tuple
142SETITEMS = 'u' # modify dict by adding topmost key+value pairs
143BINFLOAT = 'G' # push float; arg is 8-byte float encoding
144
145TRUE = 'I01\n' # not an opcode; see INT docs in pickletools.py
146FALSE = 'I00\n' # not an opcode; see INT docs in pickletools.py
Guido van Rossum77f6a652002-04-03 22:41:51 +0000147
Guido van Rossum586c9e82003-01-29 06:16:12 +0000148# Protocol 2
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000149
Tim Peterse1054782003-01-28 00:22:12 +0000150PROTO = '\x80' # identify pickle protocol
151NEWOBJ = '\x81' # build object by applying cls.__new__ to argtuple
152EXT1 = '\x82' # push object from extension registry; 1-byte index
153EXT2 = '\x83' # ditto, but 2-byte index
154EXT4 = '\x84' # ditto, but 4-byte index
155TUPLE1 = '\x85' # build 1-tuple from stack top
156TUPLE2 = '\x86' # build 2-tuple from two topmost stack items
157TUPLE3 = '\x87' # build 3-tuple from three topmost stack items
158NEWTRUE = '\x88' # push True
159NEWFALSE = '\x89' # push False
160LONG1 = '\x8a' # push long from < 256 bytes
161LONG4 = '\x8b' # push really big long
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000162
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000163_tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3]
164
Guido van Rossuma48061a1995-01-10 00:31:14 +0000165
Skip Montanaro23bafc62001-02-18 03:10:09 +0000166__all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
Neal Norwitzd5ba4ae2002-02-11 18:12:06 +0000167del x
Skip Montanaro23bafc62001-02-18 03:10:09 +0000168
Guido van Rossum1be31752003-01-28 15:19:53 +0000169
170# Pickling machinery
171
Guido van Rossuma48061a1995-01-10 00:31:14 +0000172class Pickler:
173
Guido van Rossumcf117b02003-02-09 17:19:41 +0000174 def __init__(self, file, protocol=None, bin=None):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000175 """This takes a file-like object for writing a pickle data stream.
176
Guido van Rossumcf117b02003-02-09 17:19:41 +0000177 The optional protocol argument tells the pickler to use the
178 given protocol; supported protocols are 0, 1, 2. The default
Guido van Rossum7eff63a2003-01-31 19:42:31 +0000179 protocol is 0, to be backwards compatible. (Protocol 0 is the
180 only protocol that can be written to a file opened in text
Tim Peters5bd2a792003-02-01 16:45:06 +0000181 mode and read back successfully. When using a protocol higher
182 than 0, make sure the file is opened in binary mode, both when
183 pickling and unpickling.)
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000184
185 Protocol 1 is more efficient than protocol 0; protocol 2 is
Guido van Rossum7eff63a2003-01-31 19:42:31 +0000186 more efficient than protocol 1.
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000187
Guido van Rossum7eff63a2003-01-31 19:42:31 +0000188 Specifying a negative protocol version selects the highest
Tim Peters5bd2a792003-02-01 16:45:06 +0000189 protocol version supported. The higher the protocol used, the
190 more recent the version of Python needed to read the pickle
191 produced.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000192
193 The file parameter must have a write() method that accepts a single
194 string argument. It can thus be an open file object, a StringIO
195 object, or any other custom object that meets this interface.
196
197 """
Guido van Rossumcf117b02003-02-09 17:19:41 +0000198 if protocol is not None and bin is not None:
199 raise ValueError, "can't specify both 'protocol' and 'bin'"
Guido van Rossum795ea892003-02-03 16:59:48 +0000200 if bin is not None:
201 warnings.warn("The 'bin' argument to Pickler() is deprecated",
202 PendingDeprecationWarning)
Guido van Rossumcf117b02003-02-09 17:19:41 +0000203 protocol = bin
204 if protocol is None:
205 protocol = 0
206 if protocol < 0:
Tim Peters8587b3c2003-02-13 15:44:41 +0000207 protocol = HIGHEST_PROTOCOL
208 elif not 0 <= protocol <= HIGHEST_PROTOCOL:
209 raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000210 self.write = file.write
211 self.memo = {}
Guido van Rossumcf117b02003-02-09 17:19:41 +0000212 self.proto = int(protocol)
213 self.bin = protocol >= 1
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000214 self.fast = 0
Guido van Rossuma48061a1995-01-10 00:31:14 +0000215
Fred Drake7f781c92002-05-01 20:33:53 +0000216 def clear_memo(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000217 """Clears the pickler's "memo".
218
219 The memo is the data structure that remembers which objects the
Tim Petersb377f8a2003-01-28 00:23:36 +0000220 pickler has already seen, so that shared or recursive objects are
221 pickled by reference and not by value. This method is useful when
222 re-using picklers.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000223
224 """
Fred Drake7f781c92002-05-01 20:33:53 +0000225 self.memo.clear()
226
Guido van Rossum3a41c612003-01-28 15:10:22 +0000227 def dump(self, obj):
Tim Peters5bd2a792003-02-01 16:45:06 +0000228 """Write a pickled representation of obj to the open file."""
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000229 if self.proto >= 2:
230 self.write(PROTO + chr(self.proto))
Guido van Rossum3a41c612003-01-28 15:10:22 +0000231 self.save(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000232 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000233
Jeremy Hylton3422c992003-01-24 19:29:52 +0000234 def memoize(self, obj):
235 """Store an object in the memo."""
236
Tim Peterse46b73f2003-01-27 21:22:10 +0000237 # The Pickler memo is a dictionary mapping object ids to 2-tuples
238 # that contain the Unpickler memo key and the object being memoized.
239 # The memo key is written to the pickle and will become
Jeremy Hylton3422c992003-01-24 19:29:52 +0000240 # the key in the Unpickler's memo. The object is stored in the
Tim Peterse46b73f2003-01-27 21:22:10 +0000241 # Pickler memo so that transient objects are kept alive during
242 # pickling.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000243
Tim Peterse46b73f2003-01-27 21:22:10 +0000244 # The use of the Unpickler memo length as the memo key is just a
245 # convention. The only requirement is that the memo values be unique.
246 # But there appears no advantage to any other scheme, and this
Tim Peterscbd0a322003-01-28 00:24:43 +0000247 # scheme allows the Unpickler memo to be implemented as a plain (but
Tim Peterse46b73f2003-01-27 21:22:10 +0000248 # growable) array, indexed by memo key.
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000249 if self.fast:
250 return
Guido van Rossum9b40e802003-01-30 06:37:41 +0000251 assert id(obj) not in self.memo
Jeremy Hylton3422c992003-01-24 19:29:52 +0000252 memo_len = len(self.memo)
253 self.write(self.put(memo_len))
Tim Peters518df0d2003-01-28 01:00:38 +0000254 self.memo[id(obj)] = memo_len, obj
Jeremy Hylton3422c992003-01-24 19:29:52 +0000255
Tim Petersbb38e302003-01-27 21:25:41 +0000256 # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000257 def put(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000258 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000259 if i < 256:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000260 return BINPUT + chr(i)
261 else:
262 return LONG_BINPUT + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000263
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000264 return PUT + `i` + '\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000265
Tim Petersbb38e302003-01-27 21:25:41 +0000266 # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000267 def get(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000268 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000269 if i < 256:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000270 return BINGET + chr(i)
271 else:
272 return LONG_BINGET + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000273
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000274 return GET + `i` + '\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000275
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000276 def save(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000277 # Check for persistent id (defined by a subclass)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000278 pid = self.persistent_id(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000279 if pid:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000280 self.save_pers(pid)
281 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000282
Guido van Rossumbc64e222003-01-28 16:34:19 +0000283 # Check the memo
284 x = self.memo.get(id(obj))
285 if x:
286 self.write(self.get(x[0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000287 return
288
Guido van Rossumbc64e222003-01-28 16:34:19 +0000289 # Check the type dispatch table
Guido van Rossum3a41c612003-01-28 15:10:22 +0000290 t = type(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000291 f = self.dispatch.get(t)
292 if f:
293 f(self, obj) # Call unbound method with explicit self
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000294 return
295
Guido van Rossumbc64e222003-01-28 16:34:19 +0000296 # Check for a class with a custom metaclass; treat as regular class
Tim Petersb32a8312003-01-28 00:48:09 +0000297 try:
298 issc = issubclass(t, TypeType)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000299 except TypeError: # t is not a class (old Boost; see SF #502085)
Tim Petersb32a8312003-01-28 00:48:09 +0000300 issc = 0
301 if issc:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000302 self.save_global(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000303 return
304
Guido van Rossumbc64e222003-01-28 16:34:19 +0000305 # Check copy_reg.dispatch_table
306 reduce = dispatch_table.get(t)
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000307 if not reduce:
308 # Check for a __reduce__ method.
309 # Subtle: get the unbound method from the class, so that
310 # protocol 2 can override the default __reduce__ that all
311 # classes inherit from object. This has the added
312 # advantage that the call always has the form reduce(obj)
313 reduce = getattr(t, "__reduce__", None)
314 if self.proto >= 2:
315 # Protocol 2 can do better than the default __reduce__
316 if reduce is object.__reduce__:
Guido van Rossum5aac4e62003-02-06 22:57:00 +0000317 reduce = _better_reduce
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000318 if not reduce:
Guido van Rossumbc64e222003-01-28 16:34:19 +0000319 raise PicklingError("Can't pickle %r object: %r" %
320 (t.__name__, obj))
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000321 rv = reduce(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000322
Guido van Rossumbc64e222003-01-28 16:34:19 +0000323 # Check for string returned by reduce(), meaning "save as global"
324 if type(rv) is StringType:
325 self.save_global(obj, rv)
Tim Petersb32a8312003-01-28 00:48:09 +0000326 return
327
Guido van Rossumbc64e222003-01-28 16:34:19 +0000328 # Assert that reduce() returned a tuple
329 if type(rv) is not TupleType:
330 raise PicklingError("%s must return string or tuple" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000331
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000332 # Assert that it returned an appropriately sized tuple
Guido van Rossumbc64e222003-01-28 16:34:19 +0000333 l = len(rv)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000334 if not (2 <= l <= 5):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000335 raise PicklingError("Tuple returned by %s must have "
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000336 "two to five elements" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000337
Guido van Rossumbc64e222003-01-28 16:34:19 +0000338 # Save the reduce() output and finally memoize the object
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000339 self.save_reduce(obj=obj, *rv)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000340
Guido van Rossum3a41c612003-01-28 15:10:22 +0000341 def persistent_id(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000342 # This exists so a subclass can override it
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000343 return None
344
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000345 def save_pers(self, pid):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000346 # Save a persistent id reference
Tim Petersbd1cdb92003-01-28 01:03:10 +0000347 if self.bin:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000348 self.save(pid)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000349 self.write(BINPERSID)
Tim Petersbd1cdb92003-01-28 01:03:10 +0000350 else:
351 self.write(PERSID + str(pid) + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000352
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000353 def save_reduce(self, func, args, state=None,
354 listitems=None, dictitems=None, obj=None):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000355 # This API is be called by some subclasses
356
357 # Assert that args is a tuple or None
358 if not isinstance(args, TupleType):
359 if args is None:
360 # A hack for Jim Fulton's ExtensionClass, now deprecated.
361 # See load_reduce()
362 warnings.warn("__basicnew__ special case is deprecated",
363 DeprecationWarning)
364 else:
365 raise PicklingError(
366 "args from reduce() should be a tuple")
367
368 # Assert that func is callable
369 if not callable(func):
370 raise PicklingError("func from reduce should be callable")
371
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000372 save = self.save
Guido van Rossumbc64e222003-01-28 16:34:19 +0000373 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000374
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000375 # Protocol 2 special case: if func's name is __newobj__, use NEWOBJ
376 if self.proto >= 2 and getattr(func, "__name__", "") == "__newobj__":
377 # A __reduce__ implementation can direct protocol 2 to
378 # use the more efficient NEWOBJ opcode, while still
379 # allowing protocol 0 and 1 to work normally. For this to
380 # work, the function returned by __reduce__ should be
381 # called __newobj__, and its first argument should be a
382 # new-style class. The implementation for __newobj__
383 # should be as follows, although pickle has no way to
384 # verify this:
385 #
386 # def __newobj__(cls, *args):
387 # return cls.__new__(cls, *args)
388 #
389 # Protocols 0 and 1 will pickle a reference to __newobj__,
390 # while protocol 2 (and above) will pickle a reference to
391 # cls, the remaining args tuple, and the NEWOBJ code,
392 # which calls cls.__new__(cls, *args) at unpickling time
393 # (see load_newobj below). If __reduce__ returns a
394 # three-tuple, the state from the third tuple item will be
395 # pickled regardless of the protocol, calling __setstate__
396 # at unpickling time (see load_build below).
397 #
398 # Note that no standard __newobj__ implementation exists;
399 # you have to provide your own. This is to enforce
400 # compatibility with Python 2.2 (pickles written using
401 # protocol 0 or 1 in Python 2.3 should be unpicklable by
402 # Python 2.2).
403 cls = args[0]
404 if not hasattr(cls, "__new__"):
405 raise PicklingError(
406 "args[0] from __newobj__ args has no __new__")
Guido van Rossumf7f45172003-01-31 17:17:49 +0000407 if obj is not None and cls is not obj.__class__:
408 raise PicklingError(
409 "args[0] from __newobj__ args has the wrong class")
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000410 args = args[1:]
411 save(cls)
412 save(args)
413 write(NEWOBJ)
414 else:
415 save(func)
416 save(args)
417 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000418
Guido van Rossumf7f45172003-01-31 17:17:49 +0000419 if obj is not None:
420 self.memoize(obj)
421
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000422 # More new special cases (that work with older protocols as
423 # well): when __reduce__ returns a tuple with 4 or 5 items,
424 # the 4th and 5th item should be iterators that provide list
425 # items and dict items (as (key, value) tuples), or None.
426
427 if listitems is not None:
428 self._batch_appends(listitems)
429
430 if dictitems is not None:
431 self._batch_setitems(dictitems)
432
Tim Petersc32d8242001-04-10 02:48:53 +0000433 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000434 save(state)
435 write(BUILD)
436
Guido van Rossumbc64e222003-01-28 16:34:19 +0000437 # Methods below this point are dispatched through the dispatch table
438
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000439 dispatch = {}
440
Guido van Rossum3a41c612003-01-28 15:10:22 +0000441 def save_none(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000442 self.write(NONE)
443 dispatch[NoneType] = save_none
444
Guido van Rossum3a41c612003-01-28 15:10:22 +0000445 def save_bool(self, obj):
Guido van Rossum7d97d312003-01-28 04:25:27 +0000446 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000447 self.write(obj and NEWTRUE or NEWFALSE)
Guido van Rossum7d97d312003-01-28 04:25:27 +0000448 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000449 self.write(obj and TRUE or FALSE)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000450 dispatch[bool] = save_bool
451
Guido van Rossum3a41c612003-01-28 15:10:22 +0000452 def save_int(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000453 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000454 # If the int is small enough to fit in a signed 4-byte 2's-comp
455 # format, we can store it more efficiently than the general
456 # case.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000457 # First one- and two-byte unsigned ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000458 if obj >= 0:
459 if obj <= 0xff:
460 self.write(BININT1 + chr(obj))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000461 return
Guido van Rossum3a41c612003-01-28 15:10:22 +0000462 if obj <= 0xffff:
Guido van Rossumba884f32003-01-29 20:14:23 +0000463 self.write("%c%c%c" % (BININT2, obj&0xff, obj>>8))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000464 return
465 # Next check for 4-byte signed ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000466 high_bits = obj >> 31 # note that Python shift sign-extends
Tim Petersd95c2df2003-01-28 03:41:54 +0000467 if high_bits == 0 or high_bits == -1:
Tim Peters44714002001-04-10 05:02:52 +0000468 # All high bits are copies of bit 2**31, so the value
469 # fits in a 4-byte signed int.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000470 self.write(BININT + pack("<i", obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000471 return
Tim Peters44714002001-04-10 05:02:52 +0000472 # Text pickle, or int too big to fit in signed 4-byte format.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000473 self.write(INT + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000474 dispatch[IntType] = save_int
475
Guido van Rossum3a41c612003-01-28 15:10:22 +0000476 def save_long(self, obj, pack=struct.pack):
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000477 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000478 bytes = encode_long(obj)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000479 n = len(bytes)
480 if n < 256:
481 self.write(LONG1 + chr(n) + bytes)
482 else:
483 self.write(LONG4 + pack("<i", n) + bytes)
Tim Petersee1a53c2003-02-02 02:57:53 +0000484 return
Guido van Rossum3a41c612003-01-28 15:10:22 +0000485 self.write(LONG + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000486 dispatch[LongType] = save_long
487
Guido van Rossum3a41c612003-01-28 15:10:22 +0000488 def save_float(self, obj, pack=struct.pack):
Guido van Rossumd3703791998-10-22 20:15:36 +0000489 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000490 self.write(BINFLOAT + pack('>d', obj))
Guido van Rossumd3703791998-10-22 20:15:36 +0000491 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000492 self.write(FLOAT + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000493 dispatch[FloatType] = save_float
494
Guido van Rossum3a41c612003-01-28 15:10:22 +0000495 def save_string(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000496 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000497 n = len(obj)
Tim Petersbbf63cd2003-01-27 21:15:36 +0000498 if n < 256:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000499 self.write(SHORT_BINSTRING + chr(n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000500 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000501 self.write(BINSTRING + pack("<i", n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000502 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000503 self.write(STRING + `obj` + '\n')
504 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000505 dispatch[StringType] = save_string
506
Guido van Rossum3a41c612003-01-28 15:10:22 +0000507 def save_unicode(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000508 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000509 encoding = obj.encode('utf-8')
Tim Petersbbf63cd2003-01-27 21:15:36 +0000510 n = len(encoding)
Guido van Rossum5c938d02003-01-28 03:03:08 +0000511 self.write(BINUNICODE + pack("<i", n) + encoding)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000512 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000513 obj = obj.replace("\\", "\\u005c")
514 obj = obj.replace("\n", "\\u000a")
515 self.write(UNICODE + obj.encode('raw-unicode-escape') + '\n')
516 self.memoize(obj)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000517 dispatch[UnicodeType] = save_unicode
518
Guido van Rossum31584cb2001-01-22 14:53:29 +0000519 if StringType == UnicodeType:
520 # This is true for Jython
Guido van Rossum3a41c612003-01-28 15:10:22 +0000521 def save_string(self, obj, pack=struct.pack):
522 unicode = obj.isunicode()
Guido van Rossum31584cb2001-01-22 14:53:29 +0000523
Tim Petersc32d8242001-04-10 02:48:53 +0000524 if self.bin:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000525 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000526 obj = obj.encode("utf-8")
527 l = len(obj)
Tim Petersc32d8242001-04-10 02:48:53 +0000528 if l < 256 and not unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000529 self.write(SHORT_BINSTRING + chr(l) + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000530 else:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000531 s = pack("<i", l)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000532 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000533 self.write(BINUNICODE + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000534 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000535 self.write(BINSTRING + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000536 else:
Tim Peters658cba62001-02-09 20:06:00 +0000537 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000538 obj = obj.replace("\\", "\\u005c")
539 obj = obj.replace("\n", "\\u000a")
540 obj = obj.encode('raw-unicode-escape')
541 self.write(UNICODE + obj + '\n')
Guido van Rossum31584cb2001-01-22 14:53:29 +0000542 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000543 self.write(STRING + `obj` + '\n')
544 self.memoize(obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000545 dispatch[StringType] = save_string
Tim Peters658cba62001-02-09 20:06:00 +0000546
Guido van Rossum3a41c612003-01-28 15:10:22 +0000547 def save_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000548 write = self.write
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000549 proto = self.proto
550
Guido van Rossum3a41c612003-01-28 15:10:22 +0000551 n = len(obj)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000552 if n == 0:
553 if proto:
554 write(EMPTY_TUPLE)
555 else:
556 write(MARK + TUPLE)
Tim Petersd97da802003-01-28 05:48:29 +0000557 return
558
559 save = self.save
560 memo = self.memo
561 if n <= 3 and proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000562 for element in obj:
Tim Petersd97da802003-01-28 05:48:29 +0000563 save(element)
564 # Subtle. Same as in the big comment below.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000565 if id(obj) in memo:
566 get = self.get(memo[id(obj)][0])
Tim Petersd97da802003-01-28 05:48:29 +0000567 write(POP * n + get)
568 else:
569 write(_tuplesize2code[n])
Guido van Rossum3a41c612003-01-28 15:10:22 +0000570 self.memoize(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000571 return
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000572
Tim Peters1d63c9f2003-02-02 20:29:39 +0000573 # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple
Tim Petersff57bff2003-01-28 05:34:53 +0000574 # has more than 3 elements.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000575 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000576 for element in obj:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000577 save(element)
578
Tim Peters1d63c9f2003-02-02 20:29:39 +0000579 if id(obj) in memo:
Tim Petersf558da02003-01-28 02:09:55 +0000580 # Subtle. d was not in memo when we entered save_tuple(), so
581 # the process of saving the tuple's elements must have saved
582 # the tuple itself: the tuple is recursive. The proper action
583 # now is to throw away everything we put on the stack, and
584 # simply GET the tuple (it's already constructed). This check
585 # could have been done in the "for element" loop instead, but
586 # recursive tuples are a rare thing.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000587 get = self.get(memo[id(obj)][0])
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000588 if proto:
Tim Petersf558da02003-01-28 02:09:55 +0000589 write(POP_MARK + get)
590 else: # proto 0 -- POP_MARK not available
Tim Petersd97da802003-01-28 05:48:29 +0000591 write(POP * (n+1) + get)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000592 return
593
Tim Peters1d63c9f2003-02-02 20:29:39 +0000594 # No recursion.
Tim Peters518df0d2003-01-28 01:00:38 +0000595 self.write(TUPLE)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000596 self.memoize(obj)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000597
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000598 dispatch[TupleType] = save_tuple
599
Tim Petersa6ae9a22003-01-28 16:58:41 +0000600 # save_empty_tuple() isn't used by anything in Python 2.3. However, I
601 # found a Pickler subclass in Zope3 that calls it, so it's not harmless
602 # to remove it.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000603 def save_empty_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000604 self.write(EMPTY_TUPLE)
605
Guido van Rossum3a41c612003-01-28 15:10:22 +0000606 def save_list(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000607 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000608
Tim Petersc32d8242001-04-10 02:48:53 +0000609 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000610 write(EMPTY_LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000611 else: # proto 0 -- can't use EMPTY_LIST
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000612 write(MARK + LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000613
614 self.memoize(obj)
615 self._batch_appends(iter(obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000616
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000617 dispatch[ListType] = save_list
618
Tim Peters42f08ac2003-02-11 22:43:24 +0000619 # Keep in synch with cPickle's BATCHSIZE. Nothing will break if it gets
620 # out of synch, though.
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000621 _BATCHSIZE = 1000
622
623 def _batch_appends(self, items):
624 # Helper to batch up APPENDS sequences
625 save = self.save
626 write = self.write
627
628 if not self.bin:
629 for x in items:
630 save(x)
631 write(APPEND)
632 return
633
634 r = xrange(self._BATCHSIZE)
635 while items is not None:
636 tmp = []
637 for i in r:
638 try:
Guido van Rossum5aac4e62003-02-06 22:57:00 +0000639 x = items.next()
640 tmp.append(x)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000641 except StopIteration:
642 items = None
643 break
644 n = len(tmp)
645 if n > 1:
646 write(MARK)
647 for x in tmp:
648 save(x)
649 write(APPENDS)
650 elif n:
651 save(tmp[0])
652 write(APPEND)
653 # else tmp is empty, and we're done
654
Guido van Rossum3a41c612003-01-28 15:10:22 +0000655 def save_dict(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000656 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000657
Tim Petersc32d8242001-04-10 02:48:53 +0000658 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000659 write(EMPTY_DICT)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000660 else: # proto 0 -- can't use EMPTY_DICT
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000661 write(MARK + DICT)
662
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000663 self.memoize(obj)
664 self._batch_setitems(obj.iteritems())
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000665
666 dispatch[DictionaryType] = save_dict
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000667 if not PyStringMap is None:
668 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000669
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000670 def _batch_setitems(self, items):
671 # Helper to batch up SETITEMS sequences; proto >= 1 only
672 save = self.save
673 write = self.write
674
675 if not self.bin:
676 for k, v in items:
677 save(k)
678 save(v)
679 write(SETITEM)
680 return
681
682 r = xrange(self._BATCHSIZE)
683 while items is not None:
684 tmp = []
685 for i in r:
686 try:
687 tmp.append(items.next())
688 except StopIteration:
689 items = None
690 break
691 n = len(tmp)
692 if n > 1:
693 write(MARK)
694 for k, v in tmp:
695 save(k)
696 save(v)
697 write(SETITEMS)
698 elif n:
699 k, v = tmp[0]
700 save(k)
701 save(v)
702 write(SETITEM)
703 # else tmp is empty, and we're done
704
Guido van Rossum3a41c612003-01-28 15:10:22 +0000705 def save_inst(self, obj):
706 cls = obj.__class__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000707
708 memo = self.memo
709 write = self.write
710 save = self.save
711
Guido van Rossum3a41c612003-01-28 15:10:22 +0000712 if hasattr(obj, '__getinitargs__'):
713 args = obj.__getinitargs__()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000714 len(args) # XXX Assert it's a sequence
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000715 _keep_alive(args, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000716 else:
717 args = ()
718
719 write(MARK)
720
Tim Petersc32d8242001-04-10 02:48:53 +0000721 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000722 save(cls)
Tim Peters3b769832003-01-28 03:51:36 +0000723 for arg in args:
724 save(arg)
725 write(OBJ)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000726 else:
Tim Peters3b769832003-01-28 03:51:36 +0000727 for arg in args:
728 save(arg)
729 write(INST + cls.__module__ + '\n' + cls.__name__ + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000730
Guido van Rossum3a41c612003-01-28 15:10:22 +0000731 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000732
733 try:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000734 getstate = obj.__getstate__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000735 except AttributeError:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000736 stuff = obj.__dict__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000737 else:
738 stuff = getstate()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000739 _keep_alive(stuff, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000740 save(stuff)
741 write(BUILD)
Tim Peters3b769832003-01-28 03:51:36 +0000742
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000743 dispatch[InstanceType] = save_inst
744
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000745 def save_global(self, obj, name=None, pack=struct.pack):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000746 write = self.write
747 memo = self.memo
748
Tim Petersc32d8242001-04-10 02:48:53 +0000749 if name is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000750 name = obj.__name__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000751
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000752 module = getattr(obj, "__module__", None)
753 if module is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000754 module = whichmodule(obj, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000755
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000756 try:
757 __import__(module)
758 mod = sys.modules[module]
759 klass = getattr(mod, name)
760 except (ImportError, KeyError, AttributeError):
761 raise PicklingError(
762 "Can't pickle %r: it's not found as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000763 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000764 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000765 if klass is not obj:
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000766 raise PicklingError(
767 "Can't pickle %r: it's not the same object as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000768 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000769
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000770 if self.proto >= 2:
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000771 code = _extension_registry.get((module, name))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000772 if code:
773 assert code > 0
774 if code <= 0xff:
775 write(EXT1 + chr(code))
776 elif code <= 0xffff:
Guido van Rossumba884f32003-01-29 20:14:23 +0000777 write("%c%c%c" % (EXT2, code&0xff, code>>8))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000778 else:
779 write(EXT4 + pack("<i", code))
780 return
781
Tim Peters518df0d2003-01-28 01:00:38 +0000782 write(GLOBAL + module + '\n' + name + '\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000783 self.memoize(obj)
Tim Peters3b769832003-01-28 03:51:36 +0000784
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000785 dispatch[ClassType] = save_global
786 dispatch[FunctionType] = save_global
787 dispatch[BuiltinFunctionType] = save_global
Tim Peters6d6c1a32001-08-02 04:15:00 +0000788 dispatch[TypeType] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000789
Guido van Rossum1be31752003-01-28 15:19:53 +0000790# Pickling helpers
Guido van Rossuma48061a1995-01-10 00:31:14 +0000791
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000792def _keep_alive(x, memo):
793 """Keeps a reference to the object x in the memo.
794
795 Because we remember objects by their id, we have
796 to assure that possibly temporary objects are kept
797 alive by referencing them.
798 We store a reference at the id of the memo, which should
799 normally not be used unless someone tries to deepcopy
800 the memo itself...
801 """
802 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000803 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000804 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000805 # aha, this is the first one :-)
806 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000807
808
Tim Petersc0c12b52003-01-29 00:56:17 +0000809# A cache for whichmodule(), mapping a function object to the name of
810# the module in which the function was found.
811
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000812classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000813
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000814def whichmodule(func, funcname):
815 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000816
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000817 Search sys.modules for the module.
818 Cache in classmap.
819 Return a module name.
Tim Petersc0c12b52003-01-29 00:56:17 +0000820 If the function cannot be found, return "__main__".
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000821 """
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000822 # Python functions should always get an __module__ from their globals.
823 mod = getattr(func, "__module__", None)
824 if mod is not None:
825 return mod
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000826 if func in classmap:
827 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000828
829 for name, module in sys.modules.items():
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000830 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000831 continue # skip dummy package entries
Jeremy Hyltoncc1fccb2003-02-06 16:23:01 +0000832 if name != '__main__' and getattr(module, funcname, None) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000833 break
834 else:
835 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000836 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000837 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000838
839
Guido van Rossum1be31752003-01-28 15:19:53 +0000840# Unpickling machinery
841
Guido van Rossuma48061a1995-01-10 00:31:14 +0000842class Unpickler:
843
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000844 def __init__(self, file):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000845 """This takes a file-like object for reading a pickle data stream.
846
Tim Peters5bd2a792003-02-01 16:45:06 +0000847 The protocol version of the pickle is detected automatically, so no
848 proto argument is needed.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000849
850 The file-like object must have two methods, a read() method that
851 takes an integer argument, and a readline() method that requires no
852 arguments. Both methods should return a string. Thus file-like
853 object can be a file object opened for reading, a StringIO object,
854 or any other custom object that meets this interface.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000855 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000856 self.readline = file.readline
857 self.read = file.read
858 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000859
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000860 def load(self):
Guido van Rossum3a41c612003-01-28 15:10:22 +0000861 """Read a pickled object representation from the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000862
Guido van Rossum3a41c612003-01-28 15:10:22 +0000863 Return the reconstituted object hierarchy specified in the file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000864 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000865 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000866 self.stack = []
867 self.append = self.stack.append
868 read = self.read
869 dispatch = self.dispatch
870 try:
871 while 1:
872 key = read(1)
873 dispatch[key](self)
Guido van Rossumff871742000-12-13 18:11:56 +0000874 except _Stop, stopinst:
875 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000876
Tim Petersc23d18a2003-01-28 01:41:51 +0000877 # Return largest index k such that self.stack[k] is self.mark.
878 # If the stack doesn't contain a mark, eventually raises IndexError.
879 # This could be sped by maintaining another stack, of indices at which
880 # the mark appears. For that matter, the latter stack would suffice,
881 # and we wouldn't need to push mark objects on self.stack at all.
882 # Doing so is probably a good thing, though, since if the pickle is
883 # corrupt (or hostile) we may get a clue from finding self.mark embedded
884 # in unpickled objects.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000885 def marker(self):
886 stack = self.stack
887 mark = self.mark
888 k = len(stack)-1
889 while stack[k] is not mark: k = k-1
890 return k
891
892 dispatch = {}
893
894 def load_eof(self):
895 raise EOFError
896 dispatch[''] = load_eof
897
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000898 def load_proto(self):
899 proto = ord(self.read(1))
900 if not 0 <= proto <= 2:
901 raise ValueError, "unsupported pickle protocol: %d" % proto
902 dispatch[PROTO] = load_proto
903
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000904 def load_persid(self):
905 pid = self.readline()[:-1]
906 self.append(self.persistent_load(pid))
907 dispatch[PERSID] = load_persid
908
909 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000910 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000911 self.append(self.persistent_load(pid))
912 dispatch[BINPERSID] = load_binpersid
913
914 def load_none(self):
915 self.append(None)
916 dispatch[NONE] = load_none
917
Guido van Rossum7d97d312003-01-28 04:25:27 +0000918 def load_false(self):
919 self.append(False)
920 dispatch[NEWFALSE] = load_false
921
922 def load_true(self):
923 self.append(True)
924 dispatch[NEWTRUE] = load_true
925
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000926 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000927 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000928 if data == FALSE[1:]:
929 val = False
930 elif data == TRUE[1:]:
931 val = True
932 else:
933 try:
934 val = int(data)
935 except ValueError:
936 val = long(data)
937 self.append(val)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000938 dispatch[INT] = load_int
939
940 def load_binint(self):
941 self.append(mloads('i' + self.read(4)))
942 dispatch[BININT] = load_binint
943
944 def load_binint1(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000945 self.append(ord(self.read(1)))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000946 dispatch[BININT1] = load_binint1
947
948 def load_binint2(self):
949 self.append(mloads('i' + self.read(2) + '\000\000'))
950 dispatch[BININT2] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000951
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000952 def load_long(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000953 self.append(long(self.readline()[:-1], 0))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000954 dispatch[LONG] = load_long
955
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000956 def load_long1(self):
957 n = ord(self.read(1))
958 bytes = self.read(n)
Tim Petersee1a53c2003-02-02 02:57:53 +0000959 self.append(decode_long(bytes))
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000960 dispatch[LONG1] = load_long1
961
962 def load_long4(self):
963 n = mloads('i' + self.read(4))
964 bytes = self.read(n)
Tim Petersee1a53c2003-02-02 02:57:53 +0000965 self.append(decode_long(bytes))
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000966 dispatch[LONG4] = load_long4
967
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000968 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000969 self.append(float(self.readline()[:-1]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000970 dispatch[FLOAT] = load_float
971
Guido van Rossumd3703791998-10-22 20:15:36 +0000972 def load_binfloat(self, unpack=struct.unpack):
973 self.append(unpack('>d', self.read(8))[0])
974 dispatch[BINFLOAT] = load_binfloat
975
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000976 def load_string(self):
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000977 rep = self.readline()[:-1]
Tim Petersad5a7712003-01-28 16:23:33 +0000978 for q in "\"'": # double or single quote
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000979 if rep.startswith(q):
980 if not rep.endswith(q):
981 raise ValueError, "insecure string pickle"
982 rep = rep[len(q):-len(q)]
983 break
984 else:
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000985 raise ValueError, "insecure string pickle"
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000986 self.append(rep.decode("string-escape"))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000987 dispatch[STRING] = load_string
988
989 def load_binstring(self):
990 len = mloads('i' + self.read(4))
991 self.append(self.read(len))
992 dispatch[BINSTRING] = load_binstring
993
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000994 def load_unicode(self):
995 self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
996 dispatch[UNICODE] = load_unicode
997
998 def load_binunicode(self):
999 len = mloads('i' + self.read(4))
1000 self.append(unicode(self.read(len),'utf-8'))
1001 dispatch[BINUNICODE] = load_binunicode
1002
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001003 def load_short_binstring(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001004 len = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001005 self.append(self.read(len))
1006 dispatch[SHORT_BINSTRING] = load_short_binstring
1007
1008 def load_tuple(self):
1009 k = self.marker()
1010 self.stack[k:] = [tuple(self.stack[k+1:])]
1011 dispatch[TUPLE] = load_tuple
1012
1013 def load_empty_tuple(self):
1014 self.stack.append(())
1015 dispatch[EMPTY_TUPLE] = load_empty_tuple
1016
Guido van Rossum44f0ea52003-01-28 04:14:51 +00001017 def load_tuple1(self):
1018 self.stack[-1] = (self.stack[-1],)
1019 dispatch[TUPLE1] = load_tuple1
1020
1021 def load_tuple2(self):
1022 self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
1023 dispatch[TUPLE2] = load_tuple2
1024
1025 def load_tuple3(self):
1026 self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
1027 dispatch[TUPLE3] = load_tuple3
1028
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001029 def load_empty_list(self):
1030 self.stack.append([])
1031 dispatch[EMPTY_LIST] = load_empty_list
1032
1033 def load_empty_dictionary(self):
1034 self.stack.append({})
1035 dispatch[EMPTY_DICT] = load_empty_dictionary
1036
1037 def load_list(self):
1038 k = self.marker()
1039 self.stack[k:] = [self.stack[k+1:]]
1040 dispatch[LIST] = load_list
1041
1042 def load_dict(self):
1043 k = self.marker()
1044 d = {}
1045 items = self.stack[k+1:]
1046 for i in range(0, len(items), 2):
1047 key = items[i]
1048 value = items[i+1]
1049 d[key] = value
1050 self.stack[k:] = [d]
1051 dispatch[DICT] = load_dict
1052
Tim Petersd01c1e92003-01-30 15:41:46 +00001053 # INST and OBJ differ only in how they get a class object. It's not
1054 # only sensible to do the rest in a common routine, the two routines
1055 # previously diverged and grew different bugs.
1056 # klass is the class to instantiate, and k points to the topmost mark
1057 # object, following which are the arguments for klass.__init__.
1058 def _instantiate(self, klass, k):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001059 args = tuple(self.stack[k+1:])
1060 del self.stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001061 instantiated = 0
Tim Petersd01c1e92003-01-30 15:41:46 +00001062 if (not args and
1063 type(klass) is ClassType and
1064 not hasattr(klass, "__getinitargs__")):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001065 try:
1066 value = _EmptyClass()
1067 value.__class__ = klass
Guido van Rossumb19e2a31998-04-13 18:08:45 +00001068 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001069 except RuntimeError:
1070 # In restricted execution, assignment to inst.__class__ is
1071 # prohibited
1072 pass
1073 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +00001074 try:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001075 value = klass(*args)
Guido van Rossum743d17e1998-09-15 20:25:57 +00001076 except TypeError, err:
1077 raise TypeError, "in constructor for %s: %s" % (
1078 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001079 self.append(value)
Tim Petersd01c1e92003-01-30 15:41:46 +00001080
1081 def load_inst(self):
1082 module = self.readline()[:-1]
1083 name = self.readline()[:-1]
1084 klass = self.find_class(module, name)
1085 self._instantiate(klass, self.marker())
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001086 dispatch[INST] = load_inst
1087
1088 def load_obj(self):
Tim Petersd01c1e92003-01-30 15:41:46 +00001089 # Stack is ... markobject classobject arg1 arg2 ...
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001090 k = self.marker()
Tim Petersd01c1e92003-01-30 15:41:46 +00001091 klass = self.stack.pop(k+1)
1092 self._instantiate(klass, k)
Tim Peters2344fae2001-01-15 00:50:52 +00001093 dispatch[OBJ] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001094
Guido van Rossum3a41c612003-01-28 15:10:22 +00001095 def load_newobj(self):
1096 args = self.stack.pop()
1097 cls = self.stack[-1]
1098 obj = cls.__new__(cls, *args)
Guido van Rossum533dbcf2003-01-28 17:55:05 +00001099 self.stack[-1] = obj
Guido van Rossum3a41c612003-01-28 15:10:22 +00001100 dispatch[NEWOBJ] = load_newobj
1101
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001102 def load_global(self):
1103 module = self.readline()[:-1]
1104 name = self.readline()[:-1]
1105 klass = self.find_class(module, name)
1106 self.append(klass)
1107 dispatch[GLOBAL] = load_global
1108
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001109 def load_ext1(self):
1110 code = ord(self.read(1))
1111 self.get_extension(code)
1112 dispatch[EXT1] = load_ext1
1113
1114 def load_ext2(self):
1115 code = mloads('i' + self.read(2) + '\000\000')
1116 self.get_extension(code)
1117 dispatch[EXT2] = load_ext2
1118
1119 def load_ext4(self):
1120 code = mloads('i' + self.read(4))
1121 self.get_extension(code)
1122 dispatch[EXT4] = load_ext4
1123
1124 def get_extension(self, code):
1125 nil = []
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001126 obj = _extension_cache.get(code, nil)
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001127 if obj is not nil:
1128 self.append(obj)
1129 return
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001130 key = _inverted_registry.get(code)
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001131 if not key:
1132 raise ValueError("unregistered extension code %d" % code)
1133 obj = self.find_class(*key)
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001134 _extension_cache[code] = obj
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001135 self.append(obj)
1136
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001137 def find_class(self, module, name):
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001138 # Subclasses may override this
Barry Warsawbf4d9592001-11-15 23:42:58 +00001139 __import__(module)
1140 mod = sys.modules[module]
1141 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001142 return klass
1143
1144 def load_reduce(self):
1145 stack = self.stack
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001146 args = stack.pop()
1147 func = stack[-1]
1148 if args is None:
Guido van Rossumbc64e222003-01-28 16:34:19 +00001149 # A hack for Jim Fulton's ExtensionClass, now deprecated
1150 warnings.warn("__basicnew__ special case is deprecated",
Tim Peters8ac14952002-05-23 15:15:30 +00001151 DeprecationWarning)
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001152 value = func.__basicnew__()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001153 else:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001154 value = func(*args)
1155 stack[-1] = value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001156 dispatch[REDUCE] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +00001157
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001158 def load_pop(self):
1159 del self.stack[-1]
1160 dispatch[POP] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +00001161
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001162 def load_pop_mark(self):
1163 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001164 del self.stack[k:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001165 dispatch[POP_MARK] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001166
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001167 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +00001168 self.append(self.stack[-1])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001169 dispatch[DUP] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +00001170
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001171 def load_get(self):
1172 self.append(self.memo[self.readline()[:-1]])
1173 dispatch[GET] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +00001174
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001175 def load_binget(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001176 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001177 self.append(self.memo[`i`])
1178 dispatch[BINGET] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001179
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001180 def load_long_binget(self):
1181 i = mloads('i' + self.read(4))
1182 self.append(self.memo[`i`])
1183 dispatch[LONG_BINGET] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001184
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001185 def load_put(self):
1186 self.memo[self.readline()[:-1]] = self.stack[-1]
1187 dispatch[PUT] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +00001188
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001189 def load_binput(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001190 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001191 self.memo[`i`] = self.stack[-1]
1192 dispatch[BINPUT] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001193
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001194 def load_long_binput(self):
1195 i = mloads('i' + self.read(4))
1196 self.memo[`i`] = self.stack[-1]
1197 dispatch[LONG_BINPUT] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001198
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001199 def load_append(self):
1200 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001201 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001202 list = stack[-1]
1203 list.append(value)
1204 dispatch[APPEND] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +00001205
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001206 def load_appends(self):
1207 stack = self.stack
1208 mark = self.marker()
1209 list = stack[mark - 1]
Tim Peters209ad952003-01-28 01:44:45 +00001210 list.extend(stack[mark + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001211 del stack[mark:]
1212 dispatch[APPENDS] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +00001213
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001214 def load_setitem(self):
1215 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001216 value = stack.pop()
1217 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001218 dict = stack[-1]
1219 dict[key] = value
1220 dispatch[SETITEM] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001221
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001222 def load_setitems(self):
1223 stack = self.stack
1224 mark = self.marker()
1225 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001226 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001227 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001228
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001229 del stack[mark:]
1230 dispatch[SETITEMS] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001231
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001232 def load_build(self):
1233 stack = self.stack
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001234 state = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001235 inst = stack[-1]
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001236 setstate = getattr(inst, "__setstate__", None)
1237 if setstate:
1238 setstate(state)
1239 return
1240 slotstate = None
1241 if isinstance(state, tuple) and len(state) == 2:
1242 state, slotstate = state
1243 if state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001244 try:
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001245 inst.__dict__.update(state)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001246 except RuntimeError:
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001247 # XXX In restricted execution, the instance's __dict__
1248 # is not accessible. Use the old way of unpickling
1249 # the instance variables. This is a semantic
1250 # difference when unpickling in restricted
1251 # vs. unrestricted modes.
1252 for k, v in state.items():
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001253 setattr(inst, k, v)
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001254 if slotstate:
1255 for k, v in slotstate.items():
1256 setattr(inst, k, v)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001257 dispatch[BUILD] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001258
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001259 def load_mark(self):
1260 self.append(self.mark)
1261 dispatch[MARK] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001262
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001263 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001264 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001265 raise _Stop(value)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001266 dispatch[STOP] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001267
Guido van Rossume467be61997-12-05 19:42:42 +00001268# Helper class for load_inst/load_obj
1269
1270class _EmptyClass:
1271 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001272
Tim Peters91149822003-01-31 03:43:58 +00001273# Encode/decode longs in linear time.
1274
1275import binascii as _binascii
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001276
1277def encode_long(x):
Tim Peters91149822003-01-31 03:43:58 +00001278 r"""Encode a long to a two's complement little-endian binary string.
Tim Peters4b23f2b2003-01-31 16:43:39 +00001279 Note that 0L is a special case, returning an empty string, to save a
1280 byte in the LONG1 pickling context.
1281
1282 >>> encode_long(0L)
1283 ''
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001284 >>> encode_long(255L)
1285 '\xff\x00'
1286 >>> encode_long(32767L)
1287 '\xff\x7f'
1288 >>> encode_long(-256L)
1289 '\x00\xff'
1290 >>> encode_long(-32768L)
1291 '\x00\x80'
1292 >>> encode_long(-128L)
1293 '\x80'
1294 >>> encode_long(127L)
1295 '\x7f'
1296 >>>
1297 """
Tim Peters91149822003-01-31 03:43:58 +00001298
1299 if x == 0:
Tim Peters4b23f2b2003-01-31 16:43:39 +00001300 return ''
Tim Peters91149822003-01-31 03:43:58 +00001301 if x > 0:
1302 ashex = hex(x)
1303 assert ashex.startswith("0x")
1304 njunkchars = 2 + ashex.endswith('L')
1305 nibbles = len(ashex) - njunkchars
1306 if nibbles & 1:
1307 # need an even # of nibbles for unhexlify
1308 ashex = "0x0" + ashex[2:]
Tim Peters4b23f2b2003-01-31 16:43:39 +00001309 elif int(ashex[2], 16) >= 8:
Tim Peters91149822003-01-31 03:43:58 +00001310 # "looks negative", so need a byte of sign bits
1311 ashex = "0x00" + ashex[2:]
1312 else:
1313 # Build the 256's-complement: (1L << nbytes) + x. The trick is
1314 # to find the number of bytes in linear time (although that should
1315 # really be a constant-time task).
1316 ashex = hex(-x)
1317 assert ashex.startswith("0x")
1318 njunkchars = 2 + ashex.endswith('L')
1319 nibbles = len(ashex) - njunkchars
1320 if nibbles & 1:
Tim Petersee1a53c2003-02-02 02:57:53 +00001321 # Extend to a full byte.
Tim Peters91149822003-01-31 03:43:58 +00001322 nibbles += 1
Tim Peters4b23f2b2003-01-31 16:43:39 +00001323 nbits = nibbles * 4
1324 x += 1L << nbits
Tim Peters91149822003-01-31 03:43:58 +00001325 assert x > 0
1326 ashex = hex(x)
Tim Petersee1a53c2003-02-02 02:57:53 +00001327 njunkchars = 2 + ashex.endswith('L')
1328 newnibbles = len(ashex) - njunkchars
1329 if newnibbles < nibbles:
1330 ashex = "0x" + "0" * (nibbles - newnibbles) + ashex[2:]
1331 if int(ashex[2], 16) < 8:
Tim Peters91149822003-01-31 03:43:58 +00001332 # "looks positive", so need a byte of sign bits
Tim Petersee1a53c2003-02-02 02:57:53 +00001333 ashex = "0xff" + ashex[2:]
Tim Peters91149822003-01-31 03:43:58 +00001334
1335 if ashex.endswith('L'):
1336 ashex = ashex[2:-1]
1337 else:
1338 ashex = ashex[2:]
Tim Petersee1a53c2003-02-02 02:57:53 +00001339 assert len(ashex) & 1 == 0, (x, ashex)
Tim Peters91149822003-01-31 03:43:58 +00001340 binary = _binascii.unhexlify(ashex)
1341 return binary[::-1]
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001342
1343def decode_long(data):
1344 r"""Decode a long from a two's complement little-endian binary string.
Tim Peters4b23f2b2003-01-31 16:43:39 +00001345
1346 >>> decode_long('')
1347 0L
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001348 >>> decode_long("\xff\x00")
1349 255L
1350 >>> decode_long("\xff\x7f")
1351 32767L
1352 >>> decode_long("\x00\xff")
1353 -256L
1354 >>> decode_long("\x00\x80")
1355 -32768L
1356 >>> decode_long("\x80")
1357 -128L
1358 >>> decode_long("\x7f")
1359 127L
1360 """
Tim Peters91149822003-01-31 03:43:58 +00001361
Tim Peters4b23f2b2003-01-31 16:43:39 +00001362 nbytes = len(data)
1363 if nbytes == 0:
1364 return 0L
Tim Peters91149822003-01-31 03:43:58 +00001365 ashex = _binascii.hexlify(data[::-1])
Tim Petersbf2674b2003-02-02 07:51:32 +00001366 n = long(ashex, 16) # quadratic time before Python 2.3; linear now
Tim Peters91149822003-01-31 03:43:58 +00001367 if data[-1] >= '\x80':
Tim Peters4b23f2b2003-01-31 16:43:39 +00001368 n -= 1L << (nbytes * 8)
Tim Peters91149822003-01-31 03:43:58 +00001369 return n
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001370
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001371# Shorthands
1372
Jeremy Hyltonabe2c622001-10-15 21:29:28 +00001373try:
1374 from cStringIO import StringIO
1375except ImportError:
1376 from StringIO import StringIO
Guido van Rossumc7c5e691996-07-22 22:26:07 +00001377
Guido van Rossumcf117b02003-02-09 17:19:41 +00001378def dump(obj, file, protocol=None, bin=None):
1379 Pickler(file, protocol, bin).dump(obj)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001380
Guido van Rossumcf117b02003-02-09 17:19:41 +00001381def dumps(obj, protocol=None, bin=None):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001382 file = StringIO()
Guido van Rossumcf117b02003-02-09 17:19:41 +00001383 Pickler(file, protocol, bin).dump(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001384 return file.getvalue()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001385
1386def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001387 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001388
1389def loads(str):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001390 file = StringIO(str)
1391 return Unpickler(file).load()
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001392
1393# Doctest
1394
1395def _test():
1396 import doctest
1397 return doctest.testmod()
1398
1399if __name__ == "__main__":
1400 _test()