blob: 168865df92439dc336f1f1951232a1ed0d1a8270 [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
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00003See module copyreg for a mechanism for registering custom picklers.
Tim Peters22a449a2003-01-27 20:16:36 +00004See module pickletools source for extensive comments.
Guido van Rossuma48061a1995-01-10 00:31:14 +00005
Guido van Rossume467be61997-12-05 19:42:42 +00006Classes:
Guido van Rossuma48061a1995-01-10 00:31:14 +00007
Guido van Rossume467be61997-12-05 19:42:42 +00008 Pickler
9 Unpickler
Guido van Rossuma48061a1995-01-10 00:31:14 +000010
Guido van Rossume467be61997-12-05 19:42:42 +000011Functions:
Guido van Rossuma48061a1995-01-10 00:31:14 +000012
Guido van Rossume467be61997-12-05 19:42:42 +000013 dump(object, file)
14 dumps(object) -> string
15 load(file) -> object
16 loads(string) -> object
Guido van Rossuma48061a1995-01-10 00:31:14 +000017
Guido van Rossume467be61997-12-05 19:42:42 +000018Misc variables:
Guido van Rossuma48061a1995-01-10 00:31:14 +000019
Fred Drakefe82acc1998-02-13 03:24:48 +000020 __version__
Guido van Rossume467be61997-12-05 19:42:42 +000021 format_version
22 compatible_formats
Guido van Rossuma48061a1995-01-10 00:31:14 +000023
Guido van Rossuma48061a1995-01-10 00:31:14 +000024"""
25
Guido van Rossum13257902007-06-07 23:15:56 +000026from types import FunctionType, BuiltinFunctionType
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +000027from copyreg import dispatch_table
28from copyreg import _extension_registry, _inverted_registry, _extension_cache
Guido van Rossumd3703791998-10-22 20:15:36 +000029import marshal
30import sys
31import struct
Skip Montanaro23bafc62001-02-18 03:10:09 +000032import re
Guido van Rossum2e6a4b32007-05-04 19:56:22 +000033import io
Walter Dörwald42748a82007-06-12 16:40:17 +000034import codecs
Antoine Pitroud9dfaa92009-06-04 20:32:06 +000035import _compat_pickle
Guido van Rossuma48061a1995-01-10 00:31:14 +000036
Skip Montanaro352674d2001-02-07 23:14:30 +000037__all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler",
38 "Unpickler", "dump", "dumps", "load", "loads"]
39
Guido van Rossum98297ee2007-11-06 21:34:58 +000040# Shortcut for use in isinstance testing
Alexandre Vassalotti8cb02b62008-05-03 01:42:49 +000041bytes_types = (bytes, bytearray)
Guido van Rossum98297ee2007-11-06 21:34:58 +000042
Tim Petersc0c12b52003-01-29 00:56:17 +000043# These are purely informational; no code uses these.
Guido van Rossumf4169812008-03-17 22:56:06 +000044format_version = "3.0" # File format version we write
Guido van Rossumf29d3d62003-01-27 22:47:53 +000045compatible_formats = ["1.0", # Original protocol 0
Guido van Rossumbc64e222003-01-28 16:34:19 +000046 "1.1", # Protocol 0 with INST added
Guido van Rossumf29d3d62003-01-27 22:47:53 +000047 "1.2", # Original protocol 1
48 "1.3", # Protocol 1 with BINFLOAT added
49 "2.0", # Protocol 2
Guido van Rossumf4169812008-03-17 22:56:06 +000050 "3.0", # Protocol 3
Guido van Rossumf29d3d62003-01-27 22:47:53 +000051 ] # Old format versions we can read
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000052
Guido van Rossum99603b02007-07-20 00:22:32 +000053# This is the highest protocol number we know how to read.
Guido van Rossumf4169812008-03-17 22:56:06 +000054HIGHEST_PROTOCOL = 3
Tim Peters8587b3c2003-02-13 15:44:41 +000055
Guido van Rossum2e6a4b32007-05-04 19:56:22 +000056# The protocol we write by default. May be less than HIGHEST_PROTOCOL.
Guido van Rossumf4169812008-03-17 22:56:06 +000057# We intentionally write a protocol that Python 2.x cannot read;
58# there are too many issues with that.
59DEFAULT_PROTOCOL = 3
Guido van Rossum2e6a4b32007-05-04 19:56:22 +000060
Guido van Rossume0b90422003-01-28 03:17:21 +000061# Why use struct.pack() for pickling but marshal.loads() for
Tim Petersc0c12b52003-01-29 00:56:17 +000062# unpickling? struct.pack() is 40% faster than marshal.dumps(), but
Guido van Rossume0b90422003-01-28 03:17:21 +000063# marshal.loads() is twice as fast as struct.unpack()!
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000064mloads = marshal.loads
Guido van Rossum0c891ce1995-03-14 15:09:05 +000065
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000066class PickleError(Exception):
Neal Norwitzefbb67b2002-05-30 12:12:04 +000067 """A common base class for the other pickling exceptions."""
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000068 pass
69
70class PicklingError(PickleError):
71 """This exception is raised when an unpicklable object is passed to the
72 dump() method.
73
74 """
75 pass
76
77class UnpicklingError(PickleError):
78 """This exception is raised when there is a problem unpickling an object,
79 such as a security violation.
80
81 Note that other exceptions may also be raised during unpickling, including
82 (but not necessarily limited to) AttributeError, EOFError, ImportError,
83 and IndexError.
84
85 """
86 pass
Guido van Rossum7849da81995-03-09 14:08:35 +000087
Tim Petersc0c12b52003-01-29 00:56:17 +000088# An instance of _Stop is raised by Unpickler.load_stop() in response to
89# the STOP opcode, passing the object that is the result of unpickling.
Guido van Rossumff871742000-12-13 18:11:56 +000090class _Stop(Exception):
91 def __init__(self, value):
92 self.value = value
93
Guido van Rossum533dbcf2003-01-28 17:55:05 +000094# Jython has PyStringMap; it's a dict subclass with string keys
Jeremy Hylton2b9d0291998-05-27 22:38:22 +000095try:
96 from org.python.core import PyStringMap
97except ImportError:
98 PyStringMap = None
99
Tim Peters22a449a2003-01-27 20:16:36 +0000100# Pickle opcodes. See pickletools.py for extensive docs. The listing
101# here is in kind-of alphabetical order of 1-character pickle code.
102# pickletools groups them by purpose.
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000103
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000104MARK = b'(' # push special markobject on stack
105STOP = b'.' # every pickle ends with STOP
106POP = b'0' # discard topmost stack item
107POP_MARK = b'1' # discard stack top through topmost markobject
108DUP = b'2' # duplicate top stack item
109FLOAT = b'F' # push float object; decimal string argument
110INT = b'I' # push integer or bool; decimal string argument
111BININT = b'J' # push four-byte signed int
112BININT1 = b'K' # push 1-byte unsigned int
113LONG = b'L' # push long; decimal string argument
114BININT2 = b'M' # push 2-byte unsigned int
115NONE = b'N' # push None
116PERSID = b'P' # push persistent object; id is taken from string arg
117BINPERSID = b'Q' # " " " ; " " " " stack
118REDUCE = b'R' # apply callable to argtuple, both on stack
119STRING = b'S' # push string; NL-terminated string argument
120BINSTRING = b'T' # push string; counted binary string argument
121SHORT_BINSTRING= b'U' # " " ; " " " " < 256 bytes
122UNICODE = b'V' # push Unicode string; raw-unicode-escaped'd argument
123BINUNICODE = b'X' # " " " ; counted UTF-8 string argument
124APPEND = b'a' # append stack top to list below it
125BUILD = b'b' # call __setstate__ or __dict__.update()
126GLOBAL = b'c' # push self.find_class(modname, name); 2 string args
127DICT = b'd' # build a dict from stack items
128EMPTY_DICT = b'}' # push empty dict
129APPENDS = b'e' # extend list on stack by topmost stack slice
130GET = b'g' # push item from memo on stack; index is string arg
131BINGET = b'h' # " " " " " " ; " " 1-byte arg
132INST = b'i' # build & push class instance
133LONG_BINGET = b'j' # push item from memo on stack; index is 4-byte arg
134LIST = b'l' # build list from topmost stack items
135EMPTY_LIST = b']' # push empty list
136OBJ = b'o' # build & push class instance
137PUT = b'p' # store stack top in memo; index is string arg
138BINPUT = b'q' # " " " " " ; " " 1-byte arg
139LONG_BINPUT = b'r' # " " " " " ; " " 4-byte arg
140SETITEM = b's' # add key+value pair to dict
141TUPLE = b't' # build tuple from topmost stack items
142EMPTY_TUPLE = b')' # push empty tuple
143SETITEMS = b'u' # modify dict by adding topmost key+value pairs
144BINFLOAT = b'G' # push float; arg is 8-byte float encoding
Tim Peters22a449a2003-01-27 20:16:36 +0000145
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000146TRUE = b'I01\n' # not an opcode; see INT docs in pickletools.py
147FALSE = b'I00\n' # not an opcode; see INT docs in pickletools.py
Guido van Rossum77f6a652002-04-03 22:41:51 +0000148
Guido van Rossum586c9e82003-01-29 06:16:12 +0000149# Protocol 2
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000150
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000151PROTO = b'\x80' # identify pickle protocol
152NEWOBJ = b'\x81' # build object by applying cls.__new__ to argtuple
153EXT1 = b'\x82' # push object from extension registry; 1-byte index
154EXT2 = b'\x83' # ditto, but 2-byte index
155EXT4 = b'\x84' # ditto, but 4-byte index
156TUPLE1 = b'\x85' # build 1-tuple from stack top
157TUPLE2 = b'\x86' # build 2-tuple from two topmost stack items
158TUPLE3 = b'\x87' # build 3-tuple from three topmost stack items
159NEWTRUE = b'\x88' # push True
160NEWFALSE = b'\x89' # push False
161LONG1 = b'\x8a' # push long from < 256 bytes
162LONG4 = b'\x8b' # push really big long
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000163
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000164_tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3]
165
Guido van Rossumf4169812008-03-17 22:56:06 +0000166# Protocol 3 (Python 3.x)
167
168BINBYTES = b'B' # push bytes; counted binary string argument
169SHORT_BINBYTES = b'C' # " " ; " " " " < 256 bytes
Guido van Rossuma48061a1995-01-10 00:31:14 +0000170
Skip Montanaro23bafc62001-02-18 03:10:09 +0000171__all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
172
Guido van Rossum1be31752003-01-28 15:19:53 +0000173# Pickling machinery
174
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000175class _Pickler:
Guido van Rossuma48061a1995-01-10 00:31:14 +0000176
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000177 def __init__(self, file, protocol=None, *, fix_imports=True):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000178 """This takes a binary file for writing a pickle data stream.
179
Guido van Rossumcf117b02003-02-09 17:19:41 +0000180 The optional protocol argument tells the pickler to use the
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000181 given protocol; supported protocols are 0, 1, 2, 3. The default
182 protocol is 3; a backward-incompatible protocol designed for
183 Python 3.0.
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000184
Guido van Rossum7eff63a2003-01-31 19:42:31 +0000185 Specifying a negative protocol version selects the highest
Tim Peters5bd2a792003-02-01 16:45:06 +0000186 protocol version supported. The higher the protocol used, the
187 more recent the version of Python needed to read the pickle
188 produced.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000189
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000190 The file argument must have a write() method that accepts a single
191 bytes argument. It can thus be a file object opened for binary
192 writing, a io.BytesIO instance, or any other custom object that
193 meets this interface.
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000194
195 If fix_imports is True and protocol is less than 3, pickle will try to
196 map the new Python 3.x names to the old module names used in Python
197 2.x, so that the pickle data stream is readable with Python 2.x.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000198 """
Guido van Rossumcf117b02003-02-09 17:19:41 +0000199 if protocol is None:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000200 protocol = DEFAULT_PROTOCOL
Guido van Rossumcf117b02003-02-09 17:19:41 +0000201 if protocol < 0:
Tim Peters8587b3c2003-02-13 15:44:41 +0000202 protocol = HIGHEST_PROTOCOL
203 elif not 0 <= protocol <= HIGHEST_PROTOCOL:
204 raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL)
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000205 try:
206 self.write = file.write
207 except AttributeError:
208 raise TypeError("file must have a 'write' attribute")
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000209 self.memo = {}
Guido van Rossumcf117b02003-02-09 17:19:41 +0000210 self.proto = int(protocol)
211 self.bin = protocol >= 1
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000212 self.fast = 0
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000213 self.fix_imports = fix_imports and protocol < 3
Guido van Rossuma48061a1995-01-10 00:31:14 +0000214
Fred Drake7f781c92002-05-01 20:33:53 +0000215 def clear_memo(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000216 """Clears the pickler's "memo".
217
218 The memo is the data structure that remembers which objects the
Tim Petersb377f8a2003-01-28 00:23:36 +0000219 pickler has already seen, so that shared or recursive objects are
220 pickled by reference and not by value. This method is useful when
221 re-using picklers.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000222
223 """
Fred Drake7f781c92002-05-01 20:33:53 +0000224 self.memo.clear()
225
Guido van Rossum3a41c612003-01-28 15:10:22 +0000226 def dump(self, obj):
Tim Peters5bd2a792003-02-01 16:45:06 +0000227 """Write a pickled representation of obj to the open file."""
Alexandre Vassalotti3cfcab92008-12-27 09:30:39 +0000228 # Check whether Pickler was initialized correctly. This is
229 # only needed to mimic the behavior of _pickle.Pickler.dump().
230 if not hasattr(self, "write"):
231 raise PicklingError("Pickler.__init__() was not called by "
232 "%s.__init__()" % (self.__class__.__name__,))
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000233 if self.proto >= 2:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000234 self.write(PROTO + bytes([self.proto]))
Guido van Rossum3a41c612003-01-28 15:10:22 +0000235 self.save(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000236 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000237
Jeremy Hylton3422c992003-01-24 19:29:52 +0000238 def memoize(self, obj):
239 """Store an object in the memo."""
240
Tim Peterse46b73f2003-01-27 21:22:10 +0000241 # The Pickler memo is a dictionary mapping object ids to 2-tuples
242 # that contain the Unpickler memo key and the object being memoized.
243 # The memo key is written to the pickle and will become
Jeremy Hylton3422c992003-01-24 19:29:52 +0000244 # the key in the Unpickler's memo. The object is stored in the
Tim Peterse46b73f2003-01-27 21:22:10 +0000245 # Pickler memo so that transient objects are kept alive during
246 # pickling.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000247
Tim Peterse46b73f2003-01-27 21:22:10 +0000248 # The use of the Unpickler memo length as the memo key is just a
249 # convention. The only requirement is that the memo values be unique.
250 # But there appears no advantage to any other scheme, and this
Tim Peterscbd0a322003-01-28 00:24:43 +0000251 # scheme allows the Unpickler memo to be implemented as a plain (but
Tim Peterse46b73f2003-01-27 21:22:10 +0000252 # growable) array, indexed by memo key.
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000253 if self.fast:
254 return
Guido van Rossum9b40e802003-01-30 06:37:41 +0000255 assert id(obj) not in self.memo
Jeremy Hylton3422c992003-01-24 19:29:52 +0000256 memo_len = len(self.memo)
257 self.write(self.put(memo_len))
Tim Peters518df0d2003-01-28 01:00:38 +0000258 self.memo[id(obj)] = memo_len, obj
Jeremy Hylton3422c992003-01-24 19:29:52 +0000259
Tim Petersbb38e302003-01-27 21:25:41 +0000260 # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000261 def put(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000262 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000263 if i < 256:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000264 return BINPUT + bytes([i])
Guido van Rossum5c938d02003-01-28 03:03:08 +0000265 else:
Antoine Pitroubf6ecf92012-11-24 20:40:21 +0100266 return LONG_BINPUT + pack("<I", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000267
Guido van Rossum39478e82007-08-27 17:23:59 +0000268 return PUT + repr(i).encode("ascii") + b'\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000269
Tim Petersbb38e302003-01-27 21:25:41 +0000270 # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000271 def get(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000272 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000273 if i < 256:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000274 return BINGET + bytes([i])
Guido van Rossum5c938d02003-01-28 03:03:08 +0000275 else:
Antoine Pitroubf6ecf92012-11-24 20:40:21 +0100276 return LONG_BINGET + pack("<I", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000277
Guido van Rossum39478e82007-08-27 17:23:59 +0000278 return GET + repr(i).encode("ascii") + b'\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000279
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000280 def save(self, obj, save_persistent_id=True):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000281 # Check for persistent id (defined by a subclass)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000282 pid = self.persistent_id(obj)
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000283 if pid is not None and save_persistent_id:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000284 self.save_pers(pid)
285 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000286
Guido van Rossumbc64e222003-01-28 16:34:19 +0000287 # Check the memo
288 x = self.memo.get(id(obj))
289 if x:
290 self.write(self.get(x[0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000291 return
292
Guido van Rossumbc64e222003-01-28 16:34:19 +0000293 # Check the type dispatch table
Guido van Rossum3a41c612003-01-28 15:10:22 +0000294 t = type(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000295 f = self.dispatch.get(t)
296 if f:
297 f(self, obj) # Call unbound method with explicit self
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000298 return
299
Antoine Pitrou8d3c2902012-03-04 18:31:48 +0100300 # Check private dispatch table if any, or else copyreg.dispatch_table
301 reduce = getattr(self, 'dispatch_table', dispatch_table).get(t)
Guido van Rossumc53f0092003-02-18 22:05:12 +0000302 if reduce:
303 rv = reduce(obj)
304 else:
Antoine Pitrouffd41d92011-10-04 09:23:04 +0200305 # Check for a class with a custom metaclass; treat as regular class
306 try:
307 issc = issubclass(t, type)
308 except TypeError: # t is not a class (old Boost; see SF #502085)
309 issc = False
310 if issc:
311 self.save_global(obj)
312 return
313
Guido van Rossumc53f0092003-02-18 22:05:12 +0000314 # Check for a __reduce_ex__ method, fall back to __reduce__
315 reduce = getattr(obj, "__reduce_ex__", None)
316 if reduce:
317 rv = reduce(self.proto)
318 else:
319 reduce = getattr(obj, "__reduce__", None)
320 if reduce:
321 rv = reduce()
322 else:
323 raise PicklingError("Can't pickle %r object: %r" %
324 (t.__name__, obj))
Tim Petersb32a8312003-01-28 00:48:09 +0000325
Guido van Rossumbc64e222003-01-28 16:34:19 +0000326 # Check for string returned by reduce(), meaning "save as global"
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000327 if isinstance(rv, str):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000328 self.save_global(obj, rv)
Tim Petersb32a8312003-01-28 00:48:09 +0000329 return
330
Guido van Rossumbc64e222003-01-28 16:34:19 +0000331 # Assert that reduce() returned a tuple
Guido van Rossum13257902007-06-07 23:15:56 +0000332 if not isinstance(rv, tuple):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000333 raise PicklingError("%s must return string or tuple" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000334
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000335 # Assert that it returned an appropriately sized tuple
Guido van Rossumbc64e222003-01-28 16:34:19 +0000336 l = len(rv)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000337 if not (2 <= l <= 5):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000338 raise PicklingError("Tuple returned by %s must have "
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000339 "two to five elements" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000340
Guido van Rossumbc64e222003-01-28 16:34:19 +0000341 # Save the reduce() output and finally memoize the object
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000342 self.save_reduce(obj=obj, *rv)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000343
Guido van Rossum3a41c612003-01-28 15:10:22 +0000344 def persistent_id(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000345 # This exists so a subclass can override it
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000346 return None
347
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000348 def save_pers(self, pid):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000349 # Save a persistent id reference
Tim Petersbd1cdb92003-01-28 01:03:10 +0000350 if self.bin:
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000351 self.save(pid, save_persistent_id=False)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000352 self.write(BINPERSID)
Tim Petersbd1cdb92003-01-28 01:03:10 +0000353 else:
Guido van Rossum39478e82007-08-27 17:23:59 +0000354 self.write(PERSID + str(pid).encode("ascii") + b'\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000355
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000356 def save_reduce(self, func, args, state=None,
357 listitems=None, dictitems=None, obj=None):
Jeremy Hyltone3a565e2003-06-29 16:59:59 +0000358 # This API is called by some subclasses
Guido van Rossumbc64e222003-01-28 16:34:19 +0000359
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000360 # Assert that args is a tuple
Guido van Rossum13257902007-06-07 23:15:56 +0000361 if not isinstance(args, tuple):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000362 raise PicklingError("args from save_reduce() should be a tuple")
Guido van Rossumbc64e222003-01-28 16:34:19 +0000363
364 # Assert that func is callable
Florent Xicluna5d1155c2011-10-28 14:45:05 +0200365 if not callable(func):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000366 raise PicklingError("func from save_reduce() should be callable")
Guido van Rossumbc64e222003-01-28 16:34:19 +0000367
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000368 save = self.save
Guido van Rossumbc64e222003-01-28 16:34:19 +0000369 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000370
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000371 # Protocol 2 special case: if func's name is __newobj__, use NEWOBJ
372 if self.proto >= 2 and getattr(func, "__name__", "") == "__newobj__":
373 # A __reduce__ implementation can direct protocol 2 to
374 # use the more efficient NEWOBJ opcode, while still
375 # allowing protocol 0 and 1 to work normally. For this to
376 # work, the function returned by __reduce__ should be
377 # called __newobj__, and its first argument should be a
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100378 # class. The implementation for __newobj__
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000379 # should be as follows, although pickle has no way to
380 # verify this:
381 #
382 # def __newobj__(cls, *args):
383 # return cls.__new__(cls, *args)
384 #
385 # Protocols 0 and 1 will pickle a reference to __newobj__,
386 # while protocol 2 (and above) will pickle a reference to
387 # cls, the remaining args tuple, and the NEWOBJ code,
388 # which calls cls.__new__(cls, *args) at unpickling time
389 # (see load_newobj below). If __reduce__ returns a
390 # three-tuple, the state from the third tuple item will be
391 # pickled regardless of the protocol, calling __setstate__
392 # at unpickling time (see load_build below).
393 #
394 # Note that no standard __newobj__ implementation exists;
395 # you have to provide your own. This is to enforce
396 # compatibility with Python 2.2 (pickles written using
397 # protocol 0 or 1 in Python 2.3 should be unpicklable by
398 # Python 2.2).
399 cls = args[0]
400 if not hasattr(cls, "__new__"):
401 raise PicklingError(
402 "args[0] from __newobj__ args has no __new__")
Guido van Rossumf7f45172003-01-31 17:17:49 +0000403 if obj is not None and cls is not obj.__class__:
404 raise PicklingError(
405 "args[0] from __newobj__ args has the wrong class")
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000406 args = args[1:]
407 save(cls)
408 save(args)
409 write(NEWOBJ)
410 else:
411 save(func)
412 save(args)
413 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000414
Guido van Rossumf7f45172003-01-31 17:17:49 +0000415 if obj is not None:
416 self.memoize(obj)
417
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000418 # More new special cases (that work with older protocols as
419 # well): when __reduce__ returns a tuple with 4 or 5 items,
420 # the 4th and 5th item should be iterators that provide list
421 # items and dict items (as (key, value) tuples), or None.
422
423 if listitems is not None:
424 self._batch_appends(listitems)
425
426 if dictitems is not None:
427 self._batch_setitems(dictitems)
428
Tim Petersc32d8242001-04-10 02:48:53 +0000429 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000430 save(state)
431 write(BUILD)
432
Guido van Rossumbc64e222003-01-28 16:34:19 +0000433 # Methods below this point are dispatched through the dispatch table
434
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000435 dispatch = {}
436
Guido van Rossum3a41c612003-01-28 15:10:22 +0000437 def save_none(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000438 self.write(NONE)
Guido van Rossum13257902007-06-07 23:15:56 +0000439 dispatch[type(None)] = save_none
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000440
Łukasz Langaf3078fb2012-03-12 19:46:12 +0100441 def save_ellipsis(self, obj):
442 self.save_global(Ellipsis, 'Ellipsis')
443 dispatch[type(Ellipsis)] = save_ellipsis
444
445 def save_notimplemented(self, obj):
446 self.save_global(NotImplemented, 'NotImplemented')
447 dispatch[type(NotImplemented)] = save_notimplemented
448
Guido van Rossum3a41c612003-01-28 15:10:22 +0000449 def save_bool(self, obj):
Guido van Rossum7d97d312003-01-28 04:25:27 +0000450 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000451 self.write(obj and NEWTRUE or NEWFALSE)
Guido van Rossum7d97d312003-01-28 04:25:27 +0000452 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000453 self.write(obj and TRUE or FALSE)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000454 dispatch[bool] = save_bool
455
Guido van Rossum3a41c612003-01-28 15:10:22 +0000456 def save_long(self, obj, pack=struct.pack):
Guido van Rossumddefaf32007-01-14 03:31:43 +0000457 if self.bin:
458 # If the int is small enough to fit in a signed 4-byte 2's-comp
459 # format, we can store it more efficiently than the general
460 # case.
461 # First one- and two-byte unsigned ints:
462 if obj >= 0:
463 if obj <= 0xff:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000464 self.write(BININT1 + bytes([obj]))
Guido van Rossumddefaf32007-01-14 03:31:43 +0000465 return
466 if obj <= 0xffff:
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000467 self.write(BININT2 + bytes([obj&0xff, obj>>8]))
Guido van Rossumddefaf32007-01-14 03:31:43 +0000468 return
469 # Next check for 4-byte signed ints:
470 high_bits = obj >> 31 # note that Python shift sign-extends
471 if high_bits == 0 or high_bits == -1:
472 # All high bits are copies of bit 2**31, so the value
473 # fits in a 4-byte signed int.
474 self.write(BININT + pack("<i", obj))
475 return
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000476 if self.proto >= 2:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000477 encoded = encode_long(obj)
478 n = len(encoded)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000479 if n < 256:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000480 self.write(LONG1 + bytes([n]) + encoded)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000481 else:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000482 self.write(LONG4 + pack("<i", n) + encoded)
Tim Petersee1a53c2003-02-02 02:57:53 +0000483 return
Mark Dickinson8dd05142009-01-20 20:43:58 +0000484 self.write(LONG + repr(obj).encode("ascii") + b'L\n')
Guido van Rossum13257902007-06-07 23:15:56 +0000485 dispatch[int] = save_long
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000486
Guido van Rossum3a41c612003-01-28 15:10:22 +0000487 def save_float(self, obj, pack=struct.pack):
Guido van Rossumd3703791998-10-22 20:15:36 +0000488 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000489 self.write(BINFLOAT + pack('>d', obj))
Guido van Rossumd3703791998-10-22 20:15:36 +0000490 else:
Guido van Rossum39478e82007-08-27 17:23:59 +0000491 self.write(FLOAT + repr(obj).encode("ascii") + b'\n')
Guido van Rossum13257902007-06-07 23:15:56 +0000492 dispatch[float] = save_float
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000493
Guido van Rossumf4169812008-03-17 22:56:06 +0000494 def save_bytes(self, obj, pack=struct.pack):
495 if self.proto < 3:
Alexandre Vassalotti3bfc65a2011-12-13 13:08:09 -0500496 if len(obj) == 0:
497 self.save_reduce(bytes, (), obj=obj)
498 else:
499 self.save_reduce(codecs.encode,
500 (str(obj, 'latin1'), 'latin1'), obj=obj)
Guido van Rossumf4169812008-03-17 22:56:06 +0000501 return
502 n = len(obj)
503 if n < 256:
504 self.write(SHORT_BINBYTES + bytes([n]) + bytes(obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000505 else:
Antoine Pitroubf6ecf92012-11-24 20:40:21 +0100506 self.write(BINBYTES + pack("<I", n) + bytes(obj))
Guido van Rossum3a41c612003-01-28 15:10:22 +0000507 self.memoize(obj)
Guido van Rossumf4169812008-03-17 22:56:06 +0000508 dispatch[bytes] = save_bytes
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000509
Guido van Rossumf4169812008-03-17 22:56:06 +0000510 def save_str(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000511 if self.bin:
Victor Stinner485fb562010-04-13 11:07:24 +0000512 encoded = obj.encode('utf-8', 'surrogatepass')
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000513 n = len(encoded)
Antoine Pitroubf6ecf92012-11-24 20:40:21 +0100514 self.write(BINUNICODE + pack("<I", n) + encoded)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000515 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000516 obj = obj.replace("\\", "\\u005c")
517 obj = obj.replace("\n", "\\u000a")
Guido van Rossum1255ed62007-05-04 20:30:19 +0000518 self.write(UNICODE + bytes(obj.encode('raw-unicode-escape')) +
519 b'\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000520 self.memoize(obj)
Guido van Rossumf4169812008-03-17 22:56:06 +0000521 dispatch[str] = save_str
Tim Peters658cba62001-02-09 20:06:00 +0000522
Guido van Rossum3a41c612003-01-28 15:10:22 +0000523 def save_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000524 write = self.write
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000525 proto = self.proto
526
Guido van Rossum3a41c612003-01-28 15:10:22 +0000527 n = len(obj)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000528 if n == 0:
529 if proto:
530 write(EMPTY_TUPLE)
531 else:
532 write(MARK + TUPLE)
Tim Petersd97da802003-01-28 05:48:29 +0000533 return
534
535 save = self.save
536 memo = self.memo
537 if n <= 3 and proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000538 for element in obj:
Tim Petersd97da802003-01-28 05:48:29 +0000539 save(element)
540 # Subtle. Same as in the big comment below.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000541 if id(obj) in memo:
542 get = self.get(memo[id(obj)][0])
Tim Petersd97da802003-01-28 05:48:29 +0000543 write(POP * n + get)
544 else:
545 write(_tuplesize2code[n])
Guido van Rossum3a41c612003-01-28 15:10:22 +0000546 self.memoize(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000547 return
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000548
Tim Peters1d63c9f2003-02-02 20:29:39 +0000549 # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple
Tim Petersff57bff2003-01-28 05:34:53 +0000550 # has more than 3 elements.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000551 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000552 for element in obj:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000553 save(element)
554
Tim Peters1d63c9f2003-02-02 20:29:39 +0000555 if id(obj) in memo:
Tim Petersf558da02003-01-28 02:09:55 +0000556 # Subtle. d was not in memo when we entered save_tuple(), so
557 # the process of saving the tuple's elements must have saved
558 # the tuple itself: the tuple is recursive. The proper action
559 # now is to throw away everything we put on the stack, and
560 # simply GET the tuple (it's already constructed). This check
561 # could have been done in the "for element" loop instead, but
562 # recursive tuples are a rare thing.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000563 get = self.get(memo[id(obj)][0])
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000564 if proto:
Tim Petersf558da02003-01-28 02:09:55 +0000565 write(POP_MARK + get)
566 else: # proto 0 -- POP_MARK not available
Tim Petersd97da802003-01-28 05:48:29 +0000567 write(POP * (n+1) + get)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000568 return
569
Tim Peters1d63c9f2003-02-02 20:29:39 +0000570 # No recursion.
Tim Peters518df0d2003-01-28 01:00:38 +0000571 self.write(TUPLE)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000572 self.memoize(obj)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000573
Guido van Rossum13257902007-06-07 23:15:56 +0000574 dispatch[tuple] = save_tuple
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000575
Guido van Rossum3a41c612003-01-28 15:10:22 +0000576 def save_list(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000577 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000578
Tim Petersc32d8242001-04-10 02:48:53 +0000579 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000580 write(EMPTY_LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000581 else: # proto 0 -- can't use EMPTY_LIST
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000582 write(MARK + LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000583
584 self.memoize(obj)
Alexandre Vassalottic7db1d62008-05-14 21:57:18 +0000585 self._batch_appends(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000586
Guido van Rossum13257902007-06-07 23:15:56 +0000587 dispatch[list] = save_list
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000588
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000589 _BATCHSIZE = 1000
590
591 def _batch_appends(self, items):
592 # Helper to batch up APPENDS sequences
593 save = self.save
594 write = self.write
595
596 if not self.bin:
597 for x in items:
598 save(x)
599 write(APPEND)
600 return
601
Alexandre Vassalottic7db1d62008-05-14 21:57:18 +0000602 items = iter(items)
Guido van Rossum805365e2007-05-07 22:24:25 +0000603 r = range(self._BATCHSIZE)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000604 while items is not None:
605 tmp = []
606 for i in r:
607 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000608 x = next(items)
Guido van Rossum5aac4e62003-02-06 22:57:00 +0000609 tmp.append(x)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000610 except StopIteration:
611 items = None
612 break
613 n = len(tmp)
614 if n > 1:
615 write(MARK)
616 for x in tmp:
617 save(x)
618 write(APPENDS)
619 elif n:
620 save(tmp[0])
621 write(APPEND)
622 # else tmp is empty, and we're done
623
Guido van Rossum3a41c612003-01-28 15:10:22 +0000624 def save_dict(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000625 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000626
Tim Petersc32d8242001-04-10 02:48:53 +0000627 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000628 write(EMPTY_DICT)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000629 else: # proto 0 -- can't use EMPTY_DICT
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000630 write(MARK + DICT)
631
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000632 self.memoize(obj)
Alexandre Vassalottic7db1d62008-05-14 21:57:18 +0000633 self._batch_setitems(obj.items())
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000634
Guido van Rossum13257902007-06-07 23:15:56 +0000635 dispatch[dict] = save_dict
636 if PyStringMap is not None:
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000637 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000638
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000639 def _batch_setitems(self, items):
640 # Helper to batch up SETITEMS sequences; proto >= 1 only
641 save = self.save
642 write = self.write
643
644 if not self.bin:
645 for k, v in items:
646 save(k)
647 save(v)
648 write(SETITEM)
649 return
650
Alexandre Vassalottic7db1d62008-05-14 21:57:18 +0000651 items = iter(items)
Guido van Rossum805365e2007-05-07 22:24:25 +0000652 r = range(self._BATCHSIZE)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000653 while items is not None:
654 tmp = []
655 for i in r:
656 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000657 tmp.append(next(items))
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000658 except StopIteration:
659 items = None
660 break
661 n = len(tmp)
662 if n > 1:
663 write(MARK)
664 for k, v in tmp:
665 save(k)
666 save(v)
667 write(SETITEMS)
668 elif n:
669 k, v = tmp[0]
670 save(k)
671 save(v)
672 write(SETITEM)
673 # else tmp is empty, and we're done
674
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000675 def save_global(self, obj, name=None, pack=struct.pack):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000676 write = self.write
677 memo = self.memo
678
Tim Petersc32d8242001-04-10 02:48:53 +0000679 if name is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000680 name = obj.__name__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000681
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000682 module = getattr(obj, "__module__", None)
683 if module is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000684 module = whichmodule(obj, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000685
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000686 try:
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000687 __import__(module, level=0)
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000688 mod = sys.modules[module]
689 klass = getattr(mod, name)
690 except (ImportError, KeyError, AttributeError):
691 raise PicklingError(
692 "Can't pickle %r: it's not found as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000693 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000694 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000695 if klass is not obj:
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000696 raise PicklingError(
697 "Can't pickle %r: it's not the same object as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000698 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000699
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000700 if self.proto >= 2:
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000701 code = _extension_registry.get((module, name))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000702 if code:
703 assert code > 0
704 if code <= 0xff:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000705 write(EXT1 + bytes([code]))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000706 elif code <= 0xffff:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000707 write(EXT2 + bytes([code&0xff, code>>8]))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000708 else:
709 write(EXT4 + pack("<i", code))
710 return
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000711 # Non-ASCII identifiers are supported only with protocols >= 3.
712 if self.proto >= 3:
713 write(GLOBAL + bytes(module, "utf-8") + b'\n' +
714 bytes(name, "utf-8") + b'\n')
715 else:
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000716 if self.fix_imports:
717 if (module, name) in _compat_pickle.REVERSE_NAME_MAPPING:
718 module, name = _compat_pickle.REVERSE_NAME_MAPPING[(module, name)]
719 if module in _compat_pickle.REVERSE_IMPORT_MAPPING:
720 module = _compat_pickle.REVERSE_IMPORT_MAPPING[module]
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000721 try:
722 write(GLOBAL + bytes(module, "ascii") + b'\n' +
723 bytes(name, "ascii") + b'\n')
724 except UnicodeEncodeError:
725 raise PicklingError(
726 "can't pickle global identifier '%s.%s' using "
727 "pickle protocol %i" % (module, name, self.proto))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000728
Guido van Rossum3a41c612003-01-28 15:10:22 +0000729 self.memoize(obj)
Tim Peters3b769832003-01-28 03:51:36 +0000730
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000731 dispatch[FunctionType] = save_global
732 dispatch[BuiltinFunctionType] = save_global
Guido van Rossum13257902007-06-07 23:15:56 +0000733 dispatch[type] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000734
Guido van Rossum1be31752003-01-28 15:19:53 +0000735# Pickling helpers
Guido van Rossuma48061a1995-01-10 00:31:14 +0000736
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000737def _keep_alive(x, memo):
738 """Keeps a reference to the object x in the memo.
739
740 Because we remember objects by their id, we have
741 to assure that possibly temporary objects are kept
742 alive by referencing them.
743 We store a reference at the id of the memo, which should
744 normally not be used unless someone tries to deepcopy
745 the memo itself...
746 """
747 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000748 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000749 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000750 # aha, this is the first one :-)
751 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000752
753
Tim Petersc0c12b52003-01-29 00:56:17 +0000754# A cache for whichmodule(), mapping a function object to the name of
755# the module in which the function was found.
756
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000757classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000758
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000759def whichmodule(func, funcname):
760 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000761
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000762 Search sys.modules for the module.
763 Cache in classmap.
764 Return a module name.
Tim Petersc0c12b52003-01-29 00:56:17 +0000765 If the function cannot be found, return "__main__".
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000766 """
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000767 # Python functions should always get an __module__ from their globals.
768 mod = getattr(func, "__module__", None)
769 if mod is not None:
770 return mod
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000771 if func in classmap:
772 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000773
Guido van Rossum634e53f2007-02-26 07:07:02 +0000774 for name, module in list(sys.modules.items()):
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000775 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000776 continue # skip dummy package entries
Jeremy Hyltoncc1fccb2003-02-06 16:23:01 +0000777 if name != '__main__' and getattr(module, funcname, None) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000778 break
779 else:
780 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000781 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000782 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000783
784
Guido van Rossum1be31752003-01-28 15:19:53 +0000785# Unpickling machinery
786
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000787class _Unpickler:
Guido van Rossuma48061a1995-01-10 00:31:14 +0000788
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000789 def __init__(self, file, *, fix_imports=True,
790 encoding="ASCII", errors="strict"):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000791 """This takes a binary file for reading a pickle data stream.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000792
Tim Peters5bd2a792003-02-01 16:45:06 +0000793 The protocol version of the pickle is detected automatically, so no
794 proto argument is needed.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000795
Guido van Rossumfeea0782007-10-10 18:00:50 +0000796 The file-like object must have two methods, a read() method
797 that takes an integer argument, and a readline() method that
798 requires no arguments. Both methods should return bytes.
799 Thus file-like object can be a binary file object opened for
800 reading, a BytesIO object, or any other custom object that
801 meets this interface.
Guido van Rossumf4169812008-03-17 22:56:06 +0000802
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000803 Optional keyword arguments are *fix_imports*, *encoding* and *errors*,
804 which are used to control compatiblity support for pickle stream
805 generated by Python 2.x. If *fix_imports* is True, pickle will try to
806 map the old Python 2.x names to the new names used in Python 3.x. The
807 *encoding* and *errors* tell pickle how to decode 8-bit string
808 instances pickled by Python 2.x; these default to 'ASCII' and
809 'strict', respectively.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000810 """
Guido van Rossumfeea0782007-10-10 18:00:50 +0000811 self.readline = file.readline
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000812 self.read = file.read
813 self.memo = {}
Guido van Rossumf4169812008-03-17 22:56:06 +0000814 self.encoding = encoding
815 self.errors = errors
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000816 self.proto = 0
817 self.fix_imports = fix_imports
Guido van Rossuma48061a1995-01-10 00:31:14 +0000818
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000819 def load(self):
Guido van Rossum3a41c612003-01-28 15:10:22 +0000820 """Read a pickled object representation from the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000821
Guido van Rossum3a41c612003-01-28 15:10:22 +0000822 Return the reconstituted object hierarchy specified in the file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000823 """
Alexandre Vassalotti3cfcab92008-12-27 09:30:39 +0000824 # Check whether Unpickler was initialized correctly. This is
825 # only needed to mimic the behavior of _pickle.Unpickler.dump().
826 if not hasattr(self, "read"):
827 raise UnpicklingError("Unpickler.__init__() was not called by "
828 "%s.__init__()" % (self.__class__.__name__,))
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)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000837 if not key:
838 raise EOFError
Guido van Rossum98297ee2007-11-06 21:34:58 +0000839 assert isinstance(key, bytes_types)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000840 dispatch[key[0]](self)
Guido van Rossumb940e112007-01-10 16:19:56 +0000841 except _Stop as stopinst:
Guido van Rossumff871742000-12-13 18:11:56 +0000842 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000843
Tim Petersc23d18a2003-01-28 01:41:51 +0000844 # Return largest index k such that self.stack[k] is self.mark.
845 # If the stack doesn't contain a mark, eventually raises IndexError.
846 # This could be sped by maintaining another stack, of indices at which
847 # the mark appears. For that matter, the latter stack would suffice,
848 # and we wouldn't need to push mark objects on self.stack at all.
849 # Doing so is probably a good thing, though, since if the pickle is
850 # corrupt (or hostile) we may get a clue from finding self.mark embedded
851 # in unpickled objects.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000852 def marker(self):
853 stack = self.stack
854 mark = self.mark
855 k = len(stack)-1
856 while stack[k] is not mark: k = k-1
857 return k
858
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000859 def persistent_load(self, pid):
Benjamin Peterson49956b22009-01-10 17:05:44 +0000860 raise UnpicklingError("unsupported persistent id encountered")
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000861
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000862 dispatch = {}
863
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000864 def load_proto(self):
865 proto = ord(self.read(1))
Guido van Rossumf4169812008-03-17 22:56:06 +0000866 if not 0 <= proto <= HIGHEST_PROTOCOL:
Guido van Rossum26d95c32007-08-27 23:18:54 +0000867 raise ValueError("unsupported pickle protocol: %d" % proto)
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000868 self.proto = proto
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000869 dispatch[PROTO[0]] = load_proto
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000870
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000871 def load_persid(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000872 pid = self.readline()[:-1].decode("ascii")
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000873 self.append(self.persistent_load(pid))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000874 dispatch[PERSID[0]] = load_persid
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000875
876 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000877 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000878 self.append(self.persistent_load(pid))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000879 dispatch[BINPERSID[0]] = load_binpersid
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000880
881 def load_none(self):
882 self.append(None)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000883 dispatch[NONE[0]] = load_none
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000884
Guido van Rossum7d97d312003-01-28 04:25:27 +0000885 def load_false(self):
886 self.append(False)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000887 dispatch[NEWFALSE[0]] = load_false
Guido van Rossum7d97d312003-01-28 04:25:27 +0000888
889 def load_true(self):
890 self.append(True)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000891 dispatch[NEWTRUE[0]] = load_true
Guido van Rossum7d97d312003-01-28 04:25:27 +0000892
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000893 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000894 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000895 if data == FALSE[1:]:
896 val = False
897 elif data == TRUE[1:]:
898 val = True
899 else:
900 try:
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000901 val = int(data, 0)
Guido van Rossume2763392002-04-05 19:30:08 +0000902 except ValueError:
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000903 val = int(data, 0)
Guido van Rossume2763392002-04-05 19:30:08 +0000904 self.append(val)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000905 dispatch[INT[0]] = load_int
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000906
907 def load_binint(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000908 self.append(mloads(b'i' + self.read(4)))
909 dispatch[BININT[0]] = load_binint
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000910
911 def load_binint1(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000912 self.append(ord(self.read(1)))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000913 dispatch[BININT1[0]] = load_binint1
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000914
915 def load_binint2(self):
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000916 self.append(mloads(b'i' + self.read(2) + b'\000\000'))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000917 dispatch[BININT2[0]] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000918
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000919 def load_long(self):
Guido van Rossumfeea0782007-10-10 18:00:50 +0000920 val = self.readline()[:-1].decode("ascii")
Mark Dickinson8dd05142009-01-20 20:43:58 +0000921 if val and val[-1] == 'L':
922 val = val[:-1]
Guido van Rossumfeea0782007-10-10 18:00:50 +0000923 self.append(int(val, 0))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000924 dispatch[LONG[0]] = load_long
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000925
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000926 def load_long1(self):
927 n = ord(self.read(1))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000928 data = self.read(n)
929 self.append(decode_long(data))
930 dispatch[LONG1[0]] = load_long1
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000931
932 def load_long4(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000933 n = mloads(b'i' + self.read(4))
Antoine Pitroubf6ecf92012-11-24 20:40:21 +0100934 if n < 0:
935 # Corrupt or hostile pickle -- we never write one like this
Alexandre Vassalotticc757172013-04-14 02:25:10 -0700936 raise UnpicklingError("LONG pickle has negative byte count")
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000937 data = self.read(n)
938 self.append(decode_long(data))
939 dispatch[LONG4[0]] = load_long4
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000940
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000941 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000942 self.append(float(self.readline()[:-1]))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000943 dispatch[FLOAT[0]] = load_float
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000944
Guido van Rossumd3703791998-10-22 20:15:36 +0000945 def load_binfloat(self, unpack=struct.unpack):
946 self.append(unpack('>d', self.read(8))[0])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000947 dispatch[BINFLOAT[0]] = load_binfloat
Guido van Rossumd3703791998-10-22 20:15:36 +0000948
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000949 def load_string(self):
Guido van Rossum98297ee2007-11-06 21:34:58 +0000950 orig = self.readline()
951 rep = orig[:-1]
Guido van Rossum26d95c32007-08-27 23:18:54 +0000952 for q in (b'"', b"'"): # double or single quote
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000953 if rep.startswith(q):
954 if not rep.endswith(q):
Guido van Rossum26d95c32007-08-27 23:18:54 +0000955 raise ValueError("insecure string pickle")
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000956 rep = rep[len(q):-len(q)]
957 break
958 else:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000959 raise ValueError("insecure string pickle: %r" % orig)
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000960 self.append(codecs.escape_decode(rep)[0]
961 .decode(self.encoding, self.errors))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000962 dispatch[STRING[0]] = load_string
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000963
964 def load_binstring(self):
Antoine Pitroubf6ecf92012-11-24 20:40:21 +0100965 # Deprecated BINSTRING uses signed 32-bit length
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000966 len = mloads(b'i' + self.read(4))
Antoine Pitroubf6ecf92012-11-24 20:40:21 +0100967 if len < 0:
Alexandre Vassalotticc757172013-04-14 02:25:10 -0700968 raise UnpicklingError("BINSTRING pickle has negative byte count")
Guido van Rossumf4169812008-03-17 22:56:06 +0000969 data = self.read(len)
970 value = str(data, self.encoding, self.errors)
971 self.append(value)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000972 dispatch[BINSTRING[0]] = load_binstring
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000973
Antoine Pitroubf6ecf92012-11-24 20:40:21 +0100974 def load_binbytes(self, unpack=struct.unpack, maxsize=sys.maxsize):
975 len, = unpack('<I', self.read(4))
976 if len > maxsize:
Alexandre Vassalotticc757172013-04-14 02:25:10 -0700977 raise UnpicklingError("BINBYTES exceeds system's maximum size "
978 "of %d bytes" % maxsize)
Guido van Rossumf4169812008-03-17 22:56:06 +0000979 self.append(self.read(len))
980 dispatch[BINBYTES[0]] = load_binbytes
981
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000982 def load_unicode(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000983 self.append(str(self.readline()[:-1], 'raw-unicode-escape'))
984 dispatch[UNICODE[0]] = load_unicode
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000985
Antoine Pitroubf6ecf92012-11-24 20:40:21 +0100986 def load_binunicode(self, unpack=struct.unpack, maxsize=sys.maxsize):
987 len, = unpack('<I', self.read(4))
988 if len > maxsize:
Alexandre Vassalotticc757172013-04-14 02:25:10 -0700989 raise UnpicklingError("BINUNICODE exceeds system's maximum size "
990 "of %d bytes" % maxsize)
Victor Stinner485fb562010-04-13 11:07:24 +0000991 self.append(str(self.read(len), 'utf-8', 'surrogatepass'))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000992 dispatch[BINUNICODE[0]] = load_binunicode
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000993
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000994 def load_short_binstring(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000995 len = ord(self.read(1))
Guido van Rossumf4169812008-03-17 22:56:06 +0000996 data = bytes(self.read(len))
997 value = str(data, self.encoding, self.errors)
998 self.append(value)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000999 dispatch[SHORT_BINSTRING[0]] = load_short_binstring
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001000
Guido van Rossumf4169812008-03-17 22:56:06 +00001001 def load_short_binbytes(self):
1002 len = ord(self.read(1))
1003 self.append(bytes(self.read(len)))
1004 dispatch[SHORT_BINBYTES[0]] = load_short_binbytes
1005
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001006 def load_tuple(self):
1007 k = self.marker()
1008 self.stack[k:] = [tuple(self.stack[k+1:])]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001009 dispatch[TUPLE[0]] = load_tuple
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001010
1011 def load_empty_tuple(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001012 self.append(())
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001013 dispatch[EMPTY_TUPLE[0]] = load_empty_tuple
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001014
Guido van Rossum44f0ea52003-01-28 04:14:51 +00001015 def load_tuple1(self):
1016 self.stack[-1] = (self.stack[-1],)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001017 dispatch[TUPLE1[0]] = load_tuple1
Guido van Rossum44f0ea52003-01-28 04:14:51 +00001018
1019 def load_tuple2(self):
1020 self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001021 dispatch[TUPLE2[0]] = load_tuple2
Guido van Rossum44f0ea52003-01-28 04:14:51 +00001022
1023 def load_tuple3(self):
1024 self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001025 dispatch[TUPLE3[0]] = load_tuple3
Guido van Rossum44f0ea52003-01-28 04:14:51 +00001026
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001027 def load_empty_list(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001028 self.append([])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001029 dispatch[EMPTY_LIST[0]] = load_empty_list
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001030
1031 def load_empty_dictionary(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001032 self.append({})
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001033 dispatch[EMPTY_DICT[0]] = load_empty_dictionary
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001034
1035 def load_list(self):
1036 k = self.marker()
1037 self.stack[k:] = [self.stack[k+1:]]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001038 dispatch[LIST[0]] = load_list
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001039
1040 def load_dict(self):
1041 k = self.marker()
1042 d = {}
1043 items = self.stack[k+1:]
1044 for i in range(0, len(items), 2):
1045 key = items[i]
1046 value = items[i+1]
1047 d[key] = value
1048 self.stack[k:] = [d]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001049 dispatch[DICT[0]] = load_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001050
Tim Petersd01c1e92003-01-30 15:41:46 +00001051 # INST and OBJ differ only in how they get a class object. It's not
1052 # only sensible to do the rest in a common routine, the two routines
1053 # previously diverged and grew different bugs.
1054 # klass is the class to instantiate, and k points to the topmost mark
1055 # object, following which are the arguments for klass.__init__.
1056 def _instantiate(self, klass, k):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001057 args = tuple(self.stack[k+1:])
1058 del self.stack[k:]
Alexander Belopolskyd92f0402010-07-17 22:50:45 +00001059 if (args or not isinstance(klass, type) or
1060 hasattr(klass, "__getinitargs__")):
Guido van Rossum743d17e1998-09-15 20:25:57 +00001061 try:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001062 value = klass(*args)
Guido van Rossumb940e112007-01-10 16:19:56 +00001063 except TypeError as err:
Guido van Rossum26d95c32007-08-27 23:18:54 +00001064 raise TypeError("in constructor for %s: %s" %
1065 (klass.__name__, str(err)), sys.exc_info()[2])
Alexander Belopolskyd92f0402010-07-17 22:50:45 +00001066 else:
1067 value = klass.__new__(klass)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001068 self.append(value)
Tim Petersd01c1e92003-01-30 15:41:46 +00001069
1070 def load_inst(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001071 module = self.readline()[:-1].decode("ascii")
1072 name = self.readline()[:-1].decode("ascii")
Tim Petersd01c1e92003-01-30 15:41:46 +00001073 klass = self.find_class(module, name)
1074 self._instantiate(klass, self.marker())
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001075 dispatch[INST[0]] = load_inst
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001076
1077 def load_obj(self):
Tim Petersd01c1e92003-01-30 15:41:46 +00001078 # Stack is ... markobject classobject arg1 arg2 ...
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001079 k = self.marker()
Tim Petersd01c1e92003-01-30 15:41:46 +00001080 klass = self.stack.pop(k+1)
1081 self._instantiate(klass, k)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001082 dispatch[OBJ[0]] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001083
Guido van Rossum3a41c612003-01-28 15:10:22 +00001084 def load_newobj(self):
1085 args = self.stack.pop()
1086 cls = self.stack[-1]
1087 obj = cls.__new__(cls, *args)
Guido van Rossum533dbcf2003-01-28 17:55:05 +00001088 self.stack[-1] = obj
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001089 dispatch[NEWOBJ[0]] = load_newobj
Guido van Rossum3a41c612003-01-28 15:10:22 +00001090
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001091 def load_global(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001092 module = self.readline()[:-1].decode("utf-8")
1093 name = self.readline()[:-1].decode("utf-8")
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001094 klass = self.find_class(module, name)
1095 self.append(klass)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001096 dispatch[GLOBAL[0]] = load_global
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001097
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001098 def load_ext1(self):
1099 code = ord(self.read(1))
1100 self.get_extension(code)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001101 dispatch[EXT1[0]] = load_ext1
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001102
1103 def load_ext2(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001104 code = mloads(b'i' + self.read(2) + b'\000\000')
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001105 self.get_extension(code)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001106 dispatch[EXT2[0]] = load_ext2
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001107
1108 def load_ext4(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001109 code = mloads(b'i' + self.read(4))
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001110 self.get_extension(code)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001111 dispatch[EXT4[0]] = load_ext4
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001112
1113 def get_extension(self, code):
1114 nil = []
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001115 obj = _extension_cache.get(code, nil)
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001116 if obj is not nil:
1117 self.append(obj)
1118 return
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001119 key = _inverted_registry.get(code)
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001120 if not key:
Antoine Pitroubf6ecf92012-11-24 20:40:21 +01001121 if code <= 0: # note that 0 is forbidden
1122 # Corrupt or hostile pickle.
Alexandre Vassalotticc757172013-04-14 02:25:10 -07001123 raise UnpicklingError("EXT specifies code <= 0")
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001124 raise ValueError("unregistered extension code %d" % code)
1125 obj = self.find_class(*key)
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001126 _extension_cache[code] = obj
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001127 self.append(obj)
1128
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001129 def find_class(self, module, name):
Antoine Pitroud9dfaa92009-06-04 20:32:06 +00001130 # Subclasses may override this.
1131 if self.proto < 3 and self.fix_imports:
1132 if (module, name) in _compat_pickle.NAME_MAPPING:
1133 module, name = _compat_pickle.NAME_MAPPING[(module, name)]
1134 if module in _compat_pickle.IMPORT_MAPPING:
1135 module = _compat_pickle.IMPORT_MAPPING[module]
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001136 __import__(module, level=0)
Barry Warsawbf4d9592001-11-15 23:42:58 +00001137 mod = sys.modules[module]
1138 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001139 return klass
1140
1141 def load_reduce(self):
1142 stack = self.stack
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001143 args = stack.pop()
1144 func = stack[-1]
Guido van Rossum99603b02007-07-20 00:22:32 +00001145 try:
1146 value = func(*args)
1147 except:
1148 print(sys.exc_info())
1149 print(func, args)
1150 raise
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001151 stack[-1] = value
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001152 dispatch[REDUCE[0]] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +00001153
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001154 def load_pop(self):
1155 del self.stack[-1]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001156 dispatch[POP[0]] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +00001157
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001158 def load_pop_mark(self):
1159 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001160 del self.stack[k:]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001161 dispatch[POP_MARK[0]] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001162
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001163 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +00001164 self.append(self.stack[-1])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001165 dispatch[DUP[0]] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +00001166
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001167 def load_get(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001168 i = int(self.readline()[:-1])
1169 self.append(self.memo[i])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001170 dispatch[GET[0]] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +00001171
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001172 def load_binget(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001173 i = self.read(1)[0]
1174 self.append(self.memo[i])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001175 dispatch[BINGET[0]] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001176
Antoine Pitroubf6ecf92012-11-24 20:40:21 +01001177 def load_long_binget(self, unpack=struct.unpack):
1178 i, = unpack('<I', self.read(4))
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001179 self.append(self.memo[i])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001180 dispatch[LONG_BINGET[0]] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001181
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001182 def load_put(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001183 i = int(self.readline()[:-1])
Antoine Pitrou55549ec2011-08-30 00:27:10 +02001184 if i < 0:
1185 raise ValueError("negative PUT argument")
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001186 self.memo[i] = self.stack[-1]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001187 dispatch[PUT[0]] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +00001188
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001189 def load_binput(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001190 i = self.read(1)[0]
Antoine Pitrou55549ec2011-08-30 00:27:10 +02001191 if i < 0:
1192 raise ValueError("negative BINPUT argument")
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001193 self.memo[i] = self.stack[-1]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001194 dispatch[BINPUT[0]] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001195
Antoine Pitroubf6ecf92012-11-24 20:40:21 +01001196 def load_long_binput(self, unpack=struct.unpack, maxsize=sys.maxsize):
1197 i, = unpack('<I', self.read(4))
1198 if i > maxsize:
Antoine Pitrou55549ec2011-08-30 00:27:10 +02001199 raise ValueError("negative LONG_BINPUT argument")
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001200 self.memo[i] = self.stack[-1]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001201 dispatch[LONG_BINPUT[0]] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001202
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001203 def load_append(self):
1204 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001205 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001206 list = stack[-1]
1207 list.append(value)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001208 dispatch[APPEND[0]] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +00001209
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001210 def load_appends(self):
1211 stack = self.stack
1212 mark = self.marker()
1213 list = stack[mark - 1]
Tim Peters209ad952003-01-28 01:44:45 +00001214 list.extend(stack[mark + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001215 del stack[mark:]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001216 dispatch[APPENDS[0]] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +00001217
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001218 def load_setitem(self):
1219 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001220 value = stack.pop()
1221 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001222 dict = stack[-1]
1223 dict[key] = value
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001224 dispatch[SETITEM[0]] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001225
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001226 def load_setitems(self):
1227 stack = self.stack
1228 mark = self.marker()
1229 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001230 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001231 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001232
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001233 del stack[mark:]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001234 dispatch[SETITEMS[0]] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001235
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001236 def load_build(self):
1237 stack = self.stack
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001238 state = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001239 inst = stack[-1]
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001240 setstate = getattr(inst, "__setstate__", None)
1241 if setstate:
1242 setstate(state)
1243 return
1244 slotstate = None
1245 if isinstance(state, tuple) and len(state) == 2:
1246 state, slotstate = state
1247 if state:
Alexandre Vassalottiebfecfd2009-05-25 18:50:33 +00001248 inst_dict = inst.__dict__
Antoine Pitroua9f48a02009-05-02 21:41:14 +00001249 intern = sys.intern
Alexandre Vassalottiebfecfd2009-05-25 18:50:33 +00001250 for k, v in state.items():
1251 if type(k) is str:
1252 inst_dict[intern(k)] = v
1253 else:
1254 inst_dict[k] = v
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001255 if slotstate:
1256 for k, v in slotstate.items():
1257 setattr(inst, k, v)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001258 dispatch[BUILD[0]] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001259
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001260 def load_mark(self):
1261 self.append(self.mark)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001262 dispatch[MARK[0]] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001263
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001264 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001265 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001266 raise _Stop(value)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001267 dispatch[STOP[0]] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001268
Alexander Belopolskyd92f0402010-07-17 22:50:45 +00001269# Encode/decode longs.
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001270
1271def encode_long(x):
Tim Peters91149822003-01-31 03:43:58 +00001272 r"""Encode a long to a two's complement little-endian binary string.
Guido van Rossume2a383d2007-01-15 16:59:06 +00001273 Note that 0 is a special case, returning an empty string, to save a
Tim Peters4b23f2b2003-01-31 16:43:39 +00001274 byte in the LONG1 pickling context.
1275
Guido van Rossume2a383d2007-01-15 16:59:06 +00001276 >>> encode_long(0)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001277 b''
Guido van Rossume2a383d2007-01-15 16:59:06 +00001278 >>> encode_long(255)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001279 b'\xff\x00'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001280 >>> encode_long(32767)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001281 b'\xff\x7f'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001282 >>> encode_long(-256)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001283 b'\x00\xff'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001284 >>> encode_long(-32768)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001285 b'\x00\x80'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001286 >>> encode_long(-128)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001287 b'\x80'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001288 >>> encode_long(127)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001289 b'\x7f'
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001290 >>>
1291 """
Tim Peters91149822003-01-31 03:43:58 +00001292 if x == 0:
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001293 return b''
Alexandre Vassalottid7a3da82010-01-12 01:49:31 +00001294 nbytes = (x.bit_length() >> 3) + 1
1295 result = x.to_bytes(nbytes, byteorder='little', signed=True)
1296 if x < 0 and nbytes > 1:
1297 if result[-1] == 0xff and (result[-2] & 0x80) != 0:
1298 result = result[:-1]
1299 return result
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001300
1301def decode_long(data):
1302 r"""Decode a long from a two's complement little-endian binary string.
Tim Peters4b23f2b2003-01-31 16:43:39 +00001303
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001304 >>> decode_long(b'')
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001305 0
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001306 >>> decode_long(b"\xff\x00")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001307 255
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001308 >>> decode_long(b"\xff\x7f")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001309 32767
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001310 >>> decode_long(b"\x00\xff")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001311 -256
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001312 >>> decode_long(b"\x00\x80")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001313 -32768
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001314 >>> decode_long(b"\x80")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001315 -128
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001316 >>> decode_long(b"\x7f")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001317 127
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001318 """
Alexandre Vassalottid7a3da82010-01-12 01:49:31 +00001319 return int.from_bytes(data, byteorder='little', signed=True)
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001320
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001321# Shorthands
1322
Antoine Pitroud9dfaa92009-06-04 20:32:06 +00001323def dump(obj, file, protocol=None, *, fix_imports=True):
1324 Pickler(file, protocol, fix_imports=fix_imports).dump(obj)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001325
Antoine Pitroud9dfaa92009-06-04 20:32:06 +00001326def dumps(obj, protocol=None, *, fix_imports=True):
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001327 f = io.BytesIO()
Antoine Pitroud9dfaa92009-06-04 20:32:06 +00001328 Pickler(f, protocol, fix_imports=fix_imports).dump(obj)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001329 res = f.getvalue()
Guido van Rossum98297ee2007-11-06 21:34:58 +00001330 assert isinstance(res, bytes_types)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001331 return res
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001332
Antoine Pitroud9dfaa92009-06-04 20:32:06 +00001333def load(file, *, fix_imports=True, encoding="ASCII", errors="strict"):
1334 return Unpickler(file, fix_imports=fix_imports,
1335 encoding=encoding, errors=errors).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001336
Antoine Pitroud9dfaa92009-06-04 20:32:06 +00001337def loads(s, *, fix_imports=True, encoding="ASCII", errors="strict"):
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001338 if isinstance(s, str):
1339 raise TypeError("Can't load pickle from unicode string")
1340 file = io.BytesIO(s)
Antoine Pitroud9dfaa92009-06-04 20:32:06 +00001341 return Unpickler(file, fix_imports=fix_imports,
1342 encoding=encoding, errors=errors).load()
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001343
Antoine Pitrouea99c5c2010-09-09 18:33:21 +00001344# Use the faster _pickle if possible
1345try:
1346 from _pickle import *
1347except ImportError:
1348 Pickler, Unpickler = _Pickler, _Unpickler
1349
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001350# Doctest
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001351def _test():
1352 import doctest
1353 return doctest.testmod()
1354
1355if __name__ == "__main__":
Florent Xicluna54540ec2011-11-04 08:29:17 +01001356 import argparse
Alexander Belopolsky455f7bd2010-07-27 23:02:38 +00001357 parser = argparse.ArgumentParser(
1358 description='display contents of the pickle files')
1359 parser.add_argument(
1360 'pickle_file', type=argparse.FileType('br'),
1361 nargs='*', help='the pickle file')
1362 parser.add_argument(
1363 '-t', '--test', action='store_true',
1364 help='run self-test suite')
1365 parser.add_argument(
1366 '-v', action='store_true',
1367 help='run verbosely; only affects self-test run')
1368 args = parser.parse_args()
1369 if args.test:
1370 _test()
1371 else:
1372 if not args.pickle_file:
1373 parser.print_help()
1374 else:
1375 import pprint
1376 for f in args.pickle_file:
1377 obj = load(f)
1378 pprint.pprint(obj)