blob: 5d0aba740e25a6227b31e20c055909d325bc7f4c [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.
Georg Brandldffbf5f2008-05-20 07:49:57 +00004See 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
Senthil Kumaran4af1c6a2011-07-28 22:30:27 +080027__version__ = "$Revision: 72223 $" # Code version
Guido van Rossuma48061a1995-01-10 00:31:14 +000028
29from types import *
Georg Brandldffbf5f2008-05-20 07:49:57 +000030from copy_reg import dispatch_table
31from 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)])
Neal Norwitzd5ba4ae2002-02-11 18:12:06 +0000166del x
Skip Montanaro23bafc62001-02-18 03:10:09 +0000167
Guido van Rossum1be31752003-01-28 15:19:53 +0000168
169# Pickling machinery
170
Guido van Rossuma48061a1995-01-10 00:31:14 +0000171class Pickler:
172
Raymond Hettinger3489cad2004-12-05 05:20:42 +0000173 def __init__(self, file, protocol=None):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000174 """This takes a file-like object for writing a pickle data stream.
175
Guido van Rossumcf117b02003-02-09 17:19:41 +0000176 The optional protocol argument tells the pickler to use the
177 given protocol; supported protocols are 0, 1, 2. The default
Guido van Rossum7eff63a2003-01-31 19:42:31 +0000178 protocol is 0, to be backwards compatible. (Protocol 0 is the
179 only protocol that can be written to a file opened in text
Tim Peters5bd2a792003-02-01 16:45:06 +0000180 mode and read back successfully. When using a protocol higher
181 than 0, make sure the file is opened in binary mode, both when
182 pickling and unpickling.)
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000183
184 Protocol 1 is more efficient than protocol 0; protocol 2 is
Guido van Rossum7eff63a2003-01-31 19:42:31 +0000185 more efficient than protocol 1.
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000186
Guido van Rossum7eff63a2003-01-31 19:42:31 +0000187 Specifying a negative protocol version selects the highest
Tim Peters5bd2a792003-02-01 16:45:06 +0000188 protocol version supported. The higher the protocol used, the
189 more recent the version of Python needed to read the pickle
190 produced.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000191
192 The file parameter must have a write() method that accepts a single
193 string argument. It can thus be an open file object, a StringIO
194 object, or any other custom object that meets this interface.
195
196 """
Guido van Rossumcf117b02003-02-09 17:19:41 +0000197 if protocol is None:
198 protocol = 0
199 if protocol < 0:
Tim Peters8587b3c2003-02-13 15:44:41 +0000200 protocol = HIGHEST_PROTOCOL
201 elif not 0 <= protocol <= HIGHEST_PROTOCOL:
202 raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000203 self.write = file.write
204 self.memo = {}
Guido van Rossumcf117b02003-02-09 17:19:41 +0000205 self.proto = int(protocol)
206 self.bin = protocol >= 1
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000207 self.fast = 0
Guido van Rossuma48061a1995-01-10 00:31:14 +0000208
Fred Drake7f781c92002-05-01 20:33:53 +0000209 def clear_memo(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000210 """Clears the pickler's "memo".
211
212 The memo is the data structure that remembers which objects the
Tim Petersb377f8a2003-01-28 00:23:36 +0000213 pickler has already seen, so that shared or recursive objects are
214 pickled by reference and not by value. This method is useful when
215 re-using picklers.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000216
217 """
Fred Drake7f781c92002-05-01 20:33:53 +0000218 self.memo.clear()
219
Guido van Rossum3a41c612003-01-28 15:10:22 +0000220 def dump(self, obj):
Tim Peters5bd2a792003-02-01 16:45:06 +0000221 """Write a pickled representation of obj to the open file."""
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000222 if self.proto >= 2:
223 self.write(PROTO + chr(self.proto))
Guido van Rossum3a41c612003-01-28 15:10:22 +0000224 self.save(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000225 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000226
Jeremy Hylton3422c992003-01-24 19:29:52 +0000227 def memoize(self, obj):
228 """Store an object in the memo."""
229
Tim Peterse46b73f2003-01-27 21:22:10 +0000230 # The Pickler memo is a dictionary mapping object ids to 2-tuples
231 # that contain the Unpickler memo key and the object being memoized.
232 # The memo key is written to the pickle and will become
Jeremy Hylton3422c992003-01-24 19:29:52 +0000233 # the key in the Unpickler's memo. The object is stored in the
Tim Peterse46b73f2003-01-27 21:22:10 +0000234 # Pickler memo so that transient objects are kept alive during
235 # pickling.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000236
Tim Peterse46b73f2003-01-27 21:22:10 +0000237 # The use of the Unpickler memo length as the memo key is just a
238 # convention. The only requirement is that the memo values be unique.
239 # But there appears no advantage to any other scheme, and this
Tim Peterscbd0a322003-01-28 00:24:43 +0000240 # scheme allows the Unpickler memo to be implemented as a plain (but
Tim Peterse46b73f2003-01-27 21:22:10 +0000241 # growable) array, indexed by memo key.
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000242 if self.fast:
243 return
Guido van Rossum9b40e802003-01-30 06:37:41 +0000244 assert id(obj) not in self.memo
Jeremy Hylton3422c992003-01-24 19:29:52 +0000245 memo_len = len(self.memo)
246 self.write(self.put(memo_len))
Tim Peters518df0d2003-01-28 01:00:38 +0000247 self.memo[id(obj)] = memo_len, obj
Jeremy Hylton3422c992003-01-24 19:29:52 +0000248
Tim Petersbb38e302003-01-27 21:25:41 +0000249 # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000250 def put(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000251 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000252 if i < 256:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000253 return BINPUT + chr(i)
254 else:
255 return LONG_BINPUT + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000256
Walter Dörwald70a6b492004-02-12 17:35:32 +0000257 return PUT + repr(i) + '\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000258
Tim Petersbb38e302003-01-27 21:25:41 +0000259 # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000260 def get(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000261 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000262 if i < 256:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000263 return BINGET + chr(i)
264 else:
265 return LONG_BINGET + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000266
Walter Dörwald70a6b492004-02-12 17:35:32 +0000267 return GET + repr(i) + '\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000268
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000269 def save(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000270 # Check for persistent id (defined by a subclass)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000271 pid = self.persistent_id(obj)
Alexandre Vassalotti1d3a1732013-11-30 13:24:13 -0800272 if pid is not None:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000273 self.save_pers(pid)
274 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000275
Guido van Rossumbc64e222003-01-28 16:34:19 +0000276 # Check the memo
277 x = self.memo.get(id(obj))
278 if x:
279 self.write(self.get(x[0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000280 return
281
Guido van Rossumbc64e222003-01-28 16:34:19 +0000282 # Check the type dispatch table
Guido van Rossum3a41c612003-01-28 15:10:22 +0000283 t = type(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000284 f = self.dispatch.get(t)
285 if f:
286 f(self, obj) # Call unbound method with explicit self
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000287 return
288
Georg Brandldffbf5f2008-05-20 07:49:57 +0000289 # Check copy_reg.dispatch_table
Guido van Rossumbc64e222003-01-28 16:34:19 +0000290 reduce = dispatch_table.get(t)
Guido van Rossumc53f0092003-02-18 22:05:12 +0000291 if reduce:
292 rv = reduce(obj)
293 else:
Antoine Pitrou561a8212011-10-04 09:34:48 +0200294 # Check for a class with a custom metaclass; treat as regular class
295 try:
296 issc = issubclass(t, TypeType)
297 except TypeError: # t is not a class (old Boost; see SF #502085)
298 issc = 0
299 if issc:
300 self.save_global(obj)
301 return
302
Guido van Rossumc53f0092003-02-18 22:05:12 +0000303 # Check for a __reduce_ex__ method, fall back to __reduce__
304 reduce = getattr(obj, "__reduce_ex__", None)
305 if reduce:
306 rv = reduce(self.proto)
307 else:
308 reduce = getattr(obj, "__reduce__", None)
309 if reduce:
310 rv = reduce()
311 else:
312 raise PicklingError("Can't pickle %r object: %r" %
313 (t.__name__, obj))
Tim Petersb32a8312003-01-28 00:48:09 +0000314
Guido van Rossumbc64e222003-01-28 16:34:19 +0000315 # Check for string returned by reduce(), meaning "save as global"
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000316 if type(rv) is StringType:
Guido van Rossumbc64e222003-01-28 16:34:19 +0000317 self.save_global(obj, rv)
Tim Petersb32a8312003-01-28 00:48:09 +0000318 return
319
Guido van Rossumbc64e222003-01-28 16:34:19 +0000320 # Assert that reduce() returned a tuple
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000321 if type(rv) is not TupleType:
Guido van Rossumbc64e222003-01-28 16:34:19 +0000322 raise PicklingError("%s must return string or tuple" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000323
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000324 # Assert that it returned an appropriately sized tuple
Guido van Rossumbc64e222003-01-28 16:34:19 +0000325 l = len(rv)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000326 if not (2 <= l <= 5):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000327 raise PicklingError("Tuple returned by %s must have "
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000328 "two to five elements" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000329
Guido van Rossumbc64e222003-01-28 16:34:19 +0000330 # Save the reduce() output and finally memoize the object
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000331 self.save_reduce(obj=obj, *rv)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000332
Guido van Rossum3a41c612003-01-28 15:10:22 +0000333 def persistent_id(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000334 # This exists so a subclass can override it
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000335 return None
336
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000337 def save_pers(self, pid):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000338 # Save a persistent id reference
Tim Petersbd1cdb92003-01-28 01:03:10 +0000339 if self.bin:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000340 self.save(pid)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000341 self.write(BINPERSID)
Tim Petersbd1cdb92003-01-28 01:03:10 +0000342 else:
343 self.write(PERSID + str(pid) + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000344
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000345 def save_reduce(self, func, args, state=None,
346 listitems=None, dictitems=None, obj=None):
Jeremy Hyltone3a565e2003-06-29 16:59:59 +0000347 # This API is called by some subclasses
Guido van Rossumbc64e222003-01-28 16:34:19 +0000348
349 # Assert that args is a tuple or None
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000350 if not isinstance(args, TupleType):
Raymond Hettingera6b45cc2004-12-07 07:05:57 +0000351 raise PicklingError("args from reduce() should be a tuple")
Guido van Rossumbc64e222003-01-28 16:34:19 +0000352
353 # Assert that func is callable
Brett Cannon211b3cd2008-08-04 21:34:34 +0000354 if not hasattr(func, '__call__'):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000355 raise PicklingError("func from reduce should be callable")
356
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000357 save = self.save
Guido van Rossumbc64e222003-01-28 16:34:19 +0000358 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000359
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000360 # Protocol 2 special case: if func's name is __newobj__, use NEWOBJ
361 if self.proto >= 2 and getattr(func, "__name__", "") == "__newobj__":
362 # A __reduce__ implementation can direct protocol 2 to
363 # use the more efficient NEWOBJ opcode, while still
364 # allowing protocol 0 and 1 to work normally. For this to
365 # work, the function returned by __reduce__ should be
366 # called __newobj__, and its first argument should be a
367 # new-style class. The implementation for __newobj__
368 # should be as follows, although pickle has no way to
369 # verify this:
370 #
371 # def __newobj__(cls, *args):
372 # return cls.__new__(cls, *args)
373 #
374 # Protocols 0 and 1 will pickle a reference to __newobj__,
375 # while protocol 2 (and above) will pickle a reference to
376 # cls, the remaining args tuple, and the NEWOBJ code,
377 # which calls cls.__new__(cls, *args) at unpickling time
378 # (see load_newobj below). If __reduce__ returns a
379 # three-tuple, the state from the third tuple item will be
380 # pickled regardless of the protocol, calling __setstate__
381 # at unpickling time (see load_build below).
382 #
383 # Note that no standard __newobj__ implementation exists;
384 # you have to provide your own. This is to enforce
385 # compatibility with Python 2.2 (pickles written using
386 # protocol 0 or 1 in Python 2.3 should be unpicklable by
387 # Python 2.2).
388 cls = args[0]
389 if not hasattr(cls, "__new__"):
390 raise PicklingError(
391 "args[0] from __newobj__ args has no __new__")
Guido van Rossumf7f45172003-01-31 17:17:49 +0000392 if obj is not None and cls is not obj.__class__:
393 raise PicklingError(
394 "args[0] from __newobj__ args has the wrong class")
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000395 args = args[1:]
396 save(cls)
397 save(args)
398 write(NEWOBJ)
399 else:
400 save(func)
401 save(args)
402 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000403
Guido van Rossumf7f45172003-01-31 17:17:49 +0000404 if obj is not None:
405 self.memoize(obj)
406
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000407 # More new special cases (that work with older protocols as
408 # well): when __reduce__ returns a tuple with 4 or 5 items,
409 # the 4th and 5th item should be iterators that provide list
410 # items and dict items (as (key, value) tuples), or None.
411
412 if listitems is not None:
413 self._batch_appends(listitems)
414
415 if dictitems is not None:
416 self._batch_setitems(dictitems)
417
Tim Petersc32d8242001-04-10 02:48:53 +0000418 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000419 save(state)
420 write(BUILD)
421
Guido van Rossumbc64e222003-01-28 16:34:19 +0000422 # Methods below this point are dispatched through the dispatch table
423
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000424 dispatch = {}
425
Guido van Rossum3a41c612003-01-28 15:10:22 +0000426 def save_none(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000427 self.write(NONE)
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000428 dispatch[NoneType] = save_none
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000429
Alexandre Vassalottia2934282013-11-30 16:52:03 -0800430 def save_ellipsis(self, obj):
431 self.save_global(Ellipsis, 'Ellipsis')
432 dispatch[type(Ellipsis)] = save_ellipsis
433
434 def save_notimplemented(self, obj):
435 self.save_global(NotImplemented, 'NotImplemented')
436 dispatch[type(NotImplemented)] = save_notimplemented
437
Guido van Rossum3a41c612003-01-28 15:10:22 +0000438 def save_bool(self, obj):
Guido van Rossum7d97d312003-01-28 04:25:27 +0000439 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000440 self.write(obj and NEWTRUE or NEWFALSE)
Guido van Rossum7d97d312003-01-28 04:25:27 +0000441 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000442 self.write(obj and TRUE or FALSE)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000443 dispatch[bool] = save_bool
444
Guido van Rossum3a41c612003-01-28 15:10:22 +0000445 def save_int(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000446 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000447 # If the int is small enough to fit in a signed 4-byte 2's-comp
448 # format, we can store it more efficiently than the general
449 # case.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000450 # First one- and two-byte unsigned ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000451 if obj >= 0:
452 if obj <= 0xff:
453 self.write(BININT1 + chr(obj))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000454 return
Guido van Rossum3a41c612003-01-28 15:10:22 +0000455 if obj <= 0xffff:
Guido van Rossumba884f32003-01-29 20:14:23 +0000456 self.write("%c%c%c" % (BININT2, obj&0xff, obj>>8))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000457 return
458 # Next check for 4-byte signed ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000459 high_bits = obj >> 31 # note that Python shift sign-extends
Tim Petersd95c2df2003-01-28 03:41:54 +0000460 if high_bits == 0 or high_bits == -1:
Tim Peters44714002001-04-10 05:02:52 +0000461 # All high bits are copies of bit 2**31, so the value
462 # fits in a 4-byte signed int.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000463 self.write(BININT + pack("<i", obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000464 return
Tim Peters44714002001-04-10 05:02:52 +0000465 # Text pickle, or int too big to fit in signed 4-byte format.
Walter Dörwald70a6b492004-02-12 17:35:32 +0000466 self.write(INT + repr(obj) + '\n')
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000467 dispatch[IntType] = save_int
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000468
Guido van Rossum3a41c612003-01-28 15:10:22 +0000469 def save_long(self, obj, pack=struct.pack):
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000470 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000471 bytes = encode_long(obj)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000472 n = len(bytes)
473 if n < 256:
474 self.write(LONG1 + chr(n) + bytes)
475 else:
476 self.write(LONG4 + pack("<i", n) + bytes)
Tim Petersee1a53c2003-02-02 02:57:53 +0000477 return
Walter Dörwald70a6b492004-02-12 17:35:32 +0000478 self.write(LONG + repr(obj) + '\n')
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000479 dispatch[LongType] = save_long
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000480
Guido van Rossum3a41c612003-01-28 15:10:22 +0000481 def save_float(self, obj, pack=struct.pack):
Guido van Rossumd3703791998-10-22 20:15:36 +0000482 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000483 self.write(BINFLOAT + pack('>d', obj))
Guido van Rossumd3703791998-10-22 20:15:36 +0000484 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000485 self.write(FLOAT + repr(obj) + '\n')
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000486 dispatch[FloatType] = save_float
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000487
Guido van Rossum3a41c612003-01-28 15:10:22 +0000488 def save_string(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000489 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000490 n = len(obj)
Tim Petersbbf63cd2003-01-27 21:15:36 +0000491 if n < 256:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000492 self.write(SHORT_BINSTRING + chr(n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000493 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000494 self.write(BINSTRING + pack("<i", n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000495 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000496 self.write(STRING + repr(obj) + '\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000497 self.memoize(obj)
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000498 dispatch[StringType] = save_string
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000499
Guido van Rossum3a41c612003-01-28 15:10:22 +0000500 def save_unicode(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000501 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000502 encoding = obj.encode('utf-8')
Tim Petersbbf63cd2003-01-27 21:15:36 +0000503 n = len(encoding)
Guido van Rossum5c938d02003-01-28 03:03:08 +0000504 self.write(BINUNICODE + pack("<i", n) + encoding)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000505 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000506 obj = obj.replace("\\", "\\u005c")
507 obj = obj.replace("\n", "\\u000a")
508 self.write(UNICODE + obj.encode('raw-unicode-escape') + '\n')
509 self.memoize(obj)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000510 dispatch[UnicodeType] = save_unicode
511
Benjamin Peterson1d22d002009-04-05 01:04:38 +0000512 if StringType is UnicodeType:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000513 # This is true for Jython
Guido van Rossum3a41c612003-01-28 15:10:22 +0000514 def save_string(self, obj, pack=struct.pack):
515 unicode = obj.isunicode()
Guido van Rossum31584cb2001-01-22 14:53:29 +0000516
Tim Petersc32d8242001-04-10 02:48:53 +0000517 if self.bin:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000518 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000519 obj = obj.encode("utf-8")
520 l = len(obj)
Tim Petersc32d8242001-04-10 02:48:53 +0000521 if l < 256 and not unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000522 self.write(SHORT_BINSTRING + chr(l) + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000523 else:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000524 s = pack("<i", l)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000525 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000526 self.write(BINUNICODE + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000527 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000528 self.write(BINSTRING + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000529 else:
Tim Peters658cba62001-02-09 20:06:00 +0000530 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000531 obj = obj.replace("\\", "\\u005c")
532 obj = obj.replace("\n", "\\u000a")
533 obj = obj.encode('raw-unicode-escape')
534 self.write(UNICODE + obj + '\n')
Guido van Rossum31584cb2001-01-22 14:53:29 +0000535 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000536 self.write(STRING + repr(obj) + '\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000537 self.memoize(obj)
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000538 dispatch[StringType] = save_string
Tim Peters658cba62001-02-09 20:06:00 +0000539
Guido van Rossum3a41c612003-01-28 15:10:22 +0000540 def save_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000541 write = self.write
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000542 proto = self.proto
543
Guido van Rossum3a41c612003-01-28 15:10:22 +0000544 n = len(obj)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000545 if n == 0:
546 if proto:
547 write(EMPTY_TUPLE)
548 else:
549 write(MARK + TUPLE)
Tim Petersd97da802003-01-28 05:48:29 +0000550 return
551
552 save = self.save
553 memo = self.memo
554 if n <= 3 and proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000555 for element in obj:
Tim Petersd97da802003-01-28 05:48:29 +0000556 save(element)
557 # Subtle. Same as in the big comment below.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000558 if id(obj) in memo:
559 get = self.get(memo[id(obj)][0])
Tim Petersd97da802003-01-28 05:48:29 +0000560 write(POP * n + get)
561 else:
562 write(_tuplesize2code[n])
Guido van Rossum3a41c612003-01-28 15:10:22 +0000563 self.memoize(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000564 return
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000565
Tim Peters1d63c9f2003-02-02 20:29:39 +0000566 # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple
Tim Petersff57bff2003-01-28 05:34:53 +0000567 # has more than 3 elements.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000568 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000569 for element in obj:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000570 save(element)
571
Tim Peters1d63c9f2003-02-02 20:29:39 +0000572 if id(obj) in memo:
Tim Petersf558da02003-01-28 02:09:55 +0000573 # Subtle. d was not in memo when we entered save_tuple(), so
574 # the process of saving the tuple's elements must have saved
575 # the tuple itself: the tuple is recursive. The proper action
576 # now is to throw away everything we put on the stack, and
577 # simply GET the tuple (it's already constructed). This check
578 # could have been done in the "for element" loop instead, but
579 # recursive tuples are a rare thing.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000580 get = self.get(memo[id(obj)][0])
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000581 if proto:
Tim Petersf558da02003-01-28 02:09:55 +0000582 write(POP_MARK + get)
583 else: # proto 0 -- POP_MARK not available
Tim Petersd97da802003-01-28 05:48:29 +0000584 write(POP * (n+1) + get)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000585 return
586
Tim Peters1d63c9f2003-02-02 20:29:39 +0000587 # No recursion.
Tim Peters518df0d2003-01-28 01:00:38 +0000588 self.write(TUPLE)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000589 self.memoize(obj)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000590
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000591 dispatch[TupleType] = save_tuple
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000592
Tim Petersa6ae9a22003-01-28 16:58:41 +0000593 # save_empty_tuple() isn't used by anything in Python 2.3. However, I
594 # found a Pickler subclass in Zope3 that calls it, so it's not harmless
595 # to remove it.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000596 def save_empty_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000597 self.write(EMPTY_TUPLE)
598
Guido van Rossum3a41c612003-01-28 15:10:22 +0000599 def save_list(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000600 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000601
Tim Petersc32d8242001-04-10 02:48:53 +0000602 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000603 write(EMPTY_LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000604 else: # proto 0 -- can't use EMPTY_LIST
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000605 write(MARK + LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000606
607 self.memoize(obj)
608 self._batch_appends(iter(obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000609
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000610 dispatch[ListType] = save_list
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000611
Tim Peters42f08ac2003-02-11 22:43:24 +0000612 # Keep in synch with cPickle's BATCHSIZE. Nothing will break if it gets
613 # out of synch, though.
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000614 _BATCHSIZE = 1000
615
616 def _batch_appends(self, items):
617 # Helper to batch up APPENDS sequences
618 save = self.save
619 write = self.write
620
621 if not self.bin:
622 for x in items:
623 save(x)
624 write(APPEND)
625 return
626
627 r = xrange(self._BATCHSIZE)
628 while items is not None:
629 tmp = []
630 for i in r:
631 try:
Guido van Rossum5aac4e62003-02-06 22:57:00 +0000632 x = items.next()
633 tmp.append(x)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000634 except StopIteration:
635 items = None
636 break
637 n = len(tmp)
638 if n > 1:
639 write(MARK)
640 for x in tmp:
641 save(x)
642 write(APPENDS)
643 elif n:
644 save(tmp[0])
645 write(APPEND)
646 # else tmp is empty, and we're done
647
Guido van Rossum3a41c612003-01-28 15:10:22 +0000648 def save_dict(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000649 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000650
Tim Petersc32d8242001-04-10 02:48:53 +0000651 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000652 write(EMPTY_DICT)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000653 else: # proto 0 -- can't use EMPTY_DICT
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000654 write(MARK + DICT)
655
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000656 self.memoize(obj)
657 self._batch_setitems(obj.iteritems())
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000658
Raymond Hettingerfe59dc12005-02-07 15:28:45 +0000659 dispatch[DictionaryType] = save_dict
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000660 if not PyStringMap is None:
661 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000662
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000663 def _batch_setitems(self, items):
664 # Helper to batch up SETITEMS sequences; proto >= 1 only
665 save = self.save
666 write = self.write
667
668 if not self.bin:
669 for k, v in items:
670 save(k)
671 save(v)
672 write(SETITEM)
673 return
674
675 r = xrange(self._BATCHSIZE)
676 while items is not None:
677 tmp = []
678 for i in r:
679 try:
680 tmp.append(items.next())
681 except StopIteration:
682 items = None
683 break
684 n = len(tmp)
685 if n > 1:
686 write(MARK)
687 for k, v in tmp:
688 save(k)
689 save(v)
690 write(SETITEMS)
691 elif n:
692 k, v = tmp[0]
693 save(k)
694 save(v)
695 write(SETITEM)
696 # else tmp is empty, and we're done
697
Guido van Rossum3a41c612003-01-28 15:10:22 +0000698 def save_inst(self, obj):
699 cls = obj.__class__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000700
701 memo = self.memo
702 write = self.write
703 save = self.save
704
Guido van Rossum3a41c612003-01-28 15:10:22 +0000705 if hasattr(obj, '__getinitargs__'):
706 args = obj.__getinitargs__()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000707 len(args) # XXX Assert it's a sequence
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000708 _keep_alive(args, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000709 else:
710 args = ()
711
712 write(MARK)
713
Tim Petersc32d8242001-04-10 02:48:53 +0000714 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000715 save(cls)
Tim Peters3b769832003-01-28 03:51:36 +0000716 for arg in args:
717 save(arg)
718 write(OBJ)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000719 else:
Tim Peters3b769832003-01-28 03:51:36 +0000720 for arg in args:
721 save(arg)
722 write(INST + cls.__module__ + '\n' + cls.__name__ + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000723
Guido van Rossum3a41c612003-01-28 15:10:22 +0000724 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000725
726 try:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000727 getstate = obj.__getstate__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000728 except AttributeError:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000729 stuff = obj.__dict__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000730 else:
731 stuff = getstate()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000732 _keep_alive(stuff, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000733 save(stuff)
734 write(BUILD)
Tim Peters3b769832003-01-28 03:51:36 +0000735
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000736 dispatch[InstanceType] = save_inst
737
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000738 def save_global(self, obj, name=None, pack=struct.pack):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000739 write = self.write
740 memo = self.memo
741
Tim Petersc32d8242001-04-10 02:48:53 +0000742 if name is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000743 name = obj.__name__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000744
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000745 module = getattr(obj, "__module__", None)
746 if module is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000747 module = whichmodule(obj, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000748
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000749 try:
750 __import__(module)
751 mod = sys.modules[module]
752 klass = getattr(mod, name)
753 except (ImportError, KeyError, AttributeError):
754 raise PicklingError(
755 "Can't pickle %r: it's not found as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000756 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000757 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000758 if klass is not obj:
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000759 raise PicklingError(
760 "Can't pickle %r: it's not the same object as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000761 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000762
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000763 if self.proto >= 2:
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000764 code = _extension_registry.get((module, name))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000765 if code:
766 assert code > 0
767 if code <= 0xff:
768 write(EXT1 + chr(code))
769 elif code <= 0xffff:
Guido van Rossumba884f32003-01-29 20:14:23 +0000770 write("%c%c%c" % (EXT2, code&0xff, code>>8))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000771 else:
772 write(EXT4 + pack("<i", code))
773 return
774
Tim Peters518df0d2003-01-28 01:00:38 +0000775 write(GLOBAL + module + '\n' + name + '\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000776 self.memoize(obj)
Tim Peters3b769832003-01-28 03:51:36 +0000777
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000778 dispatch[ClassType] = save_global
779 dispatch[FunctionType] = save_global
780 dispatch[BuiltinFunctionType] = save_global
Alexandre Vassalottia2934282013-11-30 16:52:03 -0800781
782 def save_type(self, obj):
783 if obj is type(None):
784 return self.save_reduce(type, (None,), obj=obj)
785 elif obj is type(NotImplemented):
786 return self.save_reduce(type, (NotImplemented,), obj=obj)
787 elif obj is type(Ellipsis):
788 return self.save_reduce(type, (Ellipsis,), obj=obj)
789 return self.save_global(obj)
790
791 dispatch[TypeType] = save_type
792
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000793
Guido van Rossum1be31752003-01-28 15:19:53 +0000794# Pickling helpers
Guido van Rossuma48061a1995-01-10 00:31:14 +0000795
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000796def _keep_alive(x, memo):
797 """Keeps a reference to the object x in the memo.
798
799 Because we remember objects by their id, we have
800 to assure that possibly temporary objects are kept
801 alive by referencing them.
802 We store a reference at the id of the memo, which should
803 normally not be used unless someone tries to deepcopy
804 the memo itself...
805 """
806 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000807 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000808 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000809 # aha, this is the first one :-)
810 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000811
812
Tim Petersc0c12b52003-01-29 00:56:17 +0000813# A cache for whichmodule(), mapping a function object to the name of
814# the module in which the function was found.
815
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000816classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000817
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000818def whichmodule(func, funcname):
819 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000820
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000821 Search sys.modules for the module.
822 Cache in classmap.
823 Return a module name.
Tim Petersc0c12b52003-01-29 00:56:17 +0000824 If the function cannot be found, return "__main__".
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000825 """
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000826 # Python functions should always get an __module__ from their globals.
827 mod = getattr(func, "__module__", None)
828 if mod is not None:
829 return mod
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000830 if func in classmap:
831 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000832
833 for name, module in sys.modules.items():
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000834 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000835 continue # skip dummy package entries
Jeremy Hyltoncc1fccb2003-02-06 16:23:01 +0000836 if name != '__main__' and getattr(module, funcname, None) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000837 break
838 else:
839 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000840 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000841 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000842
843
Guido van Rossum1be31752003-01-28 15:19:53 +0000844# Unpickling machinery
845
Guido van Rossuma48061a1995-01-10 00:31:14 +0000846class Unpickler:
847
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000848 def __init__(self, file):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000849 """This takes a file-like object for reading a pickle data stream.
850
Tim Peters5bd2a792003-02-01 16:45:06 +0000851 The protocol version of the pickle is detected automatically, so no
852 proto argument is needed.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000853
854 The file-like object must have two methods, a read() method that
855 takes an integer argument, and a readline() method that requires no
856 arguments. Both methods should return a string. Thus file-like
857 object can be a file object opened for reading, a StringIO object,
858 or any other custom object that meets this interface.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000859 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000860 self.readline = file.readline
861 self.read = file.read
862 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000863
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000864 def load(self):
Guido van Rossum3a41c612003-01-28 15:10:22 +0000865 """Read a pickled object representation from the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000866
Guido van Rossum3a41c612003-01-28 15:10:22 +0000867 Return the reconstituted object hierarchy specified in the file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000868 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000869 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000870 self.stack = []
871 self.append = self.stack.append
872 read = self.read
873 dispatch = self.dispatch
874 try:
875 while 1:
876 key = read(1)
877 dispatch[key](self)
Guido van Rossumff871742000-12-13 18:11:56 +0000878 except _Stop, stopinst:
879 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000880
Tim Petersc23d18a2003-01-28 01:41:51 +0000881 # Return largest index k such that self.stack[k] is self.mark.
882 # If the stack doesn't contain a mark, eventually raises IndexError.
883 # This could be sped by maintaining another stack, of indices at which
884 # the mark appears. For that matter, the latter stack would suffice,
885 # and we wouldn't need to push mark objects on self.stack at all.
886 # Doing so is probably a good thing, though, since if the pickle is
887 # corrupt (or hostile) we may get a clue from finding self.mark embedded
888 # in unpickled objects.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000889 def marker(self):
890 stack = self.stack
891 mark = self.mark
892 k = len(stack)-1
893 while stack[k] is not mark: k = k-1
894 return k
895
896 dispatch = {}
897
898 def load_eof(self):
899 raise EOFError
900 dispatch[''] = load_eof
901
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000902 def load_proto(self):
903 proto = ord(self.read(1))
904 if not 0 <= proto <= 2:
905 raise ValueError, "unsupported pickle protocol: %d" % proto
906 dispatch[PROTO] = load_proto
907
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000908 def load_persid(self):
909 pid = self.readline()[:-1]
910 self.append(self.persistent_load(pid))
911 dispatch[PERSID] = load_persid
912
913 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000914 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000915 self.append(self.persistent_load(pid))
916 dispatch[BINPERSID] = load_binpersid
917
918 def load_none(self):
919 self.append(None)
920 dispatch[NONE] = load_none
921
Guido van Rossum7d97d312003-01-28 04:25:27 +0000922 def load_false(self):
923 self.append(False)
924 dispatch[NEWFALSE] = load_false
925
926 def load_true(self):
927 self.append(True)
928 dispatch[NEWTRUE] = load_true
929
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000930 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000931 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000932 if data == FALSE[1:]:
933 val = False
934 elif data == TRUE[1:]:
935 val = True
936 else:
937 try:
938 val = int(data)
939 except ValueError:
940 val = long(data)
941 self.append(val)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000942 dispatch[INT] = load_int
943
944 def load_binint(self):
945 self.append(mloads('i' + self.read(4)))
946 dispatch[BININT] = load_binint
947
948 def load_binint1(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000949 self.append(ord(self.read(1)))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000950 dispatch[BININT1] = load_binint1
951
952 def load_binint2(self):
953 self.append(mloads('i' + self.read(2) + '\000\000'))
954 dispatch[BININT2] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000955
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000956 def load_long(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000957 self.append(long(self.readline()[:-1], 0))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000958 dispatch[LONG] = load_long
959
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000960 def load_long1(self):
961 n = ord(self.read(1))
962 bytes = self.read(n)
Tim Petersee1a53c2003-02-02 02:57:53 +0000963 self.append(decode_long(bytes))
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000964 dispatch[LONG1] = load_long1
965
966 def load_long4(self):
967 n = mloads('i' + self.read(4))
968 bytes = self.read(n)
Tim Petersee1a53c2003-02-02 02:57:53 +0000969 self.append(decode_long(bytes))
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000970 dispatch[LONG4] = load_long4
971
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000972 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000973 self.append(float(self.readline()[:-1]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000974 dispatch[FLOAT] = load_float
975
Guido van Rossumd3703791998-10-22 20:15:36 +0000976 def load_binfloat(self, unpack=struct.unpack):
977 self.append(unpack('>d', self.read(8))[0])
978 dispatch[BINFLOAT] = load_binfloat
979
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000980 def load_string(self):
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000981 rep = self.readline()[:-1]
Tim Petersad5a7712003-01-28 16:23:33 +0000982 for q in "\"'": # double or single quote
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000983 if rep.startswith(q):
Antoine Pitroube929712013-04-15 21:35:25 +0200984 if len(rep) < 2 or not rep.endswith(q):
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000985 raise ValueError, "insecure string pickle"
986 rep = rep[len(q):-len(q)]
987 break
988 else:
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000989 raise ValueError, "insecure string pickle"
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000990 self.append(rep.decode("string-escape"))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000991 dispatch[STRING] = load_string
992
993 def load_binstring(self):
994 len = mloads('i' + self.read(4))
995 self.append(self.read(len))
996 dispatch[BINSTRING] = load_binstring
997
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000998 def load_unicode(self):
999 self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
1000 dispatch[UNICODE] = load_unicode
1001
1002 def load_binunicode(self):
1003 len = mloads('i' + self.read(4))
1004 self.append(unicode(self.read(len),'utf-8'))
1005 dispatch[BINUNICODE] = load_binunicode
1006
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001007 def load_short_binstring(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001008 len = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001009 self.append(self.read(len))
1010 dispatch[SHORT_BINSTRING] = load_short_binstring
1011
1012 def load_tuple(self):
1013 k = self.marker()
1014 self.stack[k:] = [tuple(self.stack[k+1:])]
1015 dispatch[TUPLE] = load_tuple
1016
1017 def load_empty_tuple(self):
1018 self.stack.append(())
1019 dispatch[EMPTY_TUPLE] = load_empty_tuple
1020
Guido van Rossum44f0ea52003-01-28 04:14:51 +00001021 def load_tuple1(self):
1022 self.stack[-1] = (self.stack[-1],)
1023 dispatch[TUPLE1] = load_tuple1
1024
1025 def load_tuple2(self):
1026 self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
1027 dispatch[TUPLE2] = load_tuple2
1028
1029 def load_tuple3(self):
1030 self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
1031 dispatch[TUPLE3] = load_tuple3
1032
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001033 def load_empty_list(self):
1034 self.stack.append([])
1035 dispatch[EMPTY_LIST] = load_empty_list
1036
1037 def load_empty_dictionary(self):
1038 self.stack.append({})
1039 dispatch[EMPTY_DICT] = load_empty_dictionary
1040
1041 def load_list(self):
1042 k = self.marker()
1043 self.stack[k:] = [self.stack[k+1:]]
1044 dispatch[LIST] = load_list
1045
1046 def load_dict(self):
1047 k = self.marker()
1048 d = {}
1049 items = self.stack[k+1:]
1050 for i in range(0, len(items), 2):
1051 key = items[i]
1052 value = items[i+1]
1053 d[key] = value
1054 self.stack[k:] = [d]
1055 dispatch[DICT] = load_dict
1056
Tim Petersd01c1e92003-01-30 15:41:46 +00001057 # INST and OBJ differ only in how they get a class object. It's not
1058 # only sensible to do the rest in a common routine, the two routines
1059 # previously diverged and grew different bugs.
1060 # klass is the class to instantiate, and k points to the topmost mark
1061 # object, following which are the arguments for klass.__init__.
1062 def _instantiate(self, klass, k):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001063 args = tuple(self.stack[k+1:])
1064 del self.stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001065 instantiated = 0
Tim Petersd01c1e92003-01-30 15:41:46 +00001066 if (not args and
1067 type(klass) is ClassType and
1068 not hasattr(klass, "__getinitargs__")):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001069 try:
1070 value = _EmptyClass()
1071 value.__class__ = klass
Guido van Rossumb19e2a31998-04-13 18:08:45 +00001072 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001073 except RuntimeError:
1074 # In restricted execution, assignment to inst.__class__ is
1075 # prohibited
1076 pass
1077 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +00001078 try:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001079 value = klass(*args)
Guido van Rossum743d17e1998-09-15 20:25:57 +00001080 except TypeError, err:
1081 raise TypeError, "in constructor for %s: %s" % (
1082 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001083 self.append(value)
Tim Petersd01c1e92003-01-30 15:41:46 +00001084
1085 def load_inst(self):
1086 module = self.readline()[:-1]
1087 name = self.readline()[:-1]
1088 klass = self.find_class(module, name)
1089 self._instantiate(klass, self.marker())
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001090 dispatch[INST] = load_inst
1091
1092 def load_obj(self):
Tim Petersd01c1e92003-01-30 15:41:46 +00001093 # Stack is ... markobject classobject arg1 arg2 ...
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001094 k = self.marker()
Tim Petersd01c1e92003-01-30 15:41:46 +00001095 klass = self.stack.pop(k+1)
1096 self._instantiate(klass, k)
Tim Peters2344fae2001-01-15 00:50:52 +00001097 dispatch[OBJ] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001098
Guido van Rossum3a41c612003-01-28 15:10:22 +00001099 def load_newobj(self):
1100 args = self.stack.pop()
1101 cls = self.stack[-1]
1102 obj = cls.__new__(cls, *args)
Guido van Rossum533dbcf2003-01-28 17:55:05 +00001103 self.stack[-1] = obj
Guido van Rossum3a41c612003-01-28 15:10:22 +00001104 dispatch[NEWOBJ] = load_newobj
1105
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001106 def load_global(self):
1107 module = self.readline()[:-1]
1108 name = self.readline()[:-1]
1109 klass = self.find_class(module, name)
1110 self.append(klass)
1111 dispatch[GLOBAL] = load_global
1112
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001113 def load_ext1(self):
1114 code = ord(self.read(1))
1115 self.get_extension(code)
1116 dispatch[EXT1] = load_ext1
1117
1118 def load_ext2(self):
1119 code = mloads('i' + self.read(2) + '\000\000')
1120 self.get_extension(code)
1121 dispatch[EXT2] = load_ext2
1122
1123 def load_ext4(self):
1124 code = mloads('i' + self.read(4))
1125 self.get_extension(code)
1126 dispatch[EXT4] = load_ext4
1127
1128 def get_extension(self, code):
1129 nil = []
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001130 obj = _extension_cache.get(code, nil)
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001131 if obj is not nil:
1132 self.append(obj)
1133 return
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001134 key = _inverted_registry.get(code)
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001135 if not key:
1136 raise ValueError("unregistered extension code %d" % code)
1137 obj = self.find_class(*key)
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001138 _extension_cache[code] = obj
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001139 self.append(obj)
1140
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001141 def find_class(self, module, name):
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001142 # Subclasses may override this
Barry Warsawbf4d9592001-11-15 23:42:58 +00001143 __import__(module)
1144 mod = sys.modules[module]
1145 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001146 return klass
1147
1148 def load_reduce(self):
1149 stack = self.stack
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001150 args = stack.pop()
1151 func = stack[-1]
Raymond Hettingera6b45cc2004-12-07 07:05:57 +00001152 value = func(*args)
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001153 stack[-1] = value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001154 dispatch[REDUCE] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +00001155
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001156 def load_pop(self):
1157 del self.stack[-1]
1158 dispatch[POP] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +00001159
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001160 def load_pop_mark(self):
1161 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001162 del self.stack[k:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001163 dispatch[POP_MARK] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001164
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001165 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +00001166 self.append(self.stack[-1])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001167 dispatch[DUP] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +00001168
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001169 def load_get(self):
1170 self.append(self.memo[self.readline()[:-1]])
1171 dispatch[GET] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +00001172
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001173 def load_binget(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001174 i = ord(self.read(1))
Walter Dörwald70a6b492004-02-12 17:35:32 +00001175 self.append(self.memo[repr(i)])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001176 dispatch[BINGET] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001177
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001178 def load_long_binget(self):
1179 i = mloads('i' + self.read(4))
Walter Dörwald70a6b492004-02-12 17:35:32 +00001180 self.append(self.memo[repr(i)])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001181 dispatch[LONG_BINGET] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001182
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001183 def load_put(self):
1184 self.memo[self.readline()[:-1]] = self.stack[-1]
1185 dispatch[PUT] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +00001186
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001187 def load_binput(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001188 i = ord(self.read(1))
Walter Dörwald70a6b492004-02-12 17:35:32 +00001189 self.memo[repr(i)] = self.stack[-1]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001190 dispatch[BINPUT] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001191
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001192 def load_long_binput(self):
1193 i = mloads('i' + self.read(4))
Walter Dörwald70a6b492004-02-12 17:35:32 +00001194 self.memo[repr(i)] = self.stack[-1]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001195 dispatch[LONG_BINPUT] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001196
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001197 def load_append(self):
1198 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001199 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001200 list = stack[-1]
1201 list.append(value)
1202 dispatch[APPEND] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +00001203
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001204 def load_appends(self):
1205 stack = self.stack
1206 mark = self.marker()
1207 list = stack[mark - 1]
Tim Peters209ad952003-01-28 01:44:45 +00001208 list.extend(stack[mark + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001209 del stack[mark:]
1210 dispatch[APPENDS] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +00001211
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001212 def load_setitem(self):
1213 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001214 value = stack.pop()
1215 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001216 dict = stack[-1]
1217 dict[key] = value
1218 dispatch[SETITEM] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001219
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001220 def load_setitems(self):
1221 stack = self.stack
1222 mark = self.marker()
1223 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001224 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001225 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001226
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001227 del stack[mark:]
1228 dispatch[SETITEMS] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001229
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001230 def load_build(self):
1231 stack = self.stack
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001232 state = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001233 inst = stack[-1]
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001234 setstate = getattr(inst, "__setstate__", None)
1235 if setstate:
1236 setstate(state)
1237 return
1238 slotstate = None
1239 if isinstance(state, tuple) and len(state) == 2:
1240 state, slotstate = state
1241 if state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001242 try:
Antoine Pitrou74309892009-05-02 21:13:23 +00001243 d = inst.__dict__
1244 try:
1245 for k, v in state.iteritems():
1246 d[intern(k)] = v
1247 # keys in state don't have to be strings
1248 # don't blow up, but don't go out of our way
1249 except TypeError:
1250 d.update(state)
1251
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001252 except RuntimeError:
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001253 # XXX In restricted execution, the instance's __dict__
1254 # is not accessible. Use the old way of unpickling
1255 # the instance variables. This is a semantic
1256 # difference when unpickling in restricted
1257 # vs. unrestricted modes.
Tim Peters080c88b2003-02-15 03:01:11 +00001258 # Note, however, that cPickle has never tried to do the
1259 # .update() business, and always uses
1260 # PyObject_SetItem(inst.__dict__, key, value) in a
1261 # loop over state.items().
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001262 for k, v in state.items():
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001263 setattr(inst, k, v)
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001264 if slotstate:
1265 for k, v in slotstate.items():
1266 setattr(inst, k, v)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001267 dispatch[BUILD] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001268
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001269 def load_mark(self):
1270 self.append(self.mark)
1271 dispatch[MARK] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001272
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001273 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001274 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001275 raise _Stop(value)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001276 dispatch[STOP] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001277
Guido van Rossume467be61997-12-05 19:42:42 +00001278# Helper class for load_inst/load_obj
1279
1280class _EmptyClass:
1281 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001282
Tim Peters91149822003-01-31 03:43:58 +00001283# Encode/decode longs in linear time.
1284
1285import binascii as _binascii
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001286
1287def encode_long(x):
Tim Peters91149822003-01-31 03:43:58 +00001288 r"""Encode a long to a two's complement little-endian binary string.
Tim Peters4b23f2b2003-01-31 16:43:39 +00001289 Note that 0L is a special case, returning an empty string, to save a
1290 byte in the LONG1 pickling context.
1291
1292 >>> encode_long(0L)
1293 ''
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001294 >>> encode_long(255L)
1295 '\xff\x00'
1296 >>> encode_long(32767L)
1297 '\xff\x7f'
1298 >>> encode_long(-256L)
1299 '\x00\xff'
1300 >>> encode_long(-32768L)
1301 '\x00\x80'
1302 >>> encode_long(-128L)
1303 '\x80'
1304 >>> encode_long(127L)
1305 '\x7f'
1306 >>>
1307 """
Tim Peters91149822003-01-31 03:43:58 +00001308
1309 if x == 0:
Tim Peters4b23f2b2003-01-31 16:43:39 +00001310 return ''
Tim Peters91149822003-01-31 03:43:58 +00001311 if x > 0:
1312 ashex = hex(x)
1313 assert ashex.startswith("0x")
1314 njunkchars = 2 + ashex.endswith('L')
1315 nibbles = len(ashex) - njunkchars
1316 if nibbles & 1:
1317 # need an even # of nibbles for unhexlify
1318 ashex = "0x0" + ashex[2:]
Tim Peters4b23f2b2003-01-31 16:43:39 +00001319 elif int(ashex[2], 16) >= 8:
Tim Peters91149822003-01-31 03:43:58 +00001320 # "looks negative", so need a byte of sign bits
1321 ashex = "0x00" + ashex[2:]
1322 else:
1323 # Build the 256's-complement: (1L << nbytes) + x. The trick is
1324 # to find the number of bytes in linear time (although that should
1325 # really be a constant-time task).
1326 ashex = hex(-x)
1327 assert ashex.startswith("0x")
1328 njunkchars = 2 + ashex.endswith('L')
1329 nibbles = len(ashex) - njunkchars
1330 if nibbles & 1:
Tim Petersee1a53c2003-02-02 02:57:53 +00001331 # Extend to a full byte.
Tim Peters91149822003-01-31 03:43:58 +00001332 nibbles += 1
Tim Peters4b23f2b2003-01-31 16:43:39 +00001333 nbits = nibbles * 4
1334 x += 1L << nbits
Tim Peters91149822003-01-31 03:43:58 +00001335 assert x > 0
1336 ashex = hex(x)
Tim Petersee1a53c2003-02-02 02:57:53 +00001337 njunkchars = 2 + ashex.endswith('L')
1338 newnibbles = len(ashex) - njunkchars
1339 if newnibbles < nibbles:
1340 ashex = "0x" + "0" * (nibbles - newnibbles) + ashex[2:]
1341 if int(ashex[2], 16) < 8:
Tim Peters91149822003-01-31 03:43:58 +00001342 # "looks positive", so need a byte of sign bits
Tim Petersee1a53c2003-02-02 02:57:53 +00001343 ashex = "0xff" + ashex[2:]
Tim Peters91149822003-01-31 03:43:58 +00001344
1345 if ashex.endswith('L'):
1346 ashex = ashex[2:-1]
1347 else:
1348 ashex = ashex[2:]
Tim Petersee1a53c2003-02-02 02:57:53 +00001349 assert len(ashex) & 1 == 0, (x, ashex)
Tim Peters91149822003-01-31 03:43:58 +00001350 binary = _binascii.unhexlify(ashex)
1351 return binary[::-1]
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001352
1353def decode_long(data):
1354 r"""Decode a long from a two's complement little-endian binary string.
Tim Peters4b23f2b2003-01-31 16:43:39 +00001355
1356 >>> decode_long('')
1357 0L
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001358 >>> decode_long("\xff\x00")
1359 255L
1360 >>> decode_long("\xff\x7f")
1361 32767L
1362 >>> decode_long("\x00\xff")
1363 -256L
1364 >>> decode_long("\x00\x80")
1365 -32768L
1366 >>> decode_long("\x80")
1367 -128L
1368 >>> decode_long("\x7f")
1369 127L
1370 """
Tim Peters91149822003-01-31 03:43:58 +00001371
Tim Peters4b23f2b2003-01-31 16:43:39 +00001372 nbytes = len(data)
1373 if nbytes == 0:
1374 return 0L
Tim Peters91149822003-01-31 03:43:58 +00001375 ashex = _binascii.hexlify(data[::-1])
Tim Petersbf2674b2003-02-02 07:51:32 +00001376 n = long(ashex, 16) # quadratic time before Python 2.3; linear now
Tim Peters91149822003-01-31 03:43:58 +00001377 if data[-1] >= '\x80':
Tim Peters4b23f2b2003-01-31 16:43:39 +00001378 n -= 1L << (nbytes * 8)
Tim Peters91149822003-01-31 03:43:58 +00001379 return n
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001380
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001381# Shorthands
1382
Jeremy Hyltonabe2c622001-10-15 21:29:28 +00001383try:
1384 from cStringIO import StringIO
1385except ImportError:
1386 from StringIO import StringIO
Guido van Rossumc7c5e691996-07-22 22:26:07 +00001387
Raymond Hettinger3489cad2004-12-05 05:20:42 +00001388def dump(obj, file, protocol=None):
1389 Pickler(file, protocol).dump(obj)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001390
Raymond Hettinger3489cad2004-12-05 05:20:42 +00001391def dumps(obj, protocol=None):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001392 file = StringIO()
Raymond Hettinger3489cad2004-12-05 05:20:42 +00001393 Pickler(file, protocol).dump(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001394 return file.getvalue()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001395
1396def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001397 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001398
1399def loads(str):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001400 file = StringIO(str)
1401 return Unpickler(file).load()
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001402
1403# Doctest
1404
1405def _test():
1406 import doctest
1407 return doctest.testmod()
1408
1409if __name__ == "__main__":
1410 _test()