blob: d121ec99b5de6945aa368087283279fdc0dace50 [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
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +030029from itertools import islice
Guido van Rossumd3703791998-10-22 20:15:36 +000030import sys
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +030031from sys import maxsize
32from struct import pack, unpack
Skip Montanaro23bafc62001-02-18 03:10:09 +000033import re
Guido van Rossum2e6a4b32007-05-04 19:56:22 +000034import io
Walter Dörwald42748a82007-06-12 16:40:17 +000035import codecs
Antoine Pitroud9dfaa92009-06-04 20:32:06 +000036import _compat_pickle
Guido van Rossuma48061a1995-01-10 00:31:14 +000037
Skip Montanaro352674d2001-02-07 23:14:30 +000038__all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler",
39 "Unpickler", "dump", "dumps", "load", "loads"]
40
Guido van Rossum98297ee2007-11-06 21:34:58 +000041# Shortcut for use in isinstance testing
Alexandre Vassalotti8cb02b62008-05-03 01:42:49 +000042bytes_types = (bytes, bytearray)
Guido van Rossum98297ee2007-11-06 21:34:58 +000043
Tim Petersc0c12b52003-01-29 00:56:17 +000044# These are purely informational; no code uses these.
Guido van Rossumf4169812008-03-17 22:56:06 +000045format_version = "3.0" # File format version we write
Guido van Rossumf29d3d62003-01-27 22:47:53 +000046compatible_formats = ["1.0", # Original protocol 0
Guido van Rossumbc64e222003-01-28 16:34:19 +000047 "1.1", # Protocol 0 with INST added
Guido van Rossumf29d3d62003-01-27 22:47:53 +000048 "1.2", # Original protocol 1
49 "1.3", # Protocol 1 with BINFLOAT added
50 "2.0", # Protocol 2
Guido van Rossumf4169812008-03-17 22:56:06 +000051 "3.0", # Protocol 3
Guido van Rossumf29d3d62003-01-27 22:47:53 +000052 ] # Old format versions we can read
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000053
Guido van Rossum99603b02007-07-20 00:22:32 +000054# This is the highest protocol number we know how to read.
Guido van Rossumf4169812008-03-17 22:56:06 +000055HIGHEST_PROTOCOL = 3
Tim Peters8587b3c2003-02-13 15:44:41 +000056
Guido van Rossum2e6a4b32007-05-04 19:56:22 +000057# The protocol we write by default. May be less than HIGHEST_PROTOCOL.
Guido van Rossumf4169812008-03-17 22:56:06 +000058# We intentionally write a protocol that Python 2.x cannot read;
59# there are too many issues with that.
60DEFAULT_PROTOCOL = 3
Guido van Rossum2e6a4b32007-05-04 19:56:22 +000061
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000062class PickleError(Exception):
Neal Norwitzefbb67b2002-05-30 12:12:04 +000063 """A common base class for the other pickling exceptions."""
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000064 pass
65
66class PicklingError(PickleError):
67 """This exception is raised when an unpicklable object is passed to the
68 dump() method.
69
70 """
71 pass
72
73class UnpicklingError(PickleError):
74 """This exception is raised when there is a problem unpickling an object,
75 such as a security violation.
76
77 Note that other exceptions may also be raised during unpickling, including
78 (but not necessarily limited to) AttributeError, EOFError, ImportError,
79 and IndexError.
80
81 """
82 pass
Guido van Rossum7849da81995-03-09 14:08:35 +000083
Tim Petersc0c12b52003-01-29 00:56:17 +000084# An instance of _Stop is raised by Unpickler.load_stop() in response to
85# the STOP opcode, passing the object that is the result of unpickling.
Guido van Rossumff871742000-12-13 18:11:56 +000086class _Stop(Exception):
87 def __init__(self, value):
88 self.value = value
89
Guido van Rossum533dbcf2003-01-28 17:55:05 +000090# Jython has PyStringMap; it's a dict subclass with string keys
Jeremy Hylton2b9d0291998-05-27 22:38:22 +000091try:
92 from org.python.core import PyStringMap
93except ImportError:
94 PyStringMap = None
95
Tim Peters22a449a2003-01-27 20:16:36 +000096# Pickle opcodes. See pickletools.py for extensive docs. The listing
97# here is in kind-of alphabetical order of 1-character pickle code.
98# pickletools groups them by purpose.
Guido van Rossumdbb718f2001-09-21 19:22:34 +000099
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000100MARK = b'(' # push special markobject on stack
101STOP = b'.' # every pickle ends with STOP
102POP = b'0' # discard topmost stack item
103POP_MARK = b'1' # discard stack top through topmost markobject
104DUP = b'2' # duplicate top stack item
105FLOAT = b'F' # push float object; decimal string argument
106INT = b'I' # push integer or bool; decimal string argument
107BININT = b'J' # push four-byte signed int
108BININT1 = b'K' # push 1-byte unsigned int
109LONG = b'L' # push long; decimal string argument
110BININT2 = b'M' # push 2-byte unsigned int
111NONE = b'N' # push None
112PERSID = b'P' # push persistent object; id is taken from string arg
113BINPERSID = b'Q' # " " " ; " " " " stack
114REDUCE = b'R' # apply callable to argtuple, both on stack
115STRING = b'S' # push string; NL-terminated string argument
116BINSTRING = b'T' # push string; counted binary string argument
117SHORT_BINSTRING= b'U' # " " ; " " " " < 256 bytes
118UNICODE = b'V' # push Unicode string; raw-unicode-escaped'd argument
119BINUNICODE = b'X' # " " " ; counted UTF-8 string argument
120APPEND = b'a' # append stack top to list below it
121BUILD = b'b' # call __setstate__ or __dict__.update()
122GLOBAL = b'c' # push self.find_class(modname, name); 2 string args
123DICT = b'd' # build a dict from stack items
124EMPTY_DICT = b'}' # push empty dict
125APPENDS = b'e' # extend list on stack by topmost stack slice
126GET = b'g' # push item from memo on stack; index is string arg
127BINGET = b'h' # " " " " " " ; " " 1-byte arg
128INST = b'i' # build & push class instance
129LONG_BINGET = b'j' # push item from memo on stack; index is 4-byte arg
130LIST = b'l' # build list from topmost stack items
131EMPTY_LIST = b']' # push empty list
132OBJ = b'o' # build & push class instance
133PUT = b'p' # store stack top in memo; index is string arg
134BINPUT = b'q' # " " " " " ; " " 1-byte arg
135LONG_BINPUT = b'r' # " " " " " ; " " 4-byte arg
136SETITEM = b's' # add key+value pair to dict
137TUPLE = b't' # build tuple from topmost stack items
138EMPTY_TUPLE = b')' # push empty tuple
139SETITEMS = b'u' # modify dict by adding topmost key+value pairs
140BINFLOAT = b'G' # push float; arg is 8-byte float encoding
Tim Peters22a449a2003-01-27 20:16:36 +0000141
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000142TRUE = b'I01\n' # not an opcode; see INT docs in pickletools.py
143FALSE = b'I00\n' # not an opcode; see INT docs in pickletools.py
Guido van Rossum77f6a652002-04-03 22:41:51 +0000144
Guido van Rossum586c9e82003-01-29 06:16:12 +0000145# Protocol 2
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000146
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000147PROTO = b'\x80' # identify pickle protocol
148NEWOBJ = b'\x81' # build object by applying cls.__new__ to argtuple
149EXT1 = b'\x82' # push object from extension registry; 1-byte index
150EXT2 = b'\x83' # ditto, but 2-byte index
151EXT4 = b'\x84' # ditto, but 4-byte index
152TUPLE1 = b'\x85' # build 1-tuple from stack top
153TUPLE2 = b'\x86' # build 2-tuple from two topmost stack items
154TUPLE3 = b'\x87' # build 3-tuple from three topmost stack items
155NEWTRUE = b'\x88' # push True
156NEWFALSE = b'\x89' # push False
157LONG1 = b'\x8a' # push long from < 256 bytes
158LONG4 = b'\x8b' # push really big long
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000159
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000160_tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3]
161
Guido van Rossumf4169812008-03-17 22:56:06 +0000162# Protocol 3 (Python 3.x)
163
164BINBYTES = b'B' # push bytes; counted binary string argument
165SHORT_BINBYTES = b'C' # " " ; " " " " < 256 bytes
Guido van Rossuma48061a1995-01-10 00:31:14 +0000166
Skip Montanaro23bafc62001-02-18 03:10:09 +0000167__all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
168
Guido van Rossum1be31752003-01-28 15:19:53 +0000169# Pickling machinery
170
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000171class _Pickler:
Guido van Rossuma48061a1995-01-10 00:31:14 +0000172
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000173 def __init__(self, file, protocol=None, *, fix_imports=True):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000174 """This takes a binary file 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
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000177 given protocol; supported protocols are 0, 1, 2, 3. The default
178 protocol is 3; a backward-incompatible protocol designed for
179 Python 3.0.
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000180
Guido van Rossum7eff63a2003-01-31 19:42:31 +0000181 Specifying a negative protocol version selects the highest
Tim Peters5bd2a792003-02-01 16:45:06 +0000182 protocol version supported. The higher the protocol used, the
183 more recent the version of Python needed to read the pickle
184 produced.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000185
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000186 The file argument must have a write() method that accepts a single
187 bytes argument. It can thus be a file object opened for binary
188 writing, a io.BytesIO instance, or any other custom object that
189 meets this interface.
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000190
191 If fix_imports is True and protocol is less than 3, pickle will try to
192 map the new Python 3.x names to the old module names used in Python
193 2.x, so that the pickle data stream is readable with Python 2.x.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000194 """
Guido van Rossumcf117b02003-02-09 17:19:41 +0000195 if protocol is None:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000196 protocol = DEFAULT_PROTOCOL
Guido van Rossumcf117b02003-02-09 17:19:41 +0000197 if protocol < 0:
Tim Peters8587b3c2003-02-13 15:44:41 +0000198 protocol = HIGHEST_PROTOCOL
199 elif not 0 <= protocol <= HIGHEST_PROTOCOL:
200 raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL)
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000201 try:
202 self.write = file.write
203 except AttributeError:
204 raise TypeError("file must have a 'write' attribute")
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000205 self.memo = {}
Guido van Rossumcf117b02003-02-09 17:19:41 +0000206 self.proto = int(protocol)
207 self.bin = protocol >= 1
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000208 self.fast = 0
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000209 self.fix_imports = fix_imports and protocol < 3
Guido van Rossuma48061a1995-01-10 00:31:14 +0000210
Fred Drake7f781c92002-05-01 20:33:53 +0000211 def clear_memo(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000212 """Clears the pickler's "memo".
213
214 The memo is the data structure that remembers which objects the
Tim Petersb377f8a2003-01-28 00:23:36 +0000215 pickler has already seen, so that shared or recursive objects are
216 pickled by reference and not by value. This method is useful when
217 re-using picklers.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000218
219 """
Fred Drake7f781c92002-05-01 20:33:53 +0000220 self.memo.clear()
221
Guido van Rossum3a41c612003-01-28 15:10:22 +0000222 def dump(self, obj):
Tim Peters5bd2a792003-02-01 16:45:06 +0000223 """Write a pickled representation of obj to the open file."""
Alexandre Vassalotti3cfcab92008-12-27 09:30:39 +0000224 # Check whether Pickler was initialized correctly. This is
225 # only needed to mimic the behavior of _pickle.Pickler.dump().
226 if not hasattr(self, "write"):
227 raise PicklingError("Pickler.__init__() was not called by "
228 "%s.__init__()" % (self.__class__.__name__,))
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000229 if self.proto >= 2:
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300230 self.write(PROTO + pack("<B", self.proto))
Guido van Rossum3a41c612003-01-28 15:10:22 +0000231 self.save(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000232 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000233
Jeremy Hylton3422c992003-01-24 19:29:52 +0000234 def memoize(self, obj):
235 """Store an object in the memo."""
236
Tim Peterse46b73f2003-01-27 21:22:10 +0000237 # The Pickler memo is a dictionary mapping object ids to 2-tuples
238 # that contain the Unpickler memo key and the object being memoized.
239 # The memo key is written to the pickle and will become
Jeremy Hylton3422c992003-01-24 19:29:52 +0000240 # the key in the Unpickler's memo. The object is stored in the
Tim Peterse46b73f2003-01-27 21:22:10 +0000241 # Pickler memo so that transient objects are kept alive during
242 # pickling.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000243
Tim Peterse46b73f2003-01-27 21:22:10 +0000244 # The use of the Unpickler memo length as the memo key is just a
245 # convention. The only requirement is that the memo values be unique.
246 # But there appears no advantage to any other scheme, and this
Tim Peterscbd0a322003-01-28 00:24:43 +0000247 # scheme allows the Unpickler memo to be implemented as a plain (but
Tim Peterse46b73f2003-01-27 21:22:10 +0000248 # growable) array, indexed by memo key.
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000249 if self.fast:
250 return
Guido van Rossum9b40e802003-01-30 06:37:41 +0000251 assert id(obj) not in self.memo
Jeremy Hylton3422c992003-01-24 19:29:52 +0000252 memo_len = len(self.memo)
253 self.write(self.put(memo_len))
Tim Peters518df0d2003-01-28 01:00:38 +0000254 self.memo[id(obj)] = memo_len, obj
Jeremy Hylton3422c992003-01-24 19:29:52 +0000255
Tim Petersbb38e302003-01-27 21:25:41 +0000256 # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300257 def put(self, i):
Tim Petersc32d8242001-04-10 02:48:53 +0000258 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000259 if i < 256:
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300260 return BINPUT + pack("<B", i)
Guido van Rossum5c938d02003-01-28 03:03:08 +0000261 else:
Antoine Pitroubf6ecf92012-11-24 20:40:21 +0100262 return LONG_BINPUT + pack("<I", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000263
Guido van Rossum39478e82007-08-27 17:23:59 +0000264 return PUT + repr(i).encode("ascii") + b'\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000265
Tim Petersbb38e302003-01-27 21:25:41 +0000266 # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300267 def get(self, i):
Tim Petersc32d8242001-04-10 02:48:53 +0000268 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000269 if i < 256:
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300270 return BINGET + pack("<B", i)
Guido van Rossum5c938d02003-01-28 03:03:08 +0000271 else:
Antoine Pitroubf6ecf92012-11-24 20:40:21 +0100272 return LONG_BINGET + pack("<I", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000273
Guido van Rossum39478e82007-08-27 17:23:59 +0000274 return GET + repr(i).encode("ascii") + b'\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000275
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000276 def save(self, obj, save_persistent_id=True):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000277 # Check for persistent id (defined by a subclass)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000278 pid = self.persistent_id(obj)
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000279 if pid is not None and save_persistent_id:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000280 self.save_pers(pid)
281 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000282
Guido van Rossumbc64e222003-01-28 16:34:19 +0000283 # Check the memo
284 x = self.memo.get(id(obj))
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300285 if x is not None:
Guido van Rossumbc64e222003-01-28 16:34:19 +0000286 self.write(self.get(x[0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000287 return
288
Guido van Rossumbc64e222003-01-28 16:34:19 +0000289 # Check the type dispatch table
Guido van Rossum3a41c612003-01-28 15:10:22 +0000290 t = type(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000291 f = self.dispatch.get(t)
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300292 if f is not None:
Guido van Rossumbc64e222003-01-28 16:34:19 +0000293 f(self, obj) # Call unbound method with explicit self
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000294 return
295
Antoine Pitrou8d3c2902012-03-04 18:31:48 +0100296 # Check private dispatch table if any, or else copyreg.dispatch_table
297 reduce = getattr(self, 'dispatch_table', dispatch_table).get(t)
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300298 if reduce is not None:
Guido van Rossumc53f0092003-02-18 22:05:12 +0000299 rv = reduce(obj)
300 else:
Antoine Pitrouffd41d92011-10-04 09:23:04 +0200301 # Check for a class with a custom metaclass; treat as regular class
302 try:
303 issc = issubclass(t, type)
304 except TypeError: # t is not a class (old Boost; see SF #502085)
305 issc = False
306 if issc:
307 self.save_global(obj)
308 return
309
Guido van Rossumc53f0092003-02-18 22:05:12 +0000310 # Check for a __reduce_ex__ method, fall back to __reduce__
311 reduce = getattr(obj, "__reduce_ex__", None)
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300312 if reduce is not None:
Guido van Rossumc53f0092003-02-18 22:05:12 +0000313 rv = reduce(self.proto)
314 else:
315 reduce = getattr(obj, "__reduce__", None)
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300316 if reduce is not None:
Guido van Rossumc53f0092003-02-18 22:05:12 +0000317 rv = reduce()
318 else:
319 raise PicklingError("Can't pickle %r object: %r" %
320 (t.__name__, obj))
Tim Petersb32a8312003-01-28 00:48:09 +0000321
Guido van Rossumbc64e222003-01-28 16:34:19 +0000322 # Check for string returned by reduce(), meaning "save as global"
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000323 if isinstance(rv, str):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000324 self.save_global(obj, rv)
Tim Petersb32a8312003-01-28 00:48:09 +0000325 return
326
Guido van Rossumbc64e222003-01-28 16:34:19 +0000327 # Assert that reduce() returned a tuple
Guido van Rossum13257902007-06-07 23:15:56 +0000328 if not isinstance(rv, tuple):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000329 raise PicklingError("%s must return string or tuple" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000330
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000331 # Assert that it returned an appropriately sized tuple
Guido van Rossumbc64e222003-01-28 16:34:19 +0000332 l = len(rv)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000333 if not (2 <= l <= 5):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000334 raise PicklingError("Tuple returned by %s must have "
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000335 "two to five elements" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000336
Guido van Rossumbc64e222003-01-28 16:34:19 +0000337 # Save the reduce() output and finally memoize the object
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000338 self.save_reduce(obj=obj, *rv)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000339
Guido van Rossum3a41c612003-01-28 15:10:22 +0000340 def persistent_id(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000341 # This exists so a subclass can override it
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000342 return None
343
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000344 def save_pers(self, pid):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000345 # Save a persistent id reference
Tim Petersbd1cdb92003-01-28 01:03:10 +0000346 if self.bin:
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000347 self.save(pid, save_persistent_id=False)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000348 self.write(BINPERSID)
Tim Petersbd1cdb92003-01-28 01:03:10 +0000349 else:
Guido van Rossum39478e82007-08-27 17:23:59 +0000350 self.write(PERSID + str(pid).encode("ascii") + b'\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000351
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000352 def save_reduce(self, func, args, state=None,
353 listitems=None, dictitems=None, obj=None):
Jeremy Hyltone3a565e2003-06-29 16:59:59 +0000354 # This API is called by some subclasses
Guido van Rossumbc64e222003-01-28 16:34:19 +0000355
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000356 # Assert that args is a tuple
Guido van Rossum13257902007-06-07 23:15:56 +0000357 if not isinstance(args, tuple):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000358 raise PicklingError("args from save_reduce() should be a tuple")
Guido van Rossumbc64e222003-01-28 16:34:19 +0000359
360 # Assert that func is callable
Florent Xicluna5d1155c2011-10-28 14:45:05 +0200361 if not callable(func):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000362 raise PicklingError("func from save_reduce() should be callable")
Guido van Rossumbc64e222003-01-28 16:34:19 +0000363
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000364 save = self.save
Guido van Rossumbc64e222003-01-28 16:34:19 +0000365 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000366
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000367 # Protocol 2 special case: if func's name is __newobj__, use NEWOBJ
368 if self.proto >= 2 and getattr(func, "__name__", "") == "__newobj__":
369 # A __reduce__ implementation can direct protocol 2 to
370 # use the more efficient NEWOBJ opcode, while still
371 # allowing protocol 0 and 1 to work normally. For this to
372 # work, the function returned by __reduce__ should be
373 # called __newobj__, and its first argument should be a
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100374 # class. The implementation for __newobj__
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000375 # should be as follows, although pickle has no way to
376 # verify this:
377 #
378 # def __newobj__(cls, *args):
379 # return cls.__new__(cls, *args)
380 #
381 # Protocols 0 and 1 will pickle a reference to __newobj__,
382 # while protocol 2 (and above) will pickle a reference to
383 # cls, the remaining args tuple, and the NEWOBJ code,
384 # which calls cls.__new__(cls, *args) at unpickling time
385 # (see load_newobj below). If __reduce__ returns a
386 # three-tuple, the state from the third tuple item will be
387 # pickled regardless of the protocol, calling __setstate__
388 # at unpickling time (see load_build below).
389 #
390 # Note that no standard __newobj__ implementation exists;
391 # you have to provide your own. This is to enforce
392 # compatibility with Python 2.2 (pickles written using
393 # protocol 0 or 1 in Python 2.3 should be unpicklable by
394 # Python 2.2).
395 cls = args[0]
396 if not hasattr(cls, "__new__"):
397 raise PicklingError(
398 "args[0] from __newobj__ args has no __new__")
Guido van Rossumf7f45172003-01-31 17:17:49 +0000399 if obj is not None and cls is not obj.__class__:
400 raise PicklingError(
401 "args[0] from __newobj__ args has the wrong class")
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000402 args = args[1:]
403 save(cls)
404 save(args)
405 write(NEWOBJ)
406 else:
407 save(func)
408 save(args)
409 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000410
Guido van Rossumf7f45172003-01-31 17:17:49 +0000411 if obj is not None:
412 self.memoize(obj)
413
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000414 # More new special cases (that work with older protocols as
415 # well): when __reduce__ returns a tuple with 4 or 5 items,
416 # the 4th and 5th item should be iterators that provide list
417 # items and dict items (as (key, value) tuples), or None.
418
419 if listitems is not None:
420 self._batch_appends(listitems)
421
422 if dictitems is not None:
423 self._batch_setitems(dictitems)
424
Tim Petersc32d8242001-04-10 02:48:53 +0000425 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000426 save(state)
427 write(BUILD)
428
Guido van Rossumbc64e222003-01-28 16:34:19 +0000429 # Methods below this point are dispatched through the dispatch table
430
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000431 dispatch = {}
432
Guido van Rossum3a41c612003-01-28 15:10:22 +0000433 def save_none(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000434 self.write(NONE)
Guido van Rossum13257902007-06-07 23:15:56 +0000435 dispatch[type(None)] = save_none
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000436
Łukasz Langaf3078fb2012-03-12 19:46:12 +0100437 def save_ellipsis(self, obj):
438 self.save_global(Ellipsis, 'Ellipsis')
439 dispatch[type(Ellipsis)] = save_ellipsis
440
441 def save_notimplemented(self, obj):
442 self.save_global(NotImplemented, 'NotImplemented')
443 dispatch[type(NotImplemented)] = save_notimplemented
444
Guido van Rossum3a41c612003-01-28 15:10:22 +0000445 def save_bool(self, obj):
Guido van Rossum7d97d312003-01-28 04:25:27 +0000446 if self.proto >= 2:
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300447 self.write(NEWTRUE if obj else NEWFALSE)
Guido van Rossum7d97d312003-01-28 04:25:27 +0000448 else:
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300449 self.write(TRUE if obj else FALSE)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000450 dispatch[bool] = save_bool
451
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300452 def save_long(self, obj):
Guido van Rossumddefaf32007-01-14 03:31:43 +0000453 if self.bin:
454 # If the int is small enough to fit in a signed 4-byte 2's-comp
455 # format, we can store it more efficiently than the general
456 # case.
457 # First one- and two-byte unsigned ints:
458 if obj >= 0:
459 if obj <= 0xff:
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300460 self.write(BININT1 + pack("<B", obj))
Guido van Rossumddefaf32007-01-14 03:31:43 +0000461 return
462 if obj <= 0xffff:
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300463 self.write(BININT2 + pack("<H", obj))
Guido van Rossumddefaf32007-01-14 03:31:43 +0000464 return
465 # Next check for 4-byte signed ints:
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300466 if -0x80000000 <= obj <= 0x7fffffff:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000467 self.write(BININT + pack("<i", obj))
468 return
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000469 if self.proto >= 2:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000470 encoded = encode_long(obj)
471 n = len(encoded)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000472 if n < 256:
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300473 self.write(LONG1 + pack("<B", n) + encoded)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000474 else:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000475 self.write(LONG4 + pack("<i", n) + encoded)
Tim Petersee1a53c2003-02-02 02:57:53 +0000476 return
Mark Dickinson8dd05142009-01-20 20:43:58 +0000477 self.write(LONG + repr(obj).encode("ascii") + b'L\n')
Guido van Rossum13257902007-06-07 23:15:56 +0000478 dispatch[int] = save_long
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000479
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300480 def save_float(self, obj):
Guido van Rossumd3703791998-10-22 20:15:36 +0000481 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000482 self.write(BINFLOAT + pack('>d', obj))
Guido van Rossumd3703791998-10-22 20:15:36 +0000483 else:
Guido van Rossum39478e82007-08-27 17:23:59 +0000484 self.write(FLOAT + repr(obj).encode("ascii") + b'\n')
Guido van Rossum13257902007-06-07 23:15:56 +0000485 dispatch[float] = save_float
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000486
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300487 def save_bytes(self, obj):
Guido van Rossumf4169812008-03-17 22:56:06 +0000488 if self.proto < 3:
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300489 if not obj: # bytes object is empty
Alexandre Vassalotti3bfc65a2011-12-13 13:08:09 -0500490 self.save_reduce(bytes, (), obj=obj)
491 else:
492 self.save_reduce(codecs.encode,
493 (str(obj, 'latin1'), 'latin1'), obj=obj)
Guido van Rossumf4169812008-03-17 22:56:06 +0000494 return
495 n = len(obj)
496 if n < 256:
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300497 self.write(SHORT_BINBYTES + pack("<B", n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000498 else:
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300499 self.write(BINBYTES + pack("<I", n) + obj)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000500 self.memoize(obj)
Guido van Rossumf4169812008-03-17 22:56:06 +0000501 dispatch[bytes] = save_bytes
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000502
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300503 def save_str(self, obj):
Tim Petersc32d8242001-04-10 02:48:53 +0000504 if self.bin:
Victor Stinner485fb562010-04-13 11:07:24 +0000505 encoded = obj.encode('utf-8', 'surrogatepass')
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000506 n = len(encoded)
Antoine Pitroubf6ecf92012-11-24 20:40:21 +0100507 self.write(BINUNICODE + pack("<I", n) + encoded)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000508 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000509 obj = obj.replace("\\", "\\u005c")
510 obj = obj.replace("\n", "\\u000a")
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300511 self.write(UNICODE + obj.encode('raw-unicode-escape') + b'\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000512 self.memoize(obj)
Guido van Rossumf4169812008-03-17 22:56:06 +0000513 dispatch[str] = save_str
Tim Peters658cba62001-02-09 20:06:00 +0000514
Guido van Rossum3a41c612003-01-28 15:10:22 +0000515 def save_tuple(self, obj):
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300516 if not obj: # tuple is empty
517 if self.bin:
518 self.write(EMPTY_TUPLE)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000519 else:
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300520 self.write(MARK + TUPLE)
Tim Petersd97da802003-01-28 05:48:29 +0000521 return
522
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300523 n = len(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000524 save = self.save
525 memo = self.memo
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300526 if n <= 3 and self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000527 for element in obj:
Tim Petersd97da802003-01-28 05:48:29 +0000528 save(element)
529 # Subtle. Same as in the big comment below.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000530 if id(obj) in memo:
531 get = self.get(memo[id(obj)][0])
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300532 self.write(POP * n + get)
Tim Petersd97da802003-01-28 05:48:29 +0000533 else:
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300534 self.write(_tuplesize2code[n])
Guido van Rossum3a41c612003-01-28 15:10:22 +0000535 self.memoize(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000536 return
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000537
Tim Peters1d63c9f2003-02-02 20:29:39 +0000538 # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple
Tim Petersff57bff2003-01-28 05:34:53 +0000539 # has more than 3 elements.
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300540 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000541 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000542 for element in obj:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000543 save(element)
544
Tim Peters1d63c9f2003-02-02 20:29:39 +0000545 if id(obj) in memo:
Tim Petersf558da02003-01-28 02:09:55 +0000546 # Subtle. d was not in memo when we entered save_tuple(), so
547 # the process of saving the tuple's elements must have saved
548 # the tuple itself: the tuple is recursive. The proper action
549 # now is to throw away everything we put on the stack, and
550 # simply GET the tuple (it's already constructed). This check
551 # could have been done in the "for element" loop instead, but
552 # recursive tuples are a rare thing.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000553 get = self.get(memo[id(obj)][0])
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300554 if self.bin:
Tim Petersf558da02003-01-28 02:09:55 +0000555 write(POP_MARK + get)
556 else: # proto 0 -- POP_MARK not available
Tim Petersd97da802003-01-28 05:48:29 +0000557 write(POP * (n+1) + get)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000558 return
559
Tim Peters1d63c9f2003-02-02 20:29:39 +0000560 # No recursion.
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300561 write(TUPLE)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000562 self.memoize(obj)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000563
Guido van Rossum13257902007-06-07 23:15:56 +0000564 dispatch[tuple] = save_tuple
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000565
Guido van Rossum3a41c612003-01-28 15:10:22 +0000566 def save_list(self, obj):
Tim Petersc32d8242001-04-10 02:48:53 +0000567 if self.bin:
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300568 self.write(EMPTY_LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000569 else: # proto 0 -- can't use EMPTY_LIST
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300570 self.write(MARK + LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000571
572 self.memoize(obj)
Alexandre Vassalottic7db1d62008-05-14 21:57:18 +0000573 self._batch_appends(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000574
Guido van Rossum13257902007-06-07 23:15:56 +0000575 dispatch[list] = save_list
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000576
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000577 _BATCHSIZE = 1000
578
579 def _batch_appends(self, items):
580 # Helper to batch up APPENDS sequences
581 save = self.save
582 write = self.write
583
584 if not self.bin:
585 for x in items:
586 save(x)
587 write(APPEND)
588 return
589
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300590 it = iter(items)
591 while True:
592 tmp = list(islice(it, self._BATCHSIZE))
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000593 n = len(tmp)
594 if n > 1:
595 write(MARK)
596 for x in tmp:
597 save(x)
598 write(APPENDS)
599 elif n:
600 save(tmp[0])
601 write(APPEND)
602 # else tmp is empty, and we're done
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300603 if n < self._BATCHSIZE:
604 return
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000605
Guido van Rossum3a41c612003-01-28 15:10:22 +0000606 def save_dict(self, obj):
Tim Petersc32d8242001-04-10 02:48:53 +0000607 if self.bin:
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300608 self.write(EMPTY_DICT)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000609 else: # proto 0 -- can't use EMPTY_DICT
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300610 self.write(MARK + DICT)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000611
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000612 self.memoize(obj)
Alexandre Vassalottic7db1d62008-05-14 21:57:18 +0000613 self._batch_setitems(obj.items())
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000614
Guido van Rossum13257902007-06-07 23:15:56 +0000615 dispatch[dict] = save_dict
616 if PyStringMap is not None:
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000617 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000618
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000619 def _batch_setitems(self, items):
620 # Helper to batch up SETITEMS sequences; proto >= 1 only
621 save = self.save
622 write = self.write
623
624 if not self.bin:
625 for k, v in items:
626 save(k)
627 save(v)
628 write(SETITEM)
629 return
630
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300631 it = iter(items)
632 while True:
633 tmp = list(islice(it, self._BATCHSIZE))
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000634 n = len(tmp)
635 if n > 1:
636 write(MARK)
637 for k, v in tmp:
638 save(k)
639 save(v)
640 write(SETITEMS)
641 elif n:
642 k, v = tmp[0]
643 save(k)
644 save(v)
645 write(SETITEM)
646 # else tmp is empty, and we're done
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300647 if n < self._BATCHSIZE:
648 return
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000649
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300650 def save_global(self, obj, name=None):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000651 write = self.write
652 memo = self.memo
653
Tim Petersc32d8242001-04-10 02:48:53 +0000654 if name is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000655 name = obj.__name__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000656
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000657 module = getattr(obj, "__module__", None)
658 if module is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000659 module = whichmodule(obj, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000660
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000661 try:
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000662 __import__(module, level=0)
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000663 mod = sys.modules[module]
664 klass = getattr(mod, name)
665 except (ImportError, KeyError, AttributeError):
666 raise PicklingError(
667 "Can't pickle %r: it's not found as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000668 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000669 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000670 if klass is not obj:
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000671 raise PicklingError(
672 "Can't pickle %r: it's not the same object as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000673 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000674
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000675 if self.proto >= 2:
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000676 code = _extension_registry.get((module, name))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000677 if code:
678 assert code > 0
679 if code <= 0xff:
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300680 write(EXT1 + pack("<B", code))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000681 elif code <= 0xffff:
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300682 write(EXT2 + pack("<H", code))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000683 else:
684 write(EXT4 + pack("<i", code))
685 return
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000686 # Non-ASCII identifiers are supported only with protocols >= 3.
687 if self.proto >= 3:
688 write(GLOBAL + bytes(module, "utf-8") + b'\n' +
689 bytes(name, "utf-8") + b'\n')
690 else:
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000691 if self.fix_imports:
692 if (module, name) in _compat_pickle.REVERSE_NAME_MAPPING:
693 module, name = _compat_pickle.REVERSE_NAME_MAPPING[(module, name)]
694 if module in _compat_pickle.REVERSE_IMPORT_MAPPING:
695 module = _compat_pickle.REVERSE_IMPORT_MAPPING[module]
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000696 try:
697 write(GLOBAL + bytes(module, "ascii") + b'\n' +
698 bytes(name, "ascii") + b'\n')
699 except UnicodeEncodeError:
700 raise PicklingError(
701 "can't pickle global identifier '%s.%s' using "
702 "pickle protocol %i" % (module, name, self.proto))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000703
Guido van Rossum3a41c612003-01-28 15:10:22 +0000704 self.memoize(obj)
Tim Peters3b769832003-01-28 03:51:36 +0000705
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000706 dispatch[FunctionType] = save_global
707 dispatch[BuiltinFunctionType] = save_global
Guido van Rossum13257902007-06-07 23:15:56 +0000708 dispatch[type] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000709
Tim Petersc0c12b52003-01-29 00:56:17 +0000710# A cache for whichmodule(), mapping a function object to the name of
711# the module in which the function was found.
712
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000713classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000714
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000715def whichmodule(func, funcname):
716 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000717
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000718 Search sys.modules for the module.
719 Cache in classmap.
720 Return a module name.
Tim Petersc0c12b52003-01-29 00:56:17 +0000721 If the function cannot be found, return "__main__".
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000722 """
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000723 # Python functions should always get an __module__ from their globals.
724 mod = getattr(func, "__module__", None)
725 if mod is not None:
726 return mod
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000727 if func in classmap:
728 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000729
Guido van Rossum634e53f2007-02-26 07:07:02 +0000730 for name, module in list(sys.modules.items()):
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000731 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000732 continue # skip dummy package entries
Jeremy Hyltoncc1fccb2003-02-06 16:23:01 +0000733 if name != '__main__' and getattr(module, funcname, None) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000734 break
735 else:
736 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000737 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000738 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000739
740
Guido van Rossum1be31752003-01-28 15:19:53 +0000741# Unpickling machinery
742
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000743class _Unpickler:
Guido van Rossuma48061a1995-01-10 00:31:14 +0000744
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000745 def __init__(self, file, *, fix_imports=True,
746 encoding="ASCII", errors="strict"):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000747 """This takes a binary file for reading a pickle data stream.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000748
Tim Peters5bd2a792003-02-01 16:45:06 +0000749 The protocol version of the pickle is detected automatically, so no
750 proto argument is needed.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000751
Guido van Rossumfeea0782007-10-10 18:00:50 +0000752 The file-like object must have two methods, a read() method
753 that takes an integer argument, and a readline() method that
754 requires no arguments. Both methods should return bytes.
755 Thus file-like object can be a binary file object opened for
756 reading, a BytesIO object, or any other custom object that
757 meets this interface.
Guido van Rossumf4169812008-03-17 22:56:06 +0000758
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000759 Optional keyword arguments are *fix_imports*, *encoding* and *errors*,
760 which are used to control compatiblity support for pickle stream
761 generated by Python 2.x. If *fix_imports* is True, pickle will try to
762 map the old Python 2.x names to the new names used in Python 3.x. The
763 *encoding* and *errors* tell pickle how to decode 8-bit string
764 instances pickled by Python 2.x; these default to 'ASCII' and
765 'strict', respectively.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000766 """
Guido van Rossumfeea0782007-10-10 18:00:50 +0000767 self.readline = file.readline
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000768 self.read = file.read
769 self.memo = {}
Guido van Rossumf4169812008-03-17 22:56:06 +0000770 self.encoding = encoding
771 self.errors = errors
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000772 self.proto = 0
773 self.fix_imports = fix_imports
Guido van Rossuma48061a1995-01-10 00:31:14 +0000774
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000775 def load(self):
Guido van Rossum3a41c612003-01-28 15:10:22 +0000776 """Read a pickled object representation from the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000777
Guido van Rossum3a41c612003-01-28 15:10:22 +0000778 Return the reconstituted object hierarchy specified in the file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000779 """
Alexandre Vassalotti3cfcab92008-12-27 09:30:39 +0000780 # Check whether Unpickler was initialized correctly. This is
781 # only needed to mimic the behavior of _pickle.Unpickler.dump().
782 if not hasattr(self, "read"):
783 raise UnpicklingError("Unpickler.__init__() was not called by "
784 "%s.__init__()" % (self.__class__.__name__,))
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000785 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000786 self.stack = []
787 self.append = self.stack.append
788 read = self.read
789 dispatch = self.dispatch
790 try:
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300791 while True:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000792 key = read(1)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000793 if not key:
794 raise EOFError
Guido van Rossum98297ee2007-11-06 21:34:58 +0000795 assert isinstance(key, bytes_types)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000796 dispatch[key[0]](self)
Guido van Rossumb940e112007-01-10 16:19:56 +0000797 except _Stop as stopinst:
Guido van Rossumff871742000-12-13 18:11:56 +0000798 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000799
Tim Petersc23d18a2003-01-28 01:41:51 +0000800 # Return largest index k such that self.stack[k] is self.mark.
801 # If the stack doesn't contain a mark, eventually raises IndexError.
802 # This could be sped by maintaining another stack, of indices at which
803 # the mark appears. For that matter, the latter stack would suffice,
804 # and we wouldn't need to push mark objects on self.stack at all.
805 # Doing so is probably a good thing, though, since if the pickle is
806 # corrupt (or hostile) we may get a clue from finding self.mark embedded
807 # in unpickled objects.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000808 def marker(self):
809 stack = self.stack
810 mark = self.mark
811 k = len(stack)-1
812 while stack[k] is not mark: k = k-1
813 return k
814
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000815 def persistent_load(self, pid):
Benjamin Peterson49956b22009-01-10 17:05:44 +0000816 raise UnpicklingError("unsupported persistent id encountered")
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000817
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000818 dispatch = {}
819
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000820 def load_proto(self):
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300821 proto = self.read(1)[0]
Guido van Rossumf4169812008-03-17 22:56:06 +0000822 if not 0 <= proto <= HIGHEST_PROTOCOL:
Guido van Rossum26d95c32007-08-27 23:18:54 +0000823 raise ValueError("unsupported pickle protocol: %d" % proto)
Antoine Pitroud9dfaa92009-06-04 20:32:06 +0000824 self.proto = proto
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000825 dispatch[PROTO[0]] = load_proto
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000826
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000827 def load_persid(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000828 pid = self.readline()[:-1].decode("ascii")
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000829 self.append(self.persistent_load(pid))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000830 dispatch[PERSID[0]] = load_persid
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000831
832 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000833 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000834 self.append(self.persistent_load(pid))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000835 dispatch[BINPERSID[0]] = load_binpersid
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000836
837 def load_none(self):
838 self.append(None)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000839 dispatch[NONE[0]] = load_none
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000840
Guido van Rossum7d97d312003-01-28 04:25:27 +0000841 def load_false(self):
842 self.append(False)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000843 dispatch[NEWFALSE[0]] = load_false
Guido van Rossum7d97d312003-01-28 04:25:27 +0000844
845 def load_true(self):
846 self.append(True)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000847 dispatch[NEWTRUE[0]] = load_true
Guido van Rossum7d97d312003-01-28 04:25:27 +0000848
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000849 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000850 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000851 if data == FALSE[1:]:
852 val = False
853 elif data == TRUE[1:]:
854 val = True
855 else:
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300856 val = int(data, 0)
Guido van Rossume2763392002-04-05 19:30:08 +0000857 self.append(val)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000858 dispatch[INT[0]] = load_int
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000859
860 def load_binint(self):
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300861 self.append(unpack('<i', self.read(4))[0])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000862 dispatch[BININT[0]] = load_binint
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000863
864 def load_binint1(self):
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300865 self.append(self.read(1)[0])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000866 dispatch[BININT1[0]] = load_binint1
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000867
868 def load_binint2(self):
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300869 self.append(unpack('<H', self.read(2))[0])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000870 dispatch[BININT2[0]] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000871
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000872 def load_long(self):
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300873 val = self.readline()[:-1]
874 if val and val[-1] == b'L'[0]:
Mark Dickinson8dd05142009-01-20 20:43:58 +0000875 val = val[:-1]
Guido van Rossumfeea0782007-10-10 18:00:50 +0000876 self.append(int(val, 0))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000877 dispatch[LONG[0]] = load_long
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000878
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000879 def load_long1(self):
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300880 n = self.read(1)[0]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000881 data = self.read(n)
882 self.append(decode_long(data))
883 dispatch[LONG1[0]] = load_long1
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000884
885 def load_long4(self):
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300886 n, = unpack('<i', self.read(4))
Antoine Pitroubf6ecf92012-11-24 20:40:21 +0100887 if n < 0:
888 # Corrupt or hostile pickle -- we never write one like this
Alexandre Vassalotticc757172013-04-14 02:25:10 -0700889 raise UnpicklingError("LONG pickle has negative byte count")
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000890 data = self.read(n)
891 self.append(decode_long(data))
892 dispatch[LONG4[0]] = load_long4
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000893
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000894 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000895 self.append(float(self.readline()[:-1]))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000896 dispatch[FLOAT[0]] = load_float
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000897
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300898 def load_binfloat(self):
Guido van Rossumd3703791998-10-22 20:15:36 +0000899 self.append(unpack('>d', self.read(8))[0])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000900 dispatch[BINFLOAT[0]] = load_binfloat
Guido van Rossumd3703791998-10-22 20:15:36 +0000901
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000902 def load_string(self):
Alexandre Vassalotti7c5e0942013-04-15 23:14:55 -0700903 data = self.readline()[:-1]
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300904 # Strip outermost quotes
Alexandre Vassalotti7c5e0942013-04-15 23:14:55 -0700905 if len(data) >= 2 and data[0] == data[-1] and data[0] in b'"\'':
906 data = data[1:-1]
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000907 else:
Alexandre Vassalotti7c5e0942013-04-15 23:14:55 -0700908 raise UnpicklingError("the STRING opcode argument must be quoted")
909 self.append(codecs.escape_decode(data)[0]
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000910 .decode(self.encoding, self.errors))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000911 dispatch[STRING[0]] = load_string
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000912
913 def load_binstring(self):
Antoine Pitroubf6ecf92012-11-24 20:40:21 +0100914 # Deprecated BINSTRING uses signed 32-bit length
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300915 len, = unpack('<i', self.read(4))
Antoine Pitroubf6ecf92012-11-24 20:40:21 +0100916 if len < 0:
Alexandre Vassalotticc757172013-04-14 02:25:10 -0700917 raise UnpicklingError("BINSTRING pickle has negative byte count")
Guido van Rossumf4169812008-03-17 22:56:06 +0000918 data = self.read(len)
919 value = str(data, self.encoding, self.errors)
920 self.append(value)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000921 dispatch[BINSTRING[0]] = load_binstring
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000922
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300923 def load_binbytes(self):
Antoine Pitroubf6ecf92012-11-24 20:40:21 +0100924 len, = unpack('<I', self.read(4))
925 if len > maxsize:
Alexandre Vassalotticc757172013-04-14 02:25:10 -0700926 raise UnpicklingError("BINBYTES exceeds system's maximum size "
927 "of %d bytes" % maxsize)
Guido van Rossumf4169812008-03-17 22:56:06 +0000928 self.append(self.read(len))
929 dispatch[BINBYTES[0]] = load_binbytes
930
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000931 def load_unicode(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000932 self.append(str(self.readline()[:-1], 'raw-unicode-escape'))
933 dispatch[UNICODE[0]] = load_unicode
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000934
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300935 def load_binunicode(self):
Antoine Pitroubf6ecf92012-11-24 20:40:21 +0100936 len, = unpack('<I', self.read(4))
937 if len > maxsize:
Alexandre Vassalotticc757172013-04-14 02:25:10 -0700938 raise UnpicklingError("BINUNICODE exceeds system's maximum size "
939 "of %d bytes" % maxsize)
Victor Stinner485fb562010-04-13 11:07:24 +0000940 self.append(str(self.read(len), 'utf-8', 'surrogatepass'))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000941 dispatch[BINUNICODE[0]] = load_binunicode
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000942
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000943 def load_short_binstring(self):
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300944 len = self.read(1)[0]
945 data = self.read(len)
Guido van Rossumf4169812008-03-17 22:56:06 +0000946 value = str(data, self.encoding, self.errors)
947 self.append(value)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000948 dispatch[SHORT_BINSTRING[0]] = load_short_binstring
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000949
Guido van Rossumf4169812008-03-17 22:56:06 +0000950 def load_short_binbytes(self):
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300951 len = self.read(1)[0]
952 self.append(self.read(len))
Guido van Rossumf4169812008-03-17 22:56:06 +0000953 dispatch[SHORT_BINBYTES[0]] = load_short_binbytes
954
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000955 def load_tuple(self):
956 k = self.marker()
957 self.stack[k:] = [tuple(self.stack[k+1:])]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000958 dispatch[TUPLE[0]] = load_tuple
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000959
960 def load_empty_tuple(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000961 self.append(())
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000962 dispatch[EMPTY_TUPLE[0]] = load_empty_tuple
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000963
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000964 def load_tuple1(self):
965 self.stack[-1] = (self.stack[-1],)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000966 dispatch[TUPLE1[0]] = load_tuple1
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000967
968 def load_tuple2(self):
969 self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000970 dispatch[TUPLE2[0]] = load_tuple2
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000971
972 def load_tuple3(self):
973 self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000974 dispatch[TUPLE3[0]] = load_tuple3
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000975
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000976 def load_empty_list(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000977 self.append([])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000978 dispatch[EMPTY_LIST[0]] = load_empty_list
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000979
980 def load_empty_dictionary(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000981 self.append({})
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000982 dispatch[EMPTY_DICT[0]] = load_empty_dictionary
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000983
984 def load_list(self):
985 k = self.marker()
986 self.stack[k:] = [self.stack[k+1:]]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000987 dispatch[LIST[0]] = load_list
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000988
989 def load_dict(self):
990 k = self.marker()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000991 items = self.stack[k+1:]
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +0300992 d = {items[i]: items[i+1]
993 for i in range(0, len(items), 2)}
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000994 self.stack[k:] = [d]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000995 dispatch[DICT[0]] = load_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000996
Tim Petersd01c1e92003-01-30 15:41:46 +0000997 # INST and OBJ differ only in how they get a class object. It's not
998 # only sensible to do the rest in a common routine, the two routines
999 # previously diverged and grew different bugs.
1000 # klass is the class to instantiate, and k points to the topmost mark
1001 # object, following which are the arguments for klass.__init__.
1002 def _instantiate(self, klass, k):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001003 args = tuple(self.stack[k+1:])
1004 del self.stack[k:]
Alexander Belopolskyd92f0402010-07-17 22:50:45 +00001005 if (args or not isinstance(klass, type) or
1006 hasattr(klass, "__getinitargs__")):
Guido van Rossum743d17e1998-09-15 20:25:57 +00001007 try:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001008 value = klass(*args)
Guido van Rossumb940e112007-01-10 16:19:56 +00001009 except TypeError as err:
Guido van Rossum26d95c32007-08-27 23:18:54 +00001010 raise TypeError("in constructor for %s: %s" %
1011 (klass.__name__, str(err)), sys.exc_info()[2])
Alexander Belopolskyd92f0402010-07-17 22:50:45 +00001012 else:
1013 value = klass.__new__(klass)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001014 self.append(value)
Tim Petersd01c1e92003-01-30 15:41:46 +00001015
1016 def load_inst(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001017 module = self.readline()[:-1].decode("ascii")
1018 name = self.readline()[:-1].decode("ascii")
Tim Petersd01c1e92003-01-30 15:41:46 +00001019 klass = self.find_class(module, name)
1020 self._instantiate(klass, self.marker())
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001021 dispatch[INST[0]] = load_inst
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001022
1023 def load_obj(self):
Tim Petersd01c1e92003-01-30 15:41:46 +00001024 # Stack is ... markobject classobject arg1 arg2 ...
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001025 k = self.marker()
Tim Petersd01c1e92003-01-30 15:41:46 +00001026 klass = self.stack.pop(k+1)
1027 self._instantiate(klass, k)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001028 dispatch[OBJ[0]] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001029
Guido van Rossum3a41c612003-01-28 15:10:22 +00001030 def load_newobj(self):
1031 args = self.stack.pop()
1032 cls = self.stack[-1]
1033 obj = cls.__new__(cls, *args)
Guido van Rossum533dbcf2003-01-28 17:55:05 +00001034 self.stack[-1] = obj
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001035 dispatch[NEWOBJ[0]] = load_newobj
Guido van Rossum3a41c612003-01-28 15:10:22 +00001036
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001037 def load_global(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001038 module = self.readline()[:-1].decode("utf-8")
1039 name = self.readline()[:-1].decode("utf-8")
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001040 klass = self.find_class(module, name)
1041 self.append(klass)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001042 dispatch[GLOBAL[0]] = load_global
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001043
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001044 def load_ext1(self):
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +03001045 code = self.read(1)[0]
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001046 self.get_extension(code)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001047 dispatch[EXT1[0]] = load_ext1
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001048
1049 def load_ext2(self):
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +03001050 code, = unpack('<H', self.read(2))
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001051 self.get_extension(code)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001052 dispatch[EXT2[0]] = load_ext2
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001053
1054 def load_ext4(self):
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +03001055 code, = unpack('<i', self.read(4))
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001056 self.get_extension(code)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001057 dispatch[EXT4[0]] = load_ext4
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001058
1059 def get_extension(self, code):
1060 nil = []
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001061 obj = _extension_cache.get(code, nil)
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001062 if obj is not nil:
1063 self.append(obj)
1064 return
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001065 key = _inverted_registry.get(code)
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001066 if not key:
Antoine Pitroubf6ecf92012-11-24 20:40:21 +01001067 if code <= 0: # note that 0 is forbidden
1068 # Corrupt or hostile pickle.
Alexandre Vassalotticc757172013-04-14 02:25:10 -07001069 raise UnpicklingError("EXT specifies code <= 0")
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001070 raise ValueError("unregistered extension code %d" % code)
1071 obj = self.find_class(*key)
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001072 _extension_cache[code] = obj
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001073 self.append(obj)
1074
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001075 def find_class(self, module, name):
Antoine Pitroud9dfaa92009-06-04 20:32:06 +00001076 # Subclasses may override this.
1077 if self.proto < 3 and self.fix_imports:
1078 if (module, name) in _compat_pickle.NAME_MAPPING:
1079 module, name = _compat_pickle.NAME_MAPPING[(module, name)]
1080 if module in _compat_pickle.IMPORT_MAPPING:
1081 module = _compat_pickle.IMPORT_MAPPING[module]
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001082 __import__(module, level=0)
Barry Warsawbf4d9592001-11-15 23:42:58 +00001083 mod = sys.modules[module]
1084 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001085 return klass
1086
1087 def load_reduce(self):
1088 stack = self.stack
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001089 args = stack.pop()
1090 func = stack[-1]
Guido van Rossum99603b02007-07-20 00:22:32 +00001091 try:
1092 value = func(*args)
1093 except:
1094 print(sys.exc_info())
1095 print(func, args)
1096 raise
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001097 stack[-1] = value
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001098 dispatch[REDUCE[0]] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +00001099
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001100 def load_pop(self):
1101 del self.stack[-1]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001102 dispatch[POP[0]] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +00001103
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001104 def load_pop_mark(self):
1105 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001106 del self.stack[k:]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001107 dispatch[POP_MARK[0]] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001108
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001109 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +00001110 self.append(self.stack[-1])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001111 dispatch[DUP[0]] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +00001112
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001113 def load_get(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001114 i = int(self.readline()[:-1])
1115 self.append(self.memo[i])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001116 dispatch[GET[0]] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +00001117
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001118 def load_binget(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001119 i = self.read(1)[0]
1120 self.append(self.memo[i])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001121 dispatch[BINGET[0]] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001122
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +03001123 def load_long_binget(self):
Antoine Pitroubf6ecf92012-11-24 20:40:21 +01001124 i, = unpack('<I', self.read(4))
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001125 self.append(self.memo[i])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001126 dispatch[LONG_BINGET[0]] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001127
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001128 def load_put(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001129 i = int(self.readline()[:-1])
Antoine Pitrou55549ec2011-08-30 00:27:10 +02001130 if i < 0:
1131 raise ValueError("negative PUT argument")
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001132 self.memo[i] = self.stack[-1]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001133 dispatch[PUT[0]] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +00001134
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001135 def load_binput(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001136 i = self.read(1)[0]
Antoine Pitrou55549ec2011-08-30 00:27:10 +02001137 if i < 0:
1138 raise ValueError("negative BINPUT argument")
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001139 self.memo[i] = self.stack[-1]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001140 dispatch[BINPUT[0]] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001141
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +03001142 def load_long_binput(self):
Antoine Pitroubf6ecf92012-11-24 20:40:21 +01001143 i, = unpack('<I', self.read(4))
1144 if i > maxsize:
Antoine Pitrou55549ec2011-08-30 00:27:10 +02001145 raise ValueError("negative LONG_BINPUT argument")
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001146 self.memo[i] = self.stack[-1]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001147 dispatch[LONG_BINPUT[0]] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001148
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001149 def load_append(self):
1150 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001151 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001152 list = stack[-1]
1153 list.append(value)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001154 dispatch[APPEND[0]] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +00001155
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001156 def load_appends(self):
1157 stack = self.stack
1158 mark = self.marker()
1159 list = stack[mark - 1]
Tim Peters209ad952003-01-28 01:44:45 +00001160 list.extend(stack[mark + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001161 del stack[mark:]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001162 dispatch[APPENDS[0]] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +00001163
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001164 def load_setitem(self):
1165 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001166 value = stack.pop()
1167 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001168 dict = stack[-1]
1169 dict[key] = value
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001170 dispatch[SETITEM[0]] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001171
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001172 def load_setitems(self):
1173 stack = self.stack
1174 mark = self.marker()
1175 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001176 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001177 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001178
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001179 del stack[mark:]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001180 dispatch[SETITEMS[0]] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001181
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001182 def load_build(self):
1183 stack = self.stack
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001184 state = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001185 inst = stack[-1]
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001186 setstate = getattr(inst, "__setstate__", None)
Serhiy Storchakaa3e32c92013-04-14 13:37:02 +03001187 if setstate is not None:
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001188 setstate(state)
1189 return
1190 slotstate = None
1191 if isinstance(state, tuple) and len(state) == 2:
1192 state, slotstate = state
1193 if state:
Alexandre Vassalottiebfecfd2009-05-25 18:50:33 +00001194 inst_dict = inst.__dict__
Antoine Pitroua9f48a02009-05-02 21:41:14 +00001195 intern = sys.intern
Alexandre Vassalottiebfecfd2009-05-25 18:50:33 +00001196 for k, v in state.items():
1197 if type(k) is str:
1198 inst_dict[intern(k)] = v
1199 else:
1200 inst_dict[k] = v
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001201 if slotstate:
1202 for k, v in slotstate.items():
1203 setattr(inst, k, v)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001204 dispatch[BUILD[0]] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001205
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001206 def load_mark(self):
1207 self.append(self.mark)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001208 dispatch[MARK[0]] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001209
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001210 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001211 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001212 raise _Stop(value)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001213 dispatch[STOP[0]] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001214
Alexander Belopolskyd92f0402010-07-17 22:50:45 +00001215# Encode/decode longs.
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001216
1217def encode_long(x):
Tim Peters91149822003-01-31 03:43:58 +00001218 r"""Encode a long to a two's complement little-endian binary string.
Guido van Rossume2a383d2007-01-15 16:59:06 +00001219 Note that 0 is a special case, returning an empty string, to save a
Tim Peters4b23f2b2003-01-31 16:43:39 +00001220 byte in the LONG1 pickling context.
1221
Guido van Rossume2a383d2007-01-15 16:59:06 +00001222 >>> encode_long(0)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001223 b''
Guido van Rossume2a383d2007-01-15 16:59:06 +00001224 >>> encode_long(255)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001225 b'\xff\x00'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001226 >>> encode_long(32767)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001227 b'\xff\x7f'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001228 >>> encode_long(-256)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001229 b'\x00\xff'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001230 >>> encode_long(-32768)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001231 b'\x00\x80'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001232 >>> encode_long(-128)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001233 b'\x80'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001234 >>> encode_long(127)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001235 b'\x7f'
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001236 >>>
1237 """
Tim Peters91149822003-01-31 03:43:58 +00001238 if x == 0:
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001239 return b''
Alexandre Vassalottid7a3da82010-01-12 01:49:31 +00001240 nbytes = (x.bit_length() >> 3) + 1
1241 result = x.to_bytes(nbytes, byteorder='little', signed=True)
1242 if x < 0 and nbytes > 1:
1243 if result[-1] == 0xff and (result[-2] & 0x80) != 0:
1244 result = result[:-1]
1245 return result
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001246
1247def decode_long(data):
1248 r"""Decode a long from a two's complement little-endian binary string.
Tim Peters4b23f2b2003-01-31 16:43:39 +00001249
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001250 >>> decode_long(b'')
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001251 0
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001252 >>> decode_long(b"\xff\x00")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001253 255
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001254 >>> decode_long(b"\xff\x7f")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001255 32767
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001256 >>> decode_long(b"\x00\xff")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001257 -256
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001258 >>> decode_long(b"\x00\x80")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001259 -32768
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001260 >>> decode_long(b"\x80")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001261 -128
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001262 >>> decode_long(b"\x7f")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001263 127
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001264 """
Alexandre Vassalottid7a3da82010-01-12 01:49:31 +00001265 return int.from_bytes(data, byteorder='little', signed=True)
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001266
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001267# Shorthands
1268
Antoine Pitroud9dfaa92009-06-04 20:32:06 +00001269def dump(obj, file, protocol=None, *, fix_imports=True):
1270 Pickler(file, protocol, fix_imports=fix_imports).dump(obj)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001271
Antoine Pitroud9dfaa92009-06-04 20:32:06 +00001272def dumps(obj, protocol=None, *, fix_imports=True):
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001273 f = io.BytesIO()
Antoine Pitroud9dfaa92009-06-04 20:32:06 +00001274 Pickler(f, protocol, fix_imports=fix_imports).dump(obj)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001275 res = f.getvalue()
Guido van Rossum98297ee2007-11-06 21:34:58 +00001276 assert isinstance(res, bytes_types)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001277 return res
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001278
Antoine Pitroud9dfaa92009-06-04 20:32:06 +00001279def load(file, *, fix_imports=True, encoding="ASCII", errors="strict"):
1280 return Unpickler(file, fix_imports=fix_imports,
1281 encoding=encoding, errors=errors).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001282
Antoine Pitroud9dfaa92009-06-04 20:32:06 +00001283def loads(s, *, fix_imports=True, encoding="ASCII", errors="strict"):
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001284 if isinstance(s, str):
1285 raise TypeError("Can't load pickle from unicode string")
1286 file = io.BytesIO(s)
Antoine Pitroud9dfaa92009-06-04 20:32:06 +00001287 return Unpickler(file, fix_imports=fix_imports,
1288 encoding=encoding, errors=errors).load()
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001289
Antoine Pitrouea99c5c2010-09-09 18:33:21 +00001290# Use the faster _pickle if possible
1291try:
1292 from _pickle import *
1293except ImportError:
1294 Pickler, Unpickler = _Pickler, _Unpickler
1295
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001296# Doctest
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001297def _test():
1298 import doctest
1299 return doctest.testmod()
1300
1301if __name__ == "__main__":
Florent Xicluna54540ec2011-11-04 08:29:17 +01001302 import argparse
Alexander Belopolsky455f7bd2010-07-27 23:02:38 +00001303 parser = argparse.ArgumentParser(
1304 description='display contents of the pickle files')
1305 parser.add_argument(
1306 'pickle_file', type=argparse.FileType('br'),
1307 nargs='*', help='the pickle file')
1308 parser.add_argument(
1309 '-t', '--test', action='store_true',
1310 help='run self-test suite')
1311 parser.add_argument(
1312 '-v', action='store_true',
1313 help='run verbosely; only affects self-test run')
1314 args = parser.parse_args()
1315 if args.test:
1316 _test()
1317 else:
1318 if not args.pickle_file:
1319 parser.print_help()
1320 else:
1321 import pprint
1322 for f in args.pickle_file:
1323 obj = load(f)
1324 pprint.pprint(obj)