blob: 2b01b02ed24942e40f9c6e2bc2fa0bb0cb047769 [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 Rossum443ada42003-02-18 22:49:10 +000030from copy_reg import dispatch_table
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 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
Tim Petersc0c12b52003-01-29 00:56:17 +000040# These are purely informational; no code uses these.
Guido van Rossumf29d3d62003-01-27 22:47:53 +000041format_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
Tim Peters8587b3c2003-02-13 15:44:41 +000049# Keep in synch with cPickle. This is the highest protocol number we
50# know how to read.
51HIGHEST_PROTOCOL = 2
52
Guido van Rossume0b90422003-01-28 03:17:21 +000053# Why use struct.pack() for pickling but marshal.loads() for
Tim Petersc0c12b52003-01-29 00:56:17 +000054# unpickling? struct.pack() is 40% faster than marshal.dumps(), but
Guido van Rossume0b90422003-01-28 03:17:21 +000055# marshal.loads() is twice as fast as struct.unpack()!
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000056mloads = marshal.loads
Guido van Rossum0c891ce1995-03-14 15:09:05 +000057
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000058class PickleError(Exception):
Neal Norwitzefbb67b2002-05-30 12:12:04 +000059 """A common base class for the other pickling exceptions."""
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000060 pass
61
62class PicklingError(PickleError):
63 """This exception is raised when an unpicklable object is passed to the
64 dump() method.
65
66 """
67 pass
68
69class UnpicklingError(PickleError):
70 """This exception is raised when there is a problem unpickling an object,
71 such as a security violation.
72
73 Note that other exceptions may also be raised during unpickling, including
74 (but not necessarily limited to) AttributeError, EOFError, ImportError,
75 and IndexError.
76
77 """
78 pass
Guido van Rossum7849da81995-03-09 14:08:35 +000079
Tim Petersc0c12b52003-01-29 00:56:17 +000080# An instance of _Stop is raised by Unpickler.load_stop() in response to
81# the STOP opcode, passing the object that is the result of unpickling.
Guido van Rossumff871742000-12-13 18:11:56 +000082class _Stop(Exception):
83 def __init__(self, value):
84 self.value = value
85
Guido van Rossum533dbcf2003-01-28 17:55:05 +000086# Jython has PyStringMap; it's a dict subclass with string keys
Jeremy Hylton2b9d0291998-05-27 22:38:22 +000087try:
88 from org.python.core import PyStringMap
89except ImportError:
90 PyStringMap = None
91
Guido van Rossum533dbcf2003-01-28 17:55:05 +000092# UnicodeType may or may not be exported (normally imported from types)
Guido van Rossumdbb718f2001-09-21 19:22:34 +000093try:
94 UnicodeType
95except NameError:
96 UnicodeType = None
97
Tim Peters22a449a2003-01-27 20:16:36 +000098# Pickle opcodes. See pickletools.py for extensive docs. The listing
99# here is in kind-of alphabetical order of 1-character pickle code.
100# pickletools groups them by purpose.
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000101
Tim Peters22a449a2003-01-27 20:16:36 +0000102MARK = '(' # push special markobject on stack
103STOP = '.' # every pickle ends with STOP
104POP = '0' # discard topmost stack item
105POP_MARK = '1' # discard stack top through topmost markobject
106DUP = '2' # duplicate top stack item
107FLOAT = 'F' # push float object; decimal string argument
108INT = 'I' # push integer or bool; decimal string argument
109BININT = 'J' # push four-byte signed int
110BININT1 = 'K' # push 1-byte unsigned int
111LONG = 'L' # push long; decimal string argument
112BININT2 = 'M' # push 2-byte unsigned int
113NONE = 'N' # push None
114PERSID = 'P' # push persistent object; id is taken from string arg
115BINPERSID = 'Q' # " " " ; " " " " stack
116REDUCE = 'R' # apply callable to argtuple, both on stack
117STRING = 'S' # push string; NL-terminated string argument
118BINSTRING = 'T' # push string; counted binary string argument
119SHORT_BINSTRING = 'U' # " " ; " " " " < 256 bytes
120UNICODE = 'V' # push Unicode string; raw-unicode-escaped'd argument
121BINUNICODE = 'X' # " " " ; counted UTF-8 string argument
122APPEND = 'a' # append stack top to list below it
123BUILD = 'b' # call __setstate__ or __dict__.update()
124GLOBAL = 'c' # push self.find_class(modname, name); 2 string args
125DICT = 'd' # build a dict from stack items
126EMPTY_DICT = '}' # push empty dict
127APPENDS = 'e' # extend list on stack by topmost stack slice
128GET = 'g' # push item from memo on stack; index is string arg
129BINGET = 'h' # " " " " " " ; " " 1-byte arg
130INST = 'i' # build & push class instance
131LONG_BINGET = 'j' # push item from memo on stack; index is 4-byte arg
132LIST = 'l' # build list from topmost stack items
133EMPTY_LIST = ']' # push empty list
134OBJ = 'o' # build & push class instance
135PUT = 'p' # store stack top in memo; index is string arg
136BINPUT = 'q' # " " " " " ; " " 1-byte arg
137LONG_BINPUT = 'r' # " " " " " ; " " 4-byte arg
138SETITEM = 's' # add key+value pair to dict
139TUPLE = 't' # build tuple from topmost stack items
140EMPTY_TUPLE = ')' # push empty tuple
141SETITEMS = 'u' # modify dict by adding topmost key+value pairs
142BINFLOAT = 'G' # push float; arg is 8-byte float encoding
143
144TRUE = 'I01\n' # not an opcode; see INT docs in pickletools.py
145FALSE = 'I00\n' # not an opcode; see INT docs in pickletools.py
Guido van Rossum77f6a652002-04-03 22:41:51 +0000146
Guido van Rossum586c9e82003-01-29 06:16:12 +0000147# Protocol 2
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000148
Tim Peterse1054782003-01-28 00:22:12 +0000149PROTO = '\x80' # identify pickle protocol
150NEWOBJ = '\x81' # build object by applying cls.__new__ to argtuple
151EXT1 = '\x82' # push object from extension registry; 1-byte index
152EXT2 = '\x83' # ditto, but 2-byte index
153EXT4 = '\x84' # ditto, but 4-byte index
154TUPLE1 = '\x85' # build 1-tuple from stack top
155TUPLE2 = '\x86' # build 2-tuple from two topmost stack items
156TUPLE3 = '\x87' # build 3-tuple from three topmost stack items
157NEWTRUE = '\x88' # push True
158NEWFALSE = '\x89' # push False
159LONG1 = '\x8a' # push long from < 256 bytes
160LONG4 = '\x8b' # push really big long
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000161
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000162_tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3]
163
Guido van Rossuma48061a1995-01-10 00:31:14 +0000164
Skip Montanaro23bafc62001-02-18 03:10:09 +0000165__all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
166
Guido van Rossum1be31752003-01-28 15:19:53 +0000167
168# Pickling machinery
169
Guido van Rossuma48061a1995-01-10 00:31:14 +0000170class Pickler:
171
Raymond Hettinger3489cad2004-12-05 05:20:42 +0000172 def __init__(self, file, protocol=None):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000173 """This takes a file-like object for writing a pickle data stream.
174
Guido van Rossumcf117b02003-02-09 17:19:41 +0000175 The optional protocol argument tells the pickler to use the
176 given protocol; supported protocols are 0, 1, 2. The default
Guido van Rossum7eff63a2003-01-31 19:42:31 +0000177 protocol is 0, to be backwards compatible. (Protocol 0 is the
178 only protocol that can be written to a file opened in text
Tim Peters5bd2a792003-02-01 16:45:06 +0000179 mode and read back successfully. When using a protocol higher
180 than 0, make sure the file is opened in binary mode, both when
181 pickling and unpickling.)
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000182
183 Protocol 1 is more efficient than protocol 0; protocol 2 is
Guido van Rossum7eff63a2003-01-31 19:42:31 +0000184 more efficient than protocol 1.
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000185
Guido van Rossum7eff63a2003-01-31 19:42:31 +0000186 Specifying a negative protocol version selects the highest
Tim Peters5bd2a792003-02-01 16:45:06 +0000187 protocol version supported. The higher the protocol used, the
188 more recent the version of Python needed to read the pickle
189 produced.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000190
191 The file parameter must have a write() method that accepts a single
192 string argument. It can thus be an open file object, a StringIO
193 object, or any other custom object that meets this interface.
194
195 """
Guido van Rossumcf117b02003-02-09 17:19:41 +0000196 if protocol is None:
197 protocol = 0
198 if protocol < 0:
Tim Peters8587b3c2003-02-13 15:44:41 +0000199 protocol = HIGHEST_PROTOCOL
200 elif not 0 <= protocol <= HIGHEST_PROTOCOL:
201 raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000202 self.write = file.write
203 self.memo = {}
Guido van Rossumcf117b02003-02-09 17:19:41 +0000204 self.proto = int(protocol)
205 self.bin = protocol >= 1
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000206 self.fast = 0
Guido van Rossuma48061a1995-01-10 00:31:14 +0000207
Fred Drake7f781c92002-05-01 20:33:53 +0000208 def clear_memo(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000209 """Clears the pickler's "memo".
210
211 The memo is the data structure that remembers which objects the
Tim Petersb377f8a2003-01-28 00:23:36 +0000212 pickler has already seen, so that shared or recursive objects are
213 pickled by reference and not by value. This method is useful when
214 re-using picklers.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000215
216 """
Fred Drake7f781c92002-05-01 20:33:53 +0000217 self.memo.clear()
218
Guido van Rossum3a41c612003-01-28 15:10:22 +0000219 def dump(self, obj):
Tim Peters5bd2a792003-02-01 16:45:06 +0000220 """Write a pickled representation of obj to the open file."""
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000221 if self.proto >= 2:
222 self.write(PROTO + chr(self.proto))
Guido van Rossum3a41c612003-01-28 15:10:22 +0000223 self.save(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000224 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000225
Jeremy Hylton3422c992003-01-24 19:29:52 +0000226 def memoize(self, obj):
227 """Store an object in the memo."""
228
Tim Peterse46b73f2003-01-27 21:22:10 +0000229 # The Pickler memo is a dictionary mapping object ids to 2-tuples
230 # that contain the Unpickler memo key and the object being memoized.
231 # The memo key is written to the pickle and will become
Jeremy Hylton3422c992003-01-24 19:29:52 +0000232 # the key in the Unpickler's memo. The object is stored in the
Tim Peterse46b73f2003-01-27 21:22:10 +0000233 # Pickler memo so that transient objects are kept alive during
234 # pickling.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000235
Tim Peterse46b73f2003-01-27 21:22:10 +0000236 # The use of the Unpickler memo length as the memo key is just a
237 # convention. The only requirement is that the memo values be unique.
238 # But there appears no advantage to any other scheme, and this
Tim Peterscbd0a322003-01-28 00:24:43 +0000239 # scheme allows the Unpickler memo to be implemented as a plain (but
Tim Peterse46b73f2003-01-27 21:22:10 +0000240 # growable) array, indexed by memo key.
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000241 if self.fast:
242 return
Guido van Rossum9b40e802003-01-30 06:37:41 +0000243 assert id(obj) not in self.memo
Jeremy Hylton3422c992003-01-24 19:29:52 +0000244 memo_len = len(self.memo)
245 self.write(self.put(memo_len))
Tim Peters518df0d2003-01-28 01:00:38 +0000246 self.memo[id(obj)] = memo_len, obj
Jeremy Hylton3422c992003-01-24 19:29:52 +0000247
Tim Petersbb38e302003-01-27 21:25:41 +0000248 # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000249 def put(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000250 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000251 if i < 256:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000252 return BINPUT + chr(i)
253 else:
254 return LONG_BINPUT + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000255
Walter Dörwald70a6b492004-02-12 17:35:32 +0000256 return PUT + repr(i) + '\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000257
Tim Petersbb38e302003-01-27 21:25:41 +0000258 # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000259 def get(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000260 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000261 if i < 256:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000262 return BINGET + chr(i)
263 else:
264 return LONG_BINGET + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000265
Walter Dörwald70a6b492004-02-12 17:35:32 +0000266 return GET + repr(i) + '\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000267
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000268 def save(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000269 # Check for persistent id (defined by a subclass)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000270 pid = self.persistent_id(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000271 if pid:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000272 self.save_pers(pid)
273 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000274
Guido van Rossumbc64e222003-01-28 16:34:19 +0000275 # Check the memo
276 x = self.memo.get(id(obj))
277 if x:
278 self.write(self.get(x[0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000279 return
280
Guido van Rossumbc64e222003-01-28 16:34:19 +0000281 # Check the type dispatch table
Guido van Rossum3a41c612003-01-28 15:10:22 +0000282 t = type(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000283 f = self.dispatch.get(t)
284 if f:
285 f(self, obj) # Call unbound method with explicit self
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000286 return
287
Guido van Rossumbc64e222003-01-28 16:34:19 +0000288 # Check for a class with a custom metaclass; treat as regular class
Tim Petersb32a8312003-01-28 00:48:09 +0000289 try:
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000290 issc = issubclass(t, TypeType)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000291 except TypeError: # t is not a class (old Boost; see SF #502085)
Tim Petersb32a8312003-01-28 00:48:09 +0000292 issc = 0
293 if issc:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000294 self.save_global(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000295 return
296
Guido van Rossumbc64e222003-01-28 16:34:19 +0000297 # Check copy_reg.dispatch_table
298 reduce = dispatch_table.get(t)
Guido van Rossumc53f0092003-02-18 22:05:12 +0000299 if reduce:
300 rv = reduce(obj)
301 else:
302 # Check for a __reduce_ex__ method, fall back to __reduce__
303 reduce = getattr(obj, "__reduce_ex__", None)
304 if reduce:
305 rv = reduce(self.proto)
306 else:
307 reduce = getattr(obj, "__reduce__", None)
308 if reduce:
309 rv = reduce()
310 else:
311 raise PicklingError("Can't pickle %r object: %r" %
312 (t.__name__, obj))
Tim Petersb32a8312003-01-28 00:48:09 +0000313
Guido van Rossumbc64e222003-01-28 16:34:19 +0000314 # Check for string returned by reduce(), meaning "save as global"
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000315 if type(rv) is StringType:
Guido van Rossumbc64e222003-01-28 16:34:19 +0000316 self.save_global(obj, rv)
Tim Petersb32a8312003-01-28 00:48:09 +0000317 return
318
Guido van Rossumbc64e222003-01-28 16:34:19 +0000319 # Assert that reduce() returned a tuple
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000320 if type(rv) is not TupleType:
Guido van Rossumbc64e222003-01-28 16:34:19 +0000321 raise PicklingError("%s must return string or tuple" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000322
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000323 # Assert that it returned an appropriately sized tuple
Guido van Rossumbc64e222003-01-28 16:34:19 +0000324 l = len(rv)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000325 if not (2 <= l <= 5):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000326 raise PicklingError("Tuple returned by %s must have "
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000327 "two to five elements" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000328
Guido van Rossumbc64e222003-01-28 16:34:19 +0000329 # Save the reduce() output and finally memoize the object
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000330 self.save_reduce(obj=obj, *rv)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000331
Guido van Rossum3a41c612003-01-28 15:10:22 +0000332 def persistent_id(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000333 # This exists so a subclass can override it
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000334 return None
335
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000336 def save_pers(self, pid):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000337 # Save a persistent id reference
Tim Petersbd1cdb92003-01-28 01:03:10 +0000338 if self.bin:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000339 self.save(pid)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000340 self.write(BINPERSID)
Tim Petersbd1cdb92003-01-28 01:03:10 +0000341 else:
342 self.write(PERSID + str(pid) + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000343
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000344 def save_reduce(self, func, args, state=None,
345 listitems=None, dictitems=None, obj=None):
Jeremy Hyltone3a565e2003-06-29 16:59:59 +0000346 # This API is called by some subclasses
Guido van Rossumbc64e222003-01-28 16:34:19 +0000347
348 # Assert that args is a tuple or None
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000349 if not isinstance(args, TupleType):
Raymond Hettingera6b45cc2004-12-07 07:05:57 +0000350 raise PicklingError("args from reduce() should be a tuple")
Guido van Rossumbc64e222003-01-28 16:34:19 +0000351
352 # Assert that func is callable
353 if not callable(func):
354 raise PicklingError("func from reduce should be callable")
355
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000356 save = self.save
Guido van Rossumbc64e222003-01-28 16:34:19 +0000357 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000358
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000359 # Protocol 2 special case: if func's name is __newobj__, use NEWOBJ
360 if self.proto >= 2 and getattr(func, "__name__", "") == "__newobj__":
361 # A __reduce__ implementation can direct protocol 2 to
362 # use the more efficient NEWOBJ opcode, while still
363 # allowing protocol 0 and 1 to work normally. For this to
364 # work, the function returned by __reduce__ should be
365 # called __newobj__, and its first argument should be a
366 # new-style class. The implementation for __newobj__
367 # should be as follows, although pickle has no way to
368 # verify this:
369 #
370 # def __newobj__(cls, *args):
371 # return cls.__new__(cls, *args)
372 #
373 # Protocols 0 and 1 will pickle a reference to __newobj__,
374 # while protocol 2 (and above) will pickle a reference to
375 # cls, the remaining args tuple, and the NEWOBJ code,
376 # which calls cls.__new__(cls, *args) at unpickling time
377 # (see load_newobj below). If __reduce__ returns a
378 # three-tuple, the state from the third tuple item will be
379 # pickled regardless of the protocol, calling __setstate__
380 # at unpickling time (see load_build below).
381 #
382 # Note that no standard __newobj__ implementation exists;
383 # you have to provide your own. This is to enforce
384 # compatibility with Python 2.2 (pickles written using
385 # protocol 0 or 1 in Python 2.3 should be unpicklable by
386 # Python 2.2).
387 cls = args[0]
388 if not hasattr(cls, "__new__"):
389 raise PicklingError(
390 "args[0] from __newobj__ args has no __new__")
Guido van Rossumf7f45172003-01-31 17:17:49 +0000391 if obj is not None and cls is not obj.__class__:
392 raise PicklingError(
393 "args[0] from __newobj__ args has the wrong class")
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000394 args = args[1:]
395 save(cls)
396 save(args)
397 write(NEWOBJ)
398 else:
399 save(func)
400 save(args)
401 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000402
Guido van Rossumf7f45172003-01-31 17:17:49 +0000403 if obj is not None:
404 self.memoize(obj)
405
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000406 # More new special cases (that work with older protocols as
407 # well): when __reduce__ returns a tuple with 4 or 5 items,
408 # the 4th and 5th item should be iterators that provide list
409 # items and dict items (as (key, value) tuples), or None.
410
411 if listitems is not None:
412 self._batch_appends(listitems)
413
414 if dictitems is not None:
415 self._batch_setitems(dictitems)
416
Tim Petersc32d8242001-04-10 02:48:53 +0000417 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000418 save(state)
419 write(BUILD)
420
Guido van Rossumbc64e222003-01-28 16:34:19 +0000421 # Methods below this point are dispatched through the dispatch table
422
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000423 dispatch = {}
424
Guido van Rossum3a41c612003-01-28 15:10:22 +0000425 def save_none(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000426 self.write(NONE)
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000427 dispatch[NoneType] = save_none
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000428
Guido van Rossum3a41c612003-01-28 15:10:22 +0000429 def save_bool(self, obj):
Guido van Rossum7d97d312003-01-28 04:25:27 +0000430 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000431 self.write(obj and NEWTRUE or NEWFALSE)
Guido van Rossum7d97d312003-01-28 04:25:27 +0000432 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000433 self.write(obj and TRUE or FALSE)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000434 dispatch[bool] = save_bool
435
Guido van Rossum3a41c612003-01-28 15:10:22 +0000436 def save_int(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000437 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000438 # If the int is small enough to fit in a signed 4-byte 2's-comp
439 # format, we can store it more efficiently than the general
440 # case.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000441 # First one- and two-byte unsigned ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000442 if obj >= 0:
443 if obj <= 0xff:
444 self.write(BININT1 + chr(obj))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000445 return
Guido van Rossum3a41c612003-01-28 15:10:22 +0000446 if obj <= 0xffff:
Guido van Rossumba884f32003-01-29 20:14:23 +0000447 self.write("%c%c%c" % (BININT2, obj&0xff, obj>>8))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000448 return
449 # Next check for 4-byte signed ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000450 high_bits = obj >> 31 # note that Python shift sign-extends
Tim Petersd95c2df2003-01-28 03:41:54 +0000451 if high_bits == 0 or high_bits == -1:
Tim Peters44714002001-04-10 05:02:52 +0000452 # All high bits are copies of bit 2**31, so the value
453 # fits in a 4-byte signed int.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000454 self.write(BININT + pack("<i", obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000455 return
Tim Peters44714002001-04-10 05:02:52 +0000456 # Text pickle, or int too big to fit in signed 4-byte format.
Walter Dörwald70a6b492004-02-12 17:35:32 +0000457 self.write(INT + repr(obj) + '\n')
Guido van Rossumddefaf32007-01-14 03:31:43 +0000458 # XXX save_int is merged into save_long
459 # dispatch[IntType] = save_int
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000460
Guido van Rossum3a41c612003-01-28 15:10:22 +0000461 def save_long(self, obj, pack=struct.pack):
Guido van Rossumddefaf32007-01-14 03:31:43 +0000462 if self.bin:
463 # If the int is small enough to fit in a signed 4-byte 2's-comp
464 # format, we can store it more efficiently than the general
465 # case.
466 # First one- and two-byte unsigned ints:
467 if obj >= 0:
468 if obj <= 0xff:
469 self.write(BININT1 + chr(obj))
470 return
471 if obj <= 0xffff:
472 self.write("%c%c%c" % (BININT2, obj&0xff, obj>>8))
473 return
474 # Next check for 4-byte signed ints:
475 high_bits = obj >> 31 # note that Python shift sign-extends
476 if high_bits == 0 or high_bits == -1:
477 # All high bits are copies of bit 2**31, so the value
478 # fits in a 4-byte signed int.
479 self.write(BININT + pack("<i", obj))
480 return
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000481 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000482 bytes = encode_long(obj)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000483 n = len(bytes)
484 if n < 256:
485 self.write(LONG1 + chr(n) + bytes)
486 else:
487 self.write(LONG4 + pack("<i", n) + bytes)
Tim Petersee1a53c2003-02-02 02:57:53 +0000488 return
Walter Dörwald70a6b492004-02-12 17:35:32 +0000489 self.write(LONG + repr(obj) + '\n')
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000490 dispatch[LongType] = save_long
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000491
Guido van Rossum3a41c612003-01-28 15:10:22 +0000492 def save_float(self, obj, pack=struct.pack):
Guido van Rossumd3703791998-10-22 20:15:36 +0000493 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000494 self.write(BINFLOAT + pack('>d', obj))
Guido van Rossumd3703791998-10-22 20:15:36 +0000495 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000496 self.write(FLOAT + repr(obj) + '\n')
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000497 dispatch[FloatType] = save_float
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000498
Guido van Rossum3a41c612003-01-28 15:10:22 +0000499 def save_string(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000500 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000501 n = len(obj)
Tim Petersbbf63cd2003-01-27 21:15:36 +0000502 if n < 256:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000503 self.write(SHORT_BINSTRING + chr(n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000504 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000505 self.write(BINSTRING + pack("<i", n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000506 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000507 self.write(STRING + repr(obj) + '\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000508 self.memoize(obj)
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000509 dispatch[StringType] = save_string
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000510
Guido van Rossum3a41c612003-01-28 15:10:22 +0000511 def save_unicode(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000512 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000513 encoding = obj.encode('utf-8')
Tim Petersbbf63cd2003-01-27 21:15:36 +0000514 n = len(encoding)
Guido van Rossum5c938d02003-01-28 03:03:08 +0000515 self.write(BINUNICODE + pack("<i", n) + encoding)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000516 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000517 obj = obj.replace("\\", "\\u005c")
518 obj = obj.replace("\n", "\\u000a")
519 self.write(UNICODE + obj.encode('raw-unicode-escape') + '\n')
520 self.memoize(obj)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000521 dispatch[UnicodeType] = save_unicode
522
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000523 if StringType == UnicodeType:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000524 # This is true for Jython
Guido van Rossum3a41c612003-01-28 15:10:22 +0000525 def save_string(self, obj, pack=struct.pack):
526 unicode = obj.isunicode()
Guido van Rossum31584cb2001-01-22 14:53:29 +0000527
Tim Petersc32d8242001-04-10 02:48:53 +0000528 if self.bin:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000529 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000530 obj = obj.encode("utf-8")
531 l = len(obj)
Tim Petersc32d8242001-04-10 02:48:53 +0000532 if l < 256 and not unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000533 self.write(SHORT_BINSTRING + chr(l) + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000534 else:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000535 s = pack("<i", l)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000536 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000537 self.write(BINUNICODE + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000538 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000539 self.write(BINSTRING + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000540 else:
Tim Peters658cba62001-02-09 20:06:00 +0000541 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000542 obj = obj.replace("\\", "\\u005c")
543 obj = obj.replace("\n", "\\u000a")
544 obj = obj.encode('raw-unicode-escape')
545 self.write(UNICODE + obj + '\n')
Guido van Rossum31584cb2001-01-22 14:53:29 +0000546 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000547 self.write(STRING + repr(obj) + '\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000548 self.memoize(obj)
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000549 dispatch[StringType] = save_string
Tim Peters658cba62001-02-09 20:06:00 +0000550
Guido van Rossum3a41c612003-01-28 15:10:22 +0000551 def save_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000552 write = self.write
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000553 proto = self.proto
554
Guido van Rossum3a41c612003-01-28 15:10:22 +0000555 n = len(obj)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000556 if n == 0:
557 if proto:
558 write(EMPTY_TUPLE)
559 else:
560 write(MARK + TUPLE)
Tim Petersd97da802003-01-28 05:48:29 +0000561 return
562
563 save = self.save
564 memo = self.memo
565 if n <= 3 and proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000566 for element in obj:
Tim Petersd97da802003-01-28 05:48:29 +0000567 save(element)
568 # Subtle. Same as in the big comment below.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000569 if id(obj) in memo:
570 get = self.get(memo[id(obj)][0])
Tim Petersd97da802003-01-28 05:48:29 +0000571 write(POP * n + get)
572 else:
573 write(_tuplesize2code[n])
Guido van Rossum3a41c612003-01-28 15:10:22 +0000574 self.memoize(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000575 return
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000576
Tim Peters1d63c9f2003-02-02 20:29:39 +0000577 # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple
Tim Petersff57bff2003-01-28 05:34:53 +0000578 # has more than 3 elements.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000579 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000580 for element in obj:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000581 save(element)
582
Tim Peters1d63c9f2003-02-02 20:29:39 +0000583 if id(obj) in memo:
Tim Petersf558da02003-01-28 02:09:55 +0000584 # Subtle. d was not in memo when we entered save_tuple(), so
585 # the process of saving the tuple's elements must have saved
586 # the tuple itself: the tuple is recursive. The proper action
587 # now is to throw away everything we put on the stack, and
588 # simply GET the tuple (it's already constructed). This check
589 # could have been done in the "for element" loop instead, but
590 # recursive tuples are a rare thing.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000591 get = self.get(memo[id(obj)][0])
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000592 if proto:
Tim Petersf558da02003-01-28 02:09:55 +0000593 write(POP_MARK + get)
594 else: # proto 0 -- POP_MARK not available
Tim Petersd97da802003-01-28 05:48:29 +0000595 write(POP * (n+1) + get)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000596 return
597
Tim Peters1d63c9f2003-02-02 20:29:39 +0000598 # No recursion.
Tim Peters518df0d2003-01-28 01:00:38 +0000599 self.write(TUPLE)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000600 self.memoize(obj)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000601
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000602 dispatch[TupleType] = save_tuple
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000603
Tim Petersa6ae9a22003-01-28 16:58:41 +0000604 # save_empty_tuple() isn't used by anything in Python 2.3. However, I
605 # found a Pickler subclass in Zope3 that calls it, so it's not harmless
606 # to remove it.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000607 def save_empty_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000608 self.write(EMPTY_TUPLE)
609
Guido van Rossum3a41c612003-01-28 15:10:22 +0000610 def save_list(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000611 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000612
Tim Petersc32d8242001-04-10 02:48:53 +0000613 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000614 write(EMPTY_LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000615 else: # proto 0 -- can't use EMPTY_LIST
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000616 write(MARK + LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000617
618 self.memoize(obj)
619 self._batch_appends(iter(obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000620
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000621 dispatch[ListType] = save_list
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000622
Tim Peters42f08ac2003-02-11 22:43:24 +0000623 # Keep in synch with cPickle's BATCHSIZE. Nothing will break if it gets
624 # out of synch, though.
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000625 _BATCHSIZE = 1000
626
627 def _batch_appends(self, items):
628 # Helper to batch up APPENDS sequences
629 save = self.save
630 write = self.write
631
632 if not self.bin:
633 for x in items:
634 save(x)
635 write(APPEND)
636 return
637
638 r = xrange(self._BATCHSIZE)
639 while items is not None:
640 tmp = []
641 for i in r:
642 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000643 x = next(items)
Guido van Rossum5aac4e62003-02-06 22:57:00 +0000644 tmp.append(x)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000645 except StopIteration:
646 items = None
647 break
648 n = len(tmp)
649 if n > 1:
650 write(MARK)
651 for x in tmp:
652 save(x)
653 write(APPENDS)
654 elif n:
655 save(tmp[0])
656 write(APPEND)
657 # else tmp is empty, and we're done
658
Guido van Rossum3a41c612003-01-28 15:10:22 +0000659 def save_dict(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000660 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000661
Tim Petersc32d8242001-04-10 02:48:53 +0000662 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000663 write(EMPTY_DICT)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000664 else: # proto 0 -- can't use EMPTY_DICT
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000665 write(MARK + DICT)
666
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000667 self.memoize(obj)
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000668 self._batch_setitems(iter(obj.items()))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000669
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000670 dispatch[DictionaryType] = save_dict
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000671 if not PyStringMap is None:
672 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000673
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000674 def _batch_setitems(self, items):
675 # Helper to batch up SETITEMS sequences; proto >= 1 only
676 save = self.save
677 write = self.write
678
679 if not self.bin:
680 for k, v in items:
681 save(k)
682 save(v)
683 write(SETITEM)
684 return
685
686 r = xrange(self._BATCHSIZE)
687 while items is not None:
688 tmp = []
689 for i in r:
690 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000691 tmp.append(next(items))
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000692 except StopIteration:
693 items = None
694 break
695 n = len(tmp)
696 if n > 1:
697 write(MARK)
698 for k, v in tmp:
699 save(k)
700 save(v)
701 write(SETITEMS)
702 elif n:
703 k, v = tmp[0]
704 save(k)
705 save(v)
706 write(SETITEM)
707 # else tmp is empty, and we're done
708
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000709 def save_global(self, obj, name=None, pack=struct.pack):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000710 write = self.write
711 memo = self.memo
712
Tim Petersc32d8242001-04-10 02:48:53 +0000713 if name is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000714 name = obj.__name__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000715
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000716 module = getattr(obj, "__module__", None)
717 if module is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000718 module = whichmodule(obj, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000719
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000720 try:
721 __import__(module)
722 mod = sys.modules[module]
723 klass = getattr(mod, name)
724 except (ImportError, KeyError, AttributeError):
725 raise PicklingError(
726 "Can't pickle %r: it's not found as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000727 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000728 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000729 if klass is not obj:
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000730 raise PicklingError(
731 "Can't pickle %r: it's not the same object as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000732 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000733
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000734 if self.proto >= 2:
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000735 code = _extension_registry.get((module, name))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000736 if code:
737 assert code > 0
738 if code <= 0xff:
739 write(EXT1 + chr(code))
740 elif code <= 0xffff:
Guido van Rossumba884f32003-01-29 20:14:23 +0000741 write("%c%c%c" % (EXT2, code&0xff, code>>8))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000742 else:
743 write(EXT4 + pack("<i", code))
744 return
745
Tim Peters518df0d2003-01-28 01:00:38 +0000746 write(GLOBAL + module + '\n' + name + '\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000747 self.memoize(obj)
Tim Peters3b769832003-01-28 03:51:36 +0000748
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000749 dispatch[ClassType] = save_global
750 dispatch[FunctionType] = save_global
751 dispatch[BuiltinFunctionType] = save_global
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000752 dispatch[TypeType] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000753
Guido van Rossum1be31752003-01-28 15:19:53 +0000754# Pickling helpers
Guido van Rossuma48061a1995-01-10 00:31:14 +0000755
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000756def _keep_alive(x, memo):
757 """Keeps a reference to the object x in the memo.
758
759 Because we remember objects by their id, we have
760 to assure that possibly temporary objects are kept
761 alive by referencing them.
762 We store a reference at the id of the memo, which should
763 normally not be used unless someone tries to deepcopy
764 the memo itself...
765 """
766 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000767 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000768 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000769 # aha, this is the first one :-)
770 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000771
772
Tim Petersc0c12b52003-01-29 00:56:17 +0000773# A cache for whichmodule(), mapping a function object to the name of
774# the module in which the function was found.
775
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000776classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000777
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000778def whichmodule(func, funcname):
779 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000780
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000781 Search sys.modules for the module.
782 Cache in classmap.
783 Return a module name.
Tim Petersc0c12b52003-01-29 00:56:17 +0000784 If the function cannot be found, return "__main__".
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000785 """
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000786 # Python functions should always get an __module__ from their globals.
787 mod = getattr(func, "__module__", None)
788 if mod is not None:
789 return mod
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000790 if func in classmap:
791 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000792
Guido van Rossum634e53f2007-02-26 07:07:02 +0000793 for name, module in list(sys.modules.items()):
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000794 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000795 continue # skip dummy package entries
Jeremy Hyltoncc1fccb2003-02-06 16:23:01 +0000796 if name != '__main__' and getattr(module, funcname, None) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000797 break
798 else:
799 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000800 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000801 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000802
803
Guido van Rossum1be31752003-01-28 15:19:53 +0000804# Unpickling machinery
805
Guido van Rossuma48061a1995-01-10 00:31:14 +0000806class Unpickler:
807
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000808 def __init__(self, file):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000809 """This takes a file-like object for reading a pickle data stream.
810
Tim Peters5bd2a792003-02-01 16:45:06 +0000811 The protocol version of the pickle is detected automatically, so no
812 proto argument is needed.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000813
814 The file-like object must have two methods, a read() method that
815 takes an integer argument, and a readline() method that requires no
816 arguments. Both methods should return a string. Thus file-like
817 object can be a file object opened for reading, a StringIO object,
818 or any other custom object that meets this interface.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000819 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000820 self.readline = file.readline
821 self.read = file.read
822 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000823
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000824 def load(self):
Guido van Rossum3a41c612003-01-28 15:10:22 +0000825 """Read a pickled object representation from the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000826
Guido van Rossum3a41c612003-01-28 15:10:22 +0000827 Return the reconstituted object hierarchy specified in the file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000828 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000829 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000830 self.stack = []
831 self.append = self.stack.append
832 read = self.read
833 dispatch = self.dispatch
834 try:
835 while 1:
836 key = read(1)
837 dispatch[key](self)
Guido van Rossumb940e112007-01-10 16:19:56 +0000838 except _Stop as stopinst:
Guido van Rossumff871742000-12-13 18:11:56 +0000839 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000840
Tim Petersc23d18a2003-01-28 01:41:51 +0000841 # Return largest index k such that self.stack[k] is self.mark.
842 # If the stack doesn't contain a mark, eventually raises IndexError.
843 # This could be sped by maintaining another stack, of indices at which
844 # the mark appears. For that matter, the latter stack would suffice,
845 # and we wouldn't need to push mark objects on self.stack at all.
846 # Doing so is probably a good thing, though, since if the pickle is
847 # corrupt (or hostile) we may get a clue from finding self.mark embedded
848 # in unpickled objects.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000849 def marker(self):
850 stack = self.stack
851 mark = self.mark
852 k = len(stack)-1
853 while stack[k] is not mark: k = k-1
854 return k
855
856 dispatch = {}
857
858 def load_eof(self):
859 raise EOFError
860 dispatch[''] = load_eof
861
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000862 def load_proto(self):
863 proto = ord(self.read(1))
864 if not 0 <= proto <= 2:
865 raise ValueError, "unsupported pickle protocol: %d" % proto
866 dispatch[PROTO] = load_proto
867
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000868 def load_persid(self):
869 pid = self.readline()[:-1]
870 self.append(self.persistent_load(pid))
871 dispatch[PERSID] = load_persid
872
873 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000874 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000875 self.append(self.persistent_load(pid))
876 dispatch[BINPERSID] = load_binpersid
877
878 def load_none(self):
879 self.append(None)
880 dispatch[NONE] = load_none
881
Guido van Rossum7d97d312003-01-28 04:25:27 +0000882 def load_false(self):
883 self.append(False)
884 dispatch[NEWFALSE] = load_false
885
886 def load_true(self):
887 self.append(True)
888 dispatch[NEWTRUE] = load_true
889
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000890 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000891 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000892 if data == FALSE[1:]:
893 val = False
894 elif data == TRUE[1:]:
895 val = True
896 else:
897 try:
898 val = int(data)
899 except ValueError:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000900 val = int(data)
Guido van Rossume2763392002-04-05 19:30:08 +0000901 self.append(val)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000902 dispatch[INT] = load_int
903
904 def load_binint(self):
905 self.append(mloads('i' + self.read(4)))
906 dispatch[BININT] = load_binint
907
908 def load_binint1(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000909 self.append(ord(self.read(1)))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000910 dispatch[BININT1] = load_binint1
911
912 def load_binint2(self):
913 self.append(mloads('i' + self.read(2) + '\000\000'))
914 dispatch[BININT2] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000915
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000916 def load_long(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000917 self.append(int(self.readline()[:-1], 0))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000918 dispatch[LONG] = load_long
919
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000920 def load_long1(self):
921 n = ord(self.read(1))
922 bytes = self.read(n)
Tim Petersee1a53c2003-02-02 02:57:53 +0000923 self.append(decode_long(bytes))
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000924 dispatch[LONG1] = load_long1
925
926 def load_long4(self):
927 n = mloads('i' + self.read(4))
928 bytes = self.read(n)
Tim Petersee1a53c2003-02-02 02:57:53 +0000929 self.append(decode_long(bytes))
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000930 dispatch[LONG4] = load_long4
931
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000932 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000933 self.append(float(self.readline()[:-1]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000934 dispatch[FLOAT] = load_float
935
Guido van Rossumd3703791998-10-22 20:15:36 +0000936 def load_binfloat(self, unpack=struct.unpack):
937 self.append(unpack('>d', self.read(8))[0])
938 dispatch[BINFLOAT] = load_binfloat
939
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000940 def load_string(self):
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000941 rep = self.readline()[:-1]
Tim Petersad5a7712003-01-28 16:23:33 +0000942 for q in "\"'": # double or single quote
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000943 if rep.startswith(q):
944 if not rep.endswith(q):
945 raise ValueError, "insecure string pickle"
946 rep = rep[len(q):-len(q)]
947 break
948 else:
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000949 raise ValueError, "insecure string pickle"
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000950 self.append(rep.decode("string-escape"))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000951 dispatch[STRING] = load_string
952
953 def load_binstring(self):
954 len = mloads('i' + self.read(4))
955 self.append(self.read(len))
956 dispatch[BINSTRING] = load_binstring
957
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000958 def load_unicode(self):
959 self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
960 dispatch[UNICODE] = load_unicode
961
962 def load_binunicode(self):
963 len = mloads('i' + self.read(4))
964 self.append(unicode(self.read(len),'utf-8'))
965 dispatch[BINUNICODE] = load_binunicode
966
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000967 def load_short_binstring(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000968 len = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000969 self.append(self.read(len))
970 dispatch[SHORT_BINSTRING] = load_short_binstring
971
972 def load_tuple(self):
973 k = self.marker()
974 self.stack[k:] = [tuple(self.stack[k+1:])]
975 dispatch[TUPLE] = load_tuple
976
977 def load_empty_tuple(self):
978 self.stack.append(())
979 dispatch[EMPTY_TUPLE] = load_empty_tuple
980
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000981 def load_tuple1(self):
982 self.stack[-1] = (self.stack[-1],)
983 dispatch[TUPLE1] = load_tuple1
984
985 def load_tuple2(self):
986 self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
987 dispatch[TUPLE2] = load_tuple2
988
989 def load_tuple3(self):
990 self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
991 dispatch[TUPLE3] = load_tuple3
992
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000993 def load_empty_list(self):
994 self.stack.append([])
995 dispatch[EMPTY_LIST] = load_empty_list
996
997 def load_empty_dictionary(self):
998 self.stack.append({})
999 dispatch[EMPTY_DICT] = load_empty_dictionary
1000
1001 def load_list(self):
1002 k = self.marker()
1003 self.stack[k:] = [self.stack[k+1:]]
1004 dispatch[LIST] = load_list
1005
1006 def load_dict(self):
1007 k = self.marker()
1008 d = {}
1009 items = self.stack[k+1:]
1010 for i in range(0, len(items), 2):
1011 key = items[i]
1012 value = items[i+1]
1013 d[key] = value
1014 self.stack[k:] = [d]
1015 dispatch[DICT] = load_dict
1016
Tim Petersd01c1e92003-01-30 15:41:46 +00001017 # INST and OBJ differ only in how they get a class object. It's not
1018 # only sensible to do the rest in a common routine, the two routines
1019 # previously diverged and grew different bugs.
1020 # klass is the class to instantiate, and k points to the topmost mark
1021 # object, following which are the arguments for klass.__init__.
1022 def _instantiate(self, klass, k):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001023 args = tuple(self.stack[k+1:])
1024 del self.stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001025 instantiated = 0
Tim Petersd01c1e92003-01-30 15:41:46 +00001026 if (not args and
1027 type(klass) is ClassType and
1028 not hasattr(klass, "__getinitargs__")):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001029 try:
1030 value = _EmptyClass()
1031 value.__class__ = klass
Guido van Rossumb19e2a31998-04-13 18:08:45 +00001032 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001033 except RuntimeError:
1034 # In restricted execution, assignment to inst.__class__ is
1035 # prohibited
1036 pass
1037 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +00001038 try:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001039 value = klass(*args)
Guido van Rossumb940e112007-01-10 16:19:56 +00001040 except TypeError as err:
Guido van Rossum743d17e1998-09-15 20:25:57 +00001041 raise TypeError, "in constructor for %s: %s" % (
1042 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001043 self.append(value)
Tim Petersd01c1e92003-01-30 15:41:46 +00001044
1045 def load_inst(self):
1046 module = self.readline()[:-1]
1047 name = self.readline()[:-1]
1048 klass = self.find_class(module, name)
1049 self._instantiate(klass, self.marker())
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001050 dispatch[INST] = load_inst
1051
1052 def load_obj(self):
Tim Petersd01c1e92003-01-30 15:41:46 +00001053 # Stack is ... markobject classobject arg1 arg2 ...
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001054 k = self.marker()
Tim Petersd01c1e92003-01-30 15:41:46 +00001055 klass = self.stack.pop(k+1)
1056 self._instantiate(klass, k)
Tim Peters2344fae2001-01-15 00:50:52 +00001057 dispatch[OBJ] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001058
Guido van Rossum3a41c612003-01-28 15:10:22 +00001059 def load_newobj(self):
1060 args = self.stack.pop()
1061 cls = self.stack[-1]
1062 obj = cls.__new__(cls, *args)
Guido van Rossum533dbcf2003-01-28 17:55:05 +00001063 self.stack[-1] = obj
Guido van Rossum3a41c612003-01-28 15:10:22 +00001064 dispatch[NEWOBJ] = load_newobj
1065
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001066 def load_global(self):
1067 module = self.readline()[:-1]
1068 name = self.readline()[:-1]
1069 klass = self.find_class(module, name)
1070 self.append(klass)
1071 dispatch[GLOBAL] = load_global
1072
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001073 def load_ext1(self):
1074 code = ord(self.read(1))
1075 self.get_extension(code)
1076 dispatch[EXT1] = load_ext1
1077
1078 def load_ext2(self):
1079 code = mloads('i' + self.read(2) + '\000\000')
1080 self.get_extension(code)
1081 dispatch[EXT2] = load_ext2
1082
1083 def load_ext4(self):
1084 code = mloads('i' + self.read(4))
1085 self.get_extension(code)
1086 dispatch[EXT4] = load_ext4
1087
1088 def get_extension(self, code):
1089 nil = []
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001090 obj = _extension_cache.get(code, nil)
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001091 if obj is not nil:
1092 self.append(obj)
1093 return
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001094 key = _inverted_registry.get(code)
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001095 if not key:
1096 raise ValueError("unregistered extension code %d" % code)
1097 obj = self.find_class(*key)
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001098 _extension_cache[code] = obj
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001099 self.append(obj)
1100
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001101 def find_class(self, module, name):
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001102 # Subclasses may override this
Barry Warsawbf4d9592001-11-15 23:42:58 +00001103 __import__(module)
1104 mod = sys.modules[module]
1105 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001106 return klass
1107
1108 def load_reduce(self):
1109 stack = self.stack
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001110 args = stack.pop()
1111 func = stack[-1]
Raymond Hettingera6b45cc2004-12-07 07:05:57 +00001112 value = func(*args)
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001113 stack[-1] = value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001114 dispatch[REDUCE] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +00001115
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001116 def load_pop(self):
1117 del self.stack[-1]
1118 dispatch[POP] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +00001119
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001120 def load_pop_mark(self):
1121 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001122 del self.stack[k:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001123 dispatch[POP_MARK] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001124
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001125 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +00001126 self.append(self.stack[-1])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001127 dispatch[DUP] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +00001128
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001129 def load_get(self):
1130 self.append(self.memo[self.readline()[:-1]])
1131 dispatch[GET] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +00001132
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001133 def load_binget(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001134 i = ord(self.read(1))
Walter Dörwald70a6b492004-02-12 17:35:32 +00001135 self.append(self.memo[repr(i)])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001136 dispatch[BINGET] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001137
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001138 def load_long_binget(self):
1139 i = mloads('i' + self.read(4))
Walter Dörwald70a6b492004-02-12 17:35:32 +00001140 self.append(self.memo[repr(i)])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001141 dispatch[LONG_BINGET] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001142
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001143 def load_put(self):
1144 self.memo[self.readline()[:-1]] = self.stack[-1]
1145 dispatch[PUT] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +00001146
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001147 def load_binput(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001148 i = ord(self.read(1))
Walter Dörwald70a6b492004-02-12 17:35:32 +00001149 self.memo[repr(i)] = self.stack[-1]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001150 dispatch[BINPUT] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001151
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001152 def load_long_binput(self):
1153 i = mloads('i' + self.read(4))
Walter Dörwald70a6b492004-02-12 17:35:32 +00001154 self.memo[repr(i)] = self.stack[-1]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001155 dispatch[LONG_BINPUT] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001156
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001157 def load_append(self):
1158 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001159 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001160 list = stack[-1]
1161 list.append(value)
1162 dispatch[APPEND] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +00001163
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001164 def load_appends(self):
1165 stack = self.stack
1166 mark = self.marker()
1167 list = stack[mark - 1]
Tim Peters209ad952003-01-28 01:44:45 +00001168 list.extend(stack[mark + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001169 del stack[mark:]
1170 dispatch[APPENDS] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +00001171
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001172 def load_setitem(self):
1173 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001174 value = stack.pop()
1175 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001176 dict = stack[-1]
1177 dict[key] = value
1178 dispatch[SETITEM] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001179
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001180 def load_setitems(self):
1181 stack = self.stack
1182 mark = self.marker()
1183 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001184 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001185 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001186
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001187 del stack[mark:]
1188 dispatch[SETITEMS] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001189
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001190 def load_build(self):
1191 stack = self.stack
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001192 state = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001193 inst = stack[-1]
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001194 setstate = getattr(inst, "__setstate__", None)
1195 if setstate:
1196 setstate(state)
1197 return
1198 slotstate = None
1199 if isinstance(state, tuple) and len(state) == 2:
1200 state, slotstate = state
1201 if state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001202 try:
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001203 inst.__dict__.update(state)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001204 except RuntimeError:
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001205 # XXX In restricted execution, the instance's __dict__
1206 # is not accessible. Use the old way of unpickling
1207 # the instance variables. This is a semantic
1208 # difference when unpickling in restricted
1209 # vs. unrestricted modes.
Tim Peters080c88b2003-02-15 03:01:11 +00001210 # Note, however, that cPickle has never tried to do the
1211 # .update() business, and always uses
1212 # PyObject_SetItem(inst.__dict__, key, value) in a
1213 # loop over state.items().
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001214 for k, v in state.items():
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001215 setattr(inst, k, v)
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001216 if slotstate:
1217 for k, v in slotstate.items():
1218 setattr(inst, k, v)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001219 dispatch[BUILD] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001220
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001221 def load_mark(self):
1222 self.append(self.mark)
1223 dispatch[MARK] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001224
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001225 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001226 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001227 raise _Stop(value)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001228 dispatch[STOP] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001229
Guido van Rossume467be61997-12-05 19:42:42 +00001230# Helper class for load_inst/load_obj
1231
1232class _EmptyClass:
1233 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001234
Tim Peters91149822003-01-31 03:43:58 +00001235# Encode/decode longs in linear time.
1236
1237import binascii as _binascii
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001238
1239def encode_long(x):
Tim Peters91149822003-01-31 03:43:58 +00001240 r"""Encode a long to a two's complement little-endian binary string.
Guido van Rossume2a383d2007-01-15 16:59:06 +00001241 Note that 0 is a special case, returning an empty string, to save a
Tim Peters4b23f2b2003-01-31 16:43:39 +00001242 byte in the LONG1 pickling context.
1243
Guido van Rossume2a383d2007-01-15 16:59:06 +00001244 >>> encode_long(0)
Tim Peters4b23f2b2003-01-31 16:43:39 +00001245 ''
Guido van Rossume2a383d2007-01-15 16:59:06 +00001246 >>> encode_long(255)
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001247 '\xff\x00'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001248 >>> encode_long(32767)
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001249 '\xff\x7f'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001250 >>> encode_long(-256)
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001251 '\x00\xff'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001252 >>> encode_long(-32768)
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001253 '\x00\x80'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001254 >>> encode_long(-128)
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001255 '\x80'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001256 >>> encode_long(127)
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001257 '\x7f'
1258 >>>
1259 """
Tim Peters91149822003-01-31 03:43:58 +00001260
1261 if x == 0:
Tim Peters4b23f2b2003-01-31 16:43:39 +00001262 return ''
Tim Peters91149822003-01-31 03:43:58 +00001263 if x > 0:
1264 ashex = hex(x)
1265 assert ashex.startswith("0x")
1266 njunkchars = 2 + ashex.endswith('L')
1267 nibbles = len(ashex) - njunkchars
1268 if nibbles & 1:
1269 # need an even # of nibbles for unhexlify
1270 ashex = "0x0" + ashex[2:]
Tim Peters4b23f2b2003-01-31 16:43:39 +00001271 elif int(ashex[2], 16) >= 8:
Tim Peters91149822003-01-31 03:43:58 +00001272 # "looks negative", so need a byte of sign bits
1273 ashex = "0x00" + ashex[2:]
1274 else:
1275 # Build the 256's-complement: (1L << nbytes) + x. The trick is
1276 # to find the number of bytes in linear time (although that should
1277 # really be a constant-time task).
1278 ashex = hex(-x)
1279 assert ashex.startswith("0x")
1280 njunkchars = 2 + ashex.endswith('L')
1281 nibbles = len(ashex) - njunkchars
1282 if nibbles & 1:
Tim Petersee1a53c2003-02-02 02:57:53 +00001283 # Extend to a full byte.
Tim Peters91149822003-01-31 03:43:58 +00001284 nibbles += 1
Tim Peters4b23f2b2003-01-31 16:43:39 +00001285 nbits = nibbles * 4
Guido van Rossume2a383d2007-01-15 16:59:06 +00001286 x += 1 << nbits
Tim Peters91149822003-01-31 03:43:58 +00001287 assert x > 0
1288 ashex = hex(x)
Tim Petersee1a53c2003-02-02 02:57:53 +00001289 njunkchars = 2 + ashex.endswith('L')
1290 newnibbles = len(ashex) - njunkchars
1291 if newnibbles < nibbles:
1292 ashex = "0x" + "0" * (nibbles - newnibbles) + ashex[2:]
1293 if int(ashex[2], 16) < 8:
Tim Peters91149822003-01-31 03:43:58 +00001294 # "looks positive", so need a byte of sign bits
Tim Petersee1a53c2003-02-02 02:57:53 +00001295 ashex = "0xff" + ashex[2:]
Tim Peters91149822003-01-31 03:43:58 +00001296
1297 if ashex.endswith('L'):
1298 ashex = ashex[2:-1]
1299 else:
1300 ashex = ashex[2:]
Tim Petersee1a53c2003-02-02 02:57:53 +00001301 assert len(ashex) & 1 == 0, (x, ashex)
Tim Peters91149822003-01-31 03:43:58 +00001302 binary = _binascii.unhexlify(ashex)
1303 return binary[::-1]
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001304
1305def decode_long(data):
1306 r"""Decode a long from a two's complement little-endian binary string.
Tim Peters4b23f2b2003-01-31 16:43:39 +00001307
1308 >>> decode_long('')
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001309 0
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001310 >>> decode_long("\xff\x00")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001311 255
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001312 >>> decode_long("\xff\x7f")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001313 32767
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001314 >>> decode_long("\x00\xff")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001315 -256
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001316 >>> decode_long("\x00\x80")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001317 -32768
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001318 >>> decode_long("\x80")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001319 -128
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001320 >>> decode_long("\x7f")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001321 127
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001322 """
Tim Peters91149822003-01-31 03:43:58 +00001323
Tim Peters4b23f2b2003-01-31 16:43:39 +00001324 nbytes = len(data)
1325 if nbytes == 0:
Guido van Rossume2a383d2007-01-15 16:59:06 +00001326 return 0
Tim Peters91149822003-01-31 03:43:58 +00001327 ashex = _binascii.hexlify(data[::-1])
Guido van Rossume2a383d2007-01-15 16:59:06 +00001328 n = int(ashex, 16) # quadratic time before Python 2.3; linear now
Tim Peters91149822003-01-31 03:43:58 +00001329 if data[-1] >= '\x80':
Guido van Rossume2a383d2007-01-15 16:59:06 +00001330 n -= 1 << (nbytes * 8)
Tim Peters91149822003-01-31 03:43:58 +00001331 return n
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001332
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001333# Shorthands
1334
Jeremy Hyltonabe2c622001-10-15 21:29:28 +00001335try:
1336 from cStringIO import StringIO
1337except ImportError:
1338 from StringIO import StringIO
Guido van Rossumc7c5e691996-07-22 22:26:07 +00001339
Raymond Hettinger3489cad2004-12-05 05:20:42 +00001340def dump(obj, file, protocol=None):
1341 Pickler(file, protocol).dump(obj)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001342
Raymond Hettinger3489cad2004-12-05 05:20:42 +00001343def dumps(obj, protocol=None):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001344 file = StringIO()
Raymond Hettinger3489cad2004-12-05 05:20:42 +00001345 Pickler(file, protocol).dump(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001346 return file.getvalue()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001347
1348def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001349 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001350
1351def loads(str):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001352 file = StringIO(str)
1353 return Unpickler(file).load()
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001354
1355# Doctest
1356
1357def _test():
1358 import doctest
1359 return doctest.testmod()
1360
1361if __name__ == "__main__":
1362 _test()