blob: 2e55c8a7105fb5f5f631b77f0a8d0ed95d4b3172 [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 Rossum743d17e1998-09-15 20:25:57 +000026__version__ = "$Revision$" # Code version
Guido van Rossuma48061a1995-01-10 00:31:14 +000027
Guido van Rossum13257902007-06-07 23:15:56 +000028from types import FunctionType, BuiltinFunctionType
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +000029from copyreg import dispatch_table
30from copyreg import _extension_registry, _inverted_registry, _extension_cache
Guido van Rossumd3703791998-10-22 20:15:36 +000031import marshal
32import sys
33import struct
Skip Montanaro23bafc62001-02-18 03:10:09 +000034import re
Guido van Rossum2e6a4b32007-05-04 19:56:22 +000035import io
Walter Dörwald42748a82007-06-12 16:40:17 +000036import codecs
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
Guido van Rossume0b90422003-01-28 03:17:21 +000062# Why use struct.pack() for pickling but marshal.loads() for
Tim Petersc0c12b52003-01-29 00:56:17 +000063# unpickling? struct.pack() is 40% faster than marshal.dumps(), but
Guido van Rossume0b90422003-01-28 03:17:21 +000064# marshal.loads() is twice as fast as struct.unpack()!
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000065mloads = marshal.loads
Guido van Rossum0c891ce1995-03-14 15:09:05 +000066
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000067class PickleError(Exception):
Neal Norwitzefbb67b2002-05-30 12:12:04 +000068 """A common base class for the other pickling exceptions."""
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000069 pass
70
71class PicklingError(PickleError):
72 """This exception is raised when an unpicklable object is passed to the
73 dump() method.
74
75 """
76 pass
77
78class UnpicklingError(PickleError):
79 """This exception is raised when there is a problem unpickling an object,
80 such as a security violation.
81
82 Note that other exceptions may also be raised during unpickling, including
83 (but not necessarily limited to) AttributeError, EOFError, ImportError,
84 and IndexError.
85
86 """
87 pass
Guido van Rossum7849da81995-03-09 14:08:35 +000088
Tim Petersc0c12b52003-01-29 00:56:17 +000089# An instance of _Stop is raised by Unpickler.load_stop() in response to
90# the STOP opcode, passing the object that is the result of unpickling.
Guido van Rossumff871742000-12-13 18:11:56 +000091class _Stop(Exception):
92 def __init__(self, value):
93 self.value = value
94
Guido van Rossum533dbcf2003-01-28 17:55:05 +000095# Jython has PyStringMap; it's a dict subclass with string keys
Jeremy Hylton2b9d0291998-05-27 22:38:22 +000096try:
97 from org.python.core import PyStringMap
98except ImportError:
99 PyStringMap = None
100
Tim Peters22a449a2003-01-27 20:16:36 +0000101# Pickle opcodes. See pickletools.py for extensive docs. The listing
102# here is in kind-of alphabetical order of 1-character pickle code.
103# pickletools groups them by purpose.
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000104
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000105MARK = b'(' # push special markobject on stack
106STOP = b'.' # every pickle ends with STOP
107POP = b'0' # discard topmost stack item
108POP_MARK = b'1' # discard stack top through topmost markobject
109DUP = b'2' # duplicate top stack item
110FLOAT = b'F' # push float object; decimal string argument
111INT = b'I' # push integer or bool; decimal string argument
112BININT = b'J' # push four-byte signed int
113BININT1 = b'K' # push 1-byte unsigned int
114LONG = b'L' # push long; decimal string argument
115BININT2 = b'M' # push 2-byte unsigned int
116NONE = b'N' # push None
117PERSID = b'P' # push persistent object; id is taken from string arg
118BINPERSID = b'Q' # " " " ; " " " " stack
119REDUCE = b'R' # apply callable to argtuple, both on stack
120STRING = b'S' # push string; NL-terminated string argument
121BINSTRING = b'T' # push string; counted binary string argument
122SHORT_BINSTRING= b'U' # " " ; " " " " < 256 bytes
123UNICODE = b'V' # push Unicode string; raw-unicode-escaped'd argument
124BINUNICODE = b'X' # " " " ; counted UTF-8 string argument
125APPEND = b'a' # append stack top to list below it
126BUILD = b'b' # call __setstate__ or __dict__.update()
127GLOBAL = b'c' # push self.find_class(modname, name); 2 string args
128DICT = b'd' # build a dict from stack items
129EMPTY_DICT = b'}' # push empty dict
130APPENDS = b'e' # extend list on stack by topmost stack slice
131GET = b'g' # push item from memo on stack; index is string arg
132BINGET = b'h' # " " " " " " ; " " 1-byte arg
133INST = b'i' # build & push class instance
134LONG_BINGET = b'j' # push item from memo on stack; index is 4-byte arg
135LIST = b'l' # build list from topmost stack items
136EMPTY_LIST = b']' # push empty list
137OBJ = b'o' # build & push class instance
138PUT = b'p' # store stack top in memo; index is string arg
139BINPUT = b'q' # " " " " " ; " " 1-byte arg
140LONG_BINPUT = b'r' # " " " " " ; " " 4-byte arg
141SETITEM = b's' # add key+value pair to dict
142TUPLE = b't' # build tuple from topmost stack items
143EMPTY_TUPLE = b')' # push empty tuple
144SETITEMS = b'u' # modify dict by adding topmost key+value pairs
145BINFLOAT = b'G' # push float; arg is 8-byte float encoding
Tim Peters22a449a2003-01-27 20:16:36 +0000146
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000147TRUE = b'I01\n' # not an opcode; see INT docs in pickletools.py
148FALSE = b'I00\n' # not an opcode; see INT docs in pickletools.py
Guido van Rossum77f6a652002-04-03 22:41:51 +0000149
Guido van Rossum586c9e82003-01-29 06:16:12 +0000150# Protocol 2
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000151
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000152PROTO = b'\x80' # identify pickle protocol
153NEWOBJ = b'\x81' # build object by applying cls.__new__ to argtuple
154EXT1 = b'\x82' # push object from extension registry; 1-byte index
155EXT2 = b'\x83' # ditto, but 2-byte index
156EXT4 = b'\x84' # ditto, but 4-byte index
157TUPLE1 = b'\x85' # build 1-tuple from stack top
158TUPLE2 = b'\x86' # build 2-tuple from two topmost stack items
159TUPLE3 = b'\x87' # build 3-tuple from three topmost stack items
160NEWTRUE = b'\x88' # push True
161NEWFALSE = b'\x89' # push False
162LONG1 = b'\x8a' # push long from < 256 bytes
163LONG4 = b'\x8b' # push really big long
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000164
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000165_tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3]
166
Guido van Rossumf4169812008-03-17 22:56:06 +0000167# Protocol 3 (Python 3.x)
168
169BINBYTES = b'B' # push bytes; counted binary string argument
170SHORT_BINBYTES = b'C' # " " ; " " " " < 256 bytes
Guido van Rossuma48061a1995-01-10 00:31:14 +0000171
Skip Montanaro23bafc62001-02-18 03:10:09 +0000172__all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
173
Guido van Rossum1be31752003-01-28 15:19:53 +0000174
175# Pickling machinery
176
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000177class _Pickler:
Guido van Rossuma48061a1995-01-10 00:31:14 +0000178
Raymond Hettinger3489cad2004-12-05 05:20:42 +0000179 def __init__(self, file, protocol=None):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000180 """This takes a binary file for writing a pickle data stream.
181
Guido van Rossumcf117b02003-02-09 17:19:41 +0000182 The optional protocol argument tells the pickler to use the
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000183 given protocol; supported protocols are 0, 1, 2, 3. The default
184 protocol is 3; a backward-incompatible protocol designed for
185 Python 3.0.
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000186
Guido van Rossum7eff63a2003-01-31 19:42:31 +0000187 Specifying a negative protocol version selects the highest
Tim Peters5bd2a792003-02-01 16:45:06 +0000188 protocol version supported. The higher the protocol used, the
189 more recent the version of Python needed to read the pickle
190 produced.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000191
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000192 The file argument must have a write() method that accepts a single
193 bytes argument. It can thus be a file object opened for binary
194 writing, a io.BytesIO instance, or any other custom object that
195 meets this interface.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000196 """
Guido van Rossumcf117b02003-02-09 17:19:41 +0000197 if protocol is None:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000198 protocol = DEFAULT_PROTOCOL
Guido van Rossumcf117b02003-02-09 17:19:41 +0000199 if protocol < 0:
Tim Peters8587b3c2003-02-13 15:44:41 +0000200 protocol = HIGHEST_PROTOCOL
201 elif not 0 <= protocol <= HIGHEST_PROTOCOL:
202 raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL)
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000203 try:
204 self.write = file.write
205 except AttributeError:
206 raise TypeError("file must have a 'write' attribute")
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000207 self.memo = {}
Guido van Rossumcf117b02003-02-09 17:19:41 +0000208 self.proto = int(protocol)
209 self.bin = protocol >= 1
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000210 self.fast = 0
Guido van Rossuma48061a1995-01-10 00:31:14 +0000211
Fred Drake7f781c92002-05-01 20:33:53 +0000212 def clear_memo(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000213 """Clears the pickler's "memo".
214
215 The memo is the data structure that remembers which objects the
Tim Petersb377f8a2003-01-28 00:23:36 +0000216 pickler has already seen, so that shared or recursive objects are
217 pickled by reference and not by value. This method is useful when
218 re-using picklers.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000219
220 """
Fred Drake7f781c92002-05-01 20:33:53 +0000221 self.memo.clear()
222
Guido van Rossum3a41c612003-01-28 15:10:22 +0000223 def dump(self, obj):
Tim Peters5bd2a792003-02-01 16:45:06 +0000224 """Write a pickled representation of obj to the open file."""
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000225 if self.proto >= 2:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000226 self.write(PROTO + bytes([self.proto]))
Guido van Rossum3a41c612003-01-28 15:10:22 +0000227 self.save(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000228 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000229
Jeremy Hylton3422c992003-01-24 19:29:52 +0000230 def memoize(self, obj):
231 """Store an object in the memo."""
232
Tim Peterse46b73f2003-01-27 21:22:10 +0000233 # The Pickler memo is a dictionary mapping object ids to 2-tuples
234 # that contain the Unpickler memo key and the object being memoized.
235 # The memo key is written to the pickle and will become
Jeremy Hylton3422c992003-01-24 19:29:52 +0000236 # the key in the Unpickler's memo. The object is stored in the
Tim Peterse46b73f2003-01-27 21:22:10 +0000237 # Pickler memo so that transient objects are kept alive during
238 # pickling.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000239
Tim Peterse46b73f2003-01-27 21:22:10 +0000240 # The use of the Unpickler memo length as the memo key is just a
241 # convention. The only requirement is that the memo values be unique.
242 # But there appears no advantage to any other scheme, and this
Tim Peterscbd0a322003-01-28 00:24:43 +0000243 # scheme allows the Unpickler memo to be implemented as a plain (but
Tim Peterse46b73f2003-01-27 21:22:10 +0000244 # growable) array, indexed by memo key.
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000245 if self.fast:
246 return
Guido van Rossum9b40e802003-01-30 06:37:41 +0000247 assert id(obj) not in self.memo
Jeremy Hylton3422c992003-01-24 19:29:52 +0000248 memo_len = len(self.memo)
249 self.write(self.put(memo_len))
Tim Peters518df0d2003-01-28 01:00:38 +0000250 self.memo[id(obj)] = memo_len, obj
Jeremy Hylton3422c992003-01-24 19:29:52 +0000251
Tim Petersbb38e302003-01-27 21:25:41 +0000252 # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000253 def put(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000254 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000255 if i < 256:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000256 return BINPUT + bytes([i])
Guido van Rossum5c938d02003-01-28 03:03:08 +0000257 else:
258 return LONG_BINPUT + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000259
Guido van Rossum39478e82007-08-27 17:23:59 +0000260 return PUT + repr(i).encode("ascii") + b'\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000261
Tim Petersbb38e302003-01-27 21:25:41 +0000262 # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000263 def get(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000264 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000265 if i < 256:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000266 return BINGET + bytes([i])
Guido van Rossum5c938d02003-01-28 03:03:08 +0000267 else:
268 return LONG_BINGET + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000269
Guido van Rossum39478e82007-08-27 17:23:59 +0000270 return GET + repr(i).encode("ascii") + b'\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000271
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000272 def save(self, obj, save_persistent_id=True):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000273 # Check for persistent id (defined by a subclass)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000274 pid = self.persistent_id(obj)
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000275 if pid is not None and save_persistent_id:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000276 self.save_pers(pid)
277 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000278
Guido van Rossumbc64e222003-01-28 16:34:19 +0000279 # Check the memo
280 x = self.memo.get(id(obj))
281 if x:
282 self.write(self.get(x[0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000283 return
284
Guido van Rossumbc64e222003-01-28 16:34:19 +0000285 # Check the type dispatch table
Guido van Rossum3a41c612003-01-28 15:10:22 +0000286 t = type(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000287 f = self.dispatch.get(t)
288 if f:
289 f(self, obj) # Call unbound method with explicit self
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000290 return
291
Guido van Rossumbc64e222003-01-28 16:34:19 +0000292 # Check for a class with a custom metaclass; treat as regular class
Tim Petersb32a8312003-01-28 00:48:09 +0000293 try:
Guido van Rossum13257902007-06-07 23:15:56 +0000294 issc = issubclass(t, type)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000295 except TypeError: # t is not a class (old Boost; see SF #502085)
Tim Petersb32a8312003-01-28 00:48:09 +0000296 issc = 0
297 if issc:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000298 self.save_global(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000299 return
300
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +0000301 # Check copyreg.dispatch_table
Guido van Rossumbc64e222003-01-28 16:34:19 +0000302 reduce = dispatch_table.get(t)
Guido van Rossumc53f0092003-02-18 22:05:12 +0000303 if reduce:
304 rv = reduce(obj)
305 else:
306 # Check for a __reduce_ex__ method, fall back to __reduce__
307 reduce = getattr(obj, "__reduce_ex__", None)
308 if reduce:
309 rv = reduce(self.proto)
310 else:
311 reduce = getattr(obj, "__reduce__", None)
312 if reduce:
313 rv = reduce()
314 else:
315 raise PicklingError("Can't pickle %r object: %r" %
316 (t.__name__, obj))
Tim Petersb32a8312003-01-28 00:48:09 +0000317
Guido van Rossumbc64e222003-01-28 16:34:19 +0000318 # Check for string returned by reduce(), meaning "save as global"
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000319 if isinstance(rv, str):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000320 self.save_global(obj, rv)
Tim Petersb32a8312003-01-28 00:48:09 +0000321 return
322
Guido van Rossumbc64e222003-01-28 16:34:19 +0000323 # Assert that reduce() returned a tuple
Guido van Rossum13257902007-06-07 23:15:56 +0000324 if not isinstance(rv, tuple):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000325 raise PicklingError("%s must return string or tuple" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000326
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000327 # Assert that it returned an appropriately sized tuple
Guido van Rossumbc64e222003-01-28 16:34:19 +0000328 l = len(rv)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000329 if not (2 <= l <= 5):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000330 raise PicklingError("Tuple returned by %s must have "
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000331 "two to five elements" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000332
Guido van Rossumbc64e222003-01-28 16:34:19 +0000333 # Save the reduce() output and finally memoize the object
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000334 self.save_reduce(obj=obj, *rv)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000335
Guido van Rossum3a41c612003-01-28 15:10:22 +0000336 def persistent_id(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000337 # This exists so a subclass can override it
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000338 return None
339
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000340 def save_pers(self, pid):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000341 # Save a persistent id reference
Tim Petersbd1cdb92003-01-28 01:03:10 +0000342 if self.bin:
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000343 self.save(pid, save_persistent_id=False)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000344 self.write(BINPERSID)
Tim Petersbd1cdb92003-01-28 01:03:10 +0000345 else:
Guido van Rossum39478e82007-08-27 17:23:59 +0000346 self.write(PERSID + str(pid).encode("ascii") + b'\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000347
Hirokazu Yamamoto1543a222008-11-04 00:31:31 +0000348 def _isiter(self, obj):
349 return hasattr(obj, '__next__') and hasattr(obj, '__iter__')
350
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000351 def save_reduce(self, func, args, state=None,
352 listitems=None, dictitems=None, obj=None):
Jeremy Hyltone3a565e2003-06-29 16:59:59 +0000353 # This API is called by some subclasses
Guido van Rossumbc64e222003-01-28 16:34:19 +0000354
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000355 # Assert that args is a tuple
Guido van Rossum13257902007-06-07 23:15:56 +0000356 if not isinstance(args, tuple):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000357 raise PicklingError("args from save_reduce() should be a tuple")
Guido van Rossumbc64e222003-01-28 16:34:19 +0000358
359 # Assert that func is callable
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000360 if not hasattr(func, '__call__'):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000361 raise PicklingError("func from save_reduce() should be callable")
Guido van Rossumbc64e222003-01-28 16:34:19 +0000362
Hirokazu Yamamoto1543a222008-11-04 00:31:31 +0000363 # Assert that listitems is an iterator
364 if listitems is not None and not self._isiter(listitems):
365 raise PicklingError("listitems from save_reduce() should be an "
366 "iterator")
367
368 # Assert that dictitems is an iterator
369 if dictitems is not None and not self._isiter(dictitems):
370 raise PicklingError("dictitems from save_reduce() should be an "
371 "iterator")
372
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000373 save = self.save
Guido van Rossumbc64e222003-01-28 16:34:19 +0000374 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000375
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000376 # Protocol 2 special case: if func's name is __newobj__, use NEWOBJ
377 if self.proto >= 2 and getattr(func, "__name__", "") == "__newobj__":
378 # A __reduce__ implementation can direct protocol 2 to
379 # use the more efficient NEWOBJ opcode, while still
380 # allowing protocol 0 and 1 to work normally. For this to
381 # work, the function returned by __reduce__ should be
382 # called __newobj__, and its first argument should be a
383 # new-style class. The implementation for __newobj__
384 # should be as follows, although pickle has no way to
385 # verify this:
386 #
387 # def __newobj__(cls, *args):
388 # return cls.__new__(cls, *args)
389 #
390 # Protocols 0 and 1 will pickle a reference to __newobj__,
391 # while protocol 2 (and above) will pickle a reference to
392 # cls, the remaining args tuple, and the NEWOBJ code,
393 # which calls cls.__new__(cls, *args) at unpickling time
394 # (see load_newobj below). If __reduce__ returns a
395 # three-tuple, the state from the third tuple item will be
396 # pickled regardless of the protocol, calling __setstate__
397 # at unpickling time (see load_build below).
398 #
399 # Note that no standard __newobj__ implementation exists;
400 # you have to provide your own. This is to enforce
401 # compatibility with Python 2.2 (pickles written using
402 # protocol 0 or 1 in Python 2.3 should be unpicklable by
403 # Python 2.2).
404 cls = args[0]
405 if not hasattr(cls, "__new__"):
406 raise PicklingError(
407 "args[0] from __newobj__ args has no __new__")
Guido van Rossumf7f45172003-01-31 17:17:49 +0000408 if obj is not None and cls is not obj.__class__:
409 raise PicklingError(
410 "args[0] from __newobj__ args has the wrong class")
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000411 args = args[1:]
412 save(cls)
413 save(args)
414 write(NEWOBJ)
415 else:
416 save(func)
417 save(args)
418 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000419
Guido van Rossumf7f45172003-01-31 17:17:49 +0000420 if obj is not None:
421 self.memoize(obj)
422
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000423 # More new special cases (that work with older protocols as
424 # well): when __reduce__ returns a tuple with 4 or 5 items,
425 # the 4th and 5th item should be iterators that provide list
426 # items and dict items (as (key, value) tuples), or None.
427
428 if listitems is not None:
429 self._batch_appends(listitems)
430
431 if dictitems is not None:
432 self._batch_setitems(dictitems)
433
Tim Petersc32d8242001-04-10 02:48:53 +0000434 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000435 save(state)
436 write(BUILD)
437
Guido van Rossumbc64e222003-01-28 16:34:19 +0000438 # Methods below this point are dispatched through the dispatch table
439
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000440 dispatch = {}
441
Guido van Rossum3a41c612003-01-28 15:10:22 +0000442 def save_none(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000443 self.write(NONE)
Guido van Rossum13257902007-06-07 23:15:56 +0000444 dispatch[type(None)] = save_none
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000445
Guido van Rossum3a41c612003-01-28 15:10:22 +0000446 def save_bool(self, obj):
Guido van Rossum7d97d312003-01-28 04:25:27 +0000447 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000448 self.write(obj and NEWTRUE or NEWFALSE)
Guido van Rossum7d97d312003-01-28 04:25:27 +0000449 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000450 self.write(obj and TRUE or FALSE)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000451 dispatch[bool] = save_bool
452
Guido van Rossum3a41c612003-01-28 15:10:22 +0000453 def save_long(self, obj, pack=struct.pack):
Guido van Rossumddefaf32007-01-14 03:31:43 +0000454 if self.bin:
455 # If the int is small enough to fit in a signed 4-byte 2's-comp
456 # format, we can store it more efficiently than the general
457 # case.
458 # First one- and two-byte unsigned ints:
459 if obj >= 0:
460 if obj <= 0xff:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000461 self.write(BININT1 + bytes([obj]))
Guido van Rossumddefaf32007-01-14 03:31:43 +0000462 return
463 if obj <= 0xffff:
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000464 self.write(BININT2 + bytes([obj&0xff, obj>>8]))
Guido van Rossumddefaf32007-01-14 03:31:43 +0000465 return
466 # Next check for 4-byte signed ints:
467 high_bits = obj >> 31 # note that Python shift sign-extends
468 if high_bits == 0 or high_bits == -1:
469 # All high bits are copies of bit 2**31, so the value
470 # fits in a 4-byte signed int.
471 self.write(BININT + pack("<i", obj))
472 return
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000473 if self.proto >= 2:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000474 encoded = encode_long(obj)
475 n = len(encoded)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000476 if n < 256:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000477 self.write(LONG1 + bytes([n]) + encoded)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000478 else:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000479 self.write(LONG4 + pack("<i", n) + encoded)
Tim Petersee1a53c2003-02-02 02:57:53 +0000480 return
Guido van Rossum39478e82007-08-27 17:23:59 +0000481 self.write(LONG + repr(obj).encode("ascii") + b'\n')
Guido van Rossum13257902007-06-07 23:15:56 +0000482 dispatch[int] = save_long
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000483
Guido van Rossum3a41c612003-01-28 15:10:22 +0000484 def save_float(self, obj, pack=struct.pack):
Guido van Rossumd3703791998-10-22 20:15:36 +0000485 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000486 self.write(BINFLOAT + pack('>d', obj))
Guido van Rossumd3703791998-10-22 20:15:36 +0000487 else:
Guido van Rossum39478e82007-08-27 17:23:59 +0000488 self.write(FLOAT + repr(obj).encode("ascii") + b'\n')
Guido van Rossum13257902007-06-07 23:15:56 +0000489 dispatch[float] = save_float
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000490
Guido van Rossumf4169812008-03-17 22:56:06 +0000491 def save_bytes(self, obj, pack=struct.pack):
492 if self.proto < 3:
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000493 self.save_reduce(bytes, (list(obj),), obj=obj)
Guido van Rossumf4169812008-03-17 22:56:06 +0000494 return
495 n = len(obj)
496 if n < 256:
497 self.write(SHORT_BINBYTES + bytes([n]) + bytes(obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000498 else:
Guido van Rossumf4169812008-03-17 22:56:06 +0000499 self.write(BINBYTES + pack("<i", n) + bytes(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
Guido van Rossumf4169812008-03-17 22:56:06 +0000503 def save_str(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000504 if self.bin:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000505 encoded = obj.encode('utf-8')
506 n = len(encoded)
507 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")
Guido van Rossum1255ed62007-05-04 20:30:19 +0000511 self.write(UNICODE + bytes(obj.encode('raw-unicode-escape')) +
512 b'\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000513 self.memoize(obj)
Guido van Rossumf4169812008-03-17 22:56:06 +0000514 dispatch[str] = save_str
Tim Peters658cba62001-02-09 20:06:00 +0000515
Guido van Rossum3a41c612003-01-28 15:10:22 +0000516 def save_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000517 write = self.write
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000518 proto = self.proto
519
Guido van Rossum3a41c612003-01-28 15:10:22 +0000520 n = len(obj)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000521 if n == 0:
522 if proto:
523 write(EMPTY_TUPLE)
524 else:
525 write(MARK + TUPLE)
Tim Petersd97da802003-01-28 05:48:29 +0000526 return
527
528 save = self.save
529 memo = self.memo
530 if n <= 3 and proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000531 for element in obj:
Tim Petersd97da802003-01-28 05:48:29 +0000532 save(element)
533 # Subtle. Same as in the big comment below.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000534 if id(obj) in memo:
535 get = self.get(memo[id(obj)][0])
Tim Petersd97da802003-01-28 05:48:29 +0000536 write(POP * n + get)
537 else:
538 write(_tuplesize2code[n])
Guido van Rossum3a41c612003-01-28 15:10:22 +0000539 self.memoize(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000540 return
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000541
Tim Peters1d63c9f2003-02-02 20:29:39 +0000542 # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple
Tim Petersff57bff2003-01-28 05:34:53 +0000543 # has more than 3 elements.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000544 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000545 for element in obj:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000546 save(element)
547
Tim Peters1d63c9f2003-02-02 20:29:39 +0000548 if id(obj) in memo:
Tim Petersf558da02003-01-28 02:09:55 +0000549 # Subtle. d was not in memo when we entered save_tuple(), so
550 # the process of saving the tuple's elements must have saved
551 # the tuple itself: the tuple is recursive. The proper action
552 # now is to throw away everything we put on the stack, and
553 # simply GET the tuple (it's already constructed). This check
554 # could have been done in the "for element" loop instead, but
555 # recursive tuples are a rare thing.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000556 get = self.get(memo[id(obj)][0])
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000557 if proto:
Tim Petersf558da02003-01-28 02:09:55 +0000558 write(POP_MARK + get)
559 else: # proto 0 -- POP_MARK not available
Tim Petersd97da802003-01-28 05:48:29 +0000560 write(POP * (n+1) + get)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000561 return
562
Tim Peters1d63c9f2003-02-02 20:29:39 +0000563 # No recursion.
Tim Peters518df0d2003-01-28 01:00:38 +0000564 self.write(TUPLE)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000565 self.memoize(obj)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000566
Guido van Rossum13257902007-06-07 23:15:56 +0000567 dispatch[tuple] = save_tuple
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000568
Guido van Rossum3a41c612003-01-28 15:10:22 +0000569 def save_list(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000570 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000571
Tim Petersc32d8242001-04-10 02:48:53 +0000572 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000573 write(EMPTY_LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000574 else: # proto 0 -- can't use EMPTY_LIST
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000575 write(MARK + LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000576
577 self.memoize(obj)
Alexandre Vassalottic7db1d62008-05-14 21:57:18 +0000578 self._batch_appends(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000579
Guido van Rossum13257902007-06-07 23:15:56 +0000580 dispatch[list] = save_list
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000581
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000582 _BATCHSIZE = 1000
583
584 def _batch_appends(self, items):
585 # Helper to batch up APPENDS sequences
586 save = self.save
587 write = self.write
588
589 if not self.bin:
590 for x in items:
591 save(x)
592 write(APPEND)
593 return
594
Alexandre Vassalottic7db1d62008-05-14 21:57:18 +0000595 items = iter(items)
Guido van Rossum805365e2007-05-07 22:24:25 +0000596 r = range(self._BATCHSIZE)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000597 while items is not None:
598 tmp = []
599 for i in r:
600 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000601 x = next(items)
Guido van Rossum5aac4e62003-02-06 22:57:00 +0000602 tmp.append(x)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000603 except StopIteration:
604 items = None
605 break
606 n = len(tmp)
607 if n > 1:
608 write(MARK)
609 for x in tmp:
610 save(x)
611 write(APPENDS)
612 elif n:
613 save(tmp[0])
614 write(APPEND)
615 # else tmp is empty, and we're done
616
Guido van Rossum3a41c612003-01-28 15:10:22 +0000617 def save_dict(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000618 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000619
Tim Petersc32d8242001-04-10 02:48:53 +0000620 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000621 write(EMPTY_DICT)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000622 else: # proto 0 -- can't use EMPTY_DICT
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000623 write(MARK + DICT)
624
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000625 self.memoize(obj)
Alexandre Vassalottic7db1d62008-05-14 21:57:18 +0000626 self._batch_setitems(obj.items())
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000627
Guido van Rossum13257902007-06-07 23:15:56 +0000628 dispatch[dict] = save_dict
629 if PyStringMap is not None:
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000630 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000631
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000632 def _batch_setitems(self, items):
633 # Helper to batch up SETITEMS sequences; proto >= 1 only
634 save = self.save
635 write = self.write
636
637 if not self.bin:
638 for k, v in items:
639 save(k)
640 save(v)
641 write(SETITEM)
642 return
643
Alexandre Vassalottic7db1d62008-05-14 21:57:18 +0000644 items = iter(items)
Guido van Rossum805365e2007-05-07 22:24:25 +0000645 r = range(self._BATCHSIZE)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000646 while items is not None:
647 tmp = []
648 for i in r:
649 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000650 tmp.append(next(items))
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000651 except StopIteration:
652 items = None
653 break
654 n = len(tmp)
655 if n > 1:
656 write(MARK)
657 for k, v in tmp:
658 save(k)
659 save(v)
660 write(SETITEMS)
661 elif n:
662 k, v = tmp[0]
663 save(k)
664 save(v)
665 write(SETITEM)
666 # else tmp is empty, and we're done
667
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000668 def save_global(self, obj, name=None, pack=struct.pack):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000669 write = self.write
670 memo = self.memo
671
Tim Petersc32d8242001-04-10 02:48:53 +0000672 if name is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000673 name = obj.__name__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000674
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000675 module = getattr(obj, "__module__", None)
676 if module is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000677 module = whichmodule(obj, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000678
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000679 try:
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000680 __import__(module, level=0)
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000681 mod = sys.modules[module]
682 klass = getattr(mod, name)
683 except (ImportError, KeyError, AttributeError):
684 raise PicklingError(
685 "Can't pickle %r: it's not found as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000686 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000687 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000688 if klass is not obj:
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000689 raise PicklingError(
690 "Can't pickle %r: it's not the same object as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000691 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000692
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000693 if self.proto >= 2:
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000694 code = _extension_registry.get((module, name))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000695 if code:
696 assert code > 0
697 if code <= 0xff:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000698 write(EXT1 + bytes([code]))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000699 elif code <= 0xffff:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000700 write(EXT2 + bytes([code&0xff, code>>8]))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000701 else:
702 write(EXT4 + pack("<i", code))
703 return
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000704 # Non-ASCII identifiers are supported only with protocols >= 3.
705 if self.proto >= 3:
706 write(GLOBAL + bytes(module, "utf-8") + b'\n' +
707 bytes(name, "utf-8") + b'\n')
708 else:
709 try:
710 write(GLOBAL + bytes(module, "ascii") + b'\n' +
711 bytes(name, "ascii") + b'\n')
712 except UnicodeEncodeError:
713 raise PicklingError(
714 "can't pickle global identifier '%s.%s' using "
715 "pickle protocol %i" % (module, name, self.proto))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000716
Guido van Rossum3a41c612003-01-28 15:10:22 +0000717 self.memoize(obj)
Tim Peters3b769832003-01-28 03:51:36 +0000718
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000719 dispatch[FunctionType] = save_global
720 dispatch[BuiltinFunctionType] = save_global
Guido van Rossum13257902007-06-07 23:15:56 +0000721 dispatch[type] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000722
Guido van Rossum1be31752003-01-28 15:19:53 +0000723# Pickling helpers
Guido van Rossuma48061a1995-01-10 00:31:14 +0000724
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000725def _keep_alive(x, memo):
726 """Keeps a reference to the object x in the memo.
727
728 Because we remember objects by their id, we have
729 to assure that possibly temporary objects are kept
730 alive by referencing them.
731 We store a reference at the id of the memo, which should
732 normally not be used unless someone tries to deepcopy
733 the memo itself...
734 """
735 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000736 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000737 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000738 # aha, this is the first one :-)
739 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000740
741
Tim Petersc0c12b52003-01-29 00:56:17 +0000742# A cache for whichmodule(), mapping a function object to the name of
743# the module in which the function was found.
744
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000745classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000746
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000747def whichmodule(func, funcname):
748 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000749
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000750 Search sys.modules for the module.
751 Cache in classmap.
752 Return a module name.
Tim Petersc0c12b52003-01-29 00:56:17 +0000753 If the function cannot be found, return "__main__".
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000754 """
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000755 # Python functions should always get an __module__ from their globals.
756 mod = getattr(func, "__module__", None)
757 if mod is not None:
758 return mod
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000759 if func in classmap:
760 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000761
Guido van Rossum634e53f2007-02-26 07:07:02 +0000762 for name, module in list(sys.modules.items()):
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000763 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000764 continue # skip dummy package entries
Jeremy Hyltoncc1fccb2003-02-06 16:23:01 +0000765 if name != '__main__' and getattr(module, funcname, None) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000766 break
767 else:
768 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000769 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000770 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000771
772
Guido van Rossum1be31752003-01-28 15:19:53 +0000773# Unpickling machinery
774
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000775class _Unpickler:
Guido van Rossuma48061a1995-01-10 00:31:14 +0000776
Guido van Rossumf4169812008-03-17 22:56:06 +0000777 def __init__(self, file, *, encoding="ASCII", errors="strict"):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000778 """This takes a binary file for reading a pickle data stream.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000779
Tim Peters5bd2a792003-02-01 16:45:06 +0000780 The protocol version of the pickle is detected automatically, so no
781 proto argument is needed.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000782
Guido van Rossumfeea0782007-10-10 18:00:50 +0000783 The file-like object must have two methods, a read() method
784 that takes an integer argument, and a readline() method that
785 requires no arguments. Both methods should return bytes.
786 Thus file-like object can be a binary file object opened for
787 reading, a BytesIO object, or any other custom object that
788 meets this interface.
Guido van Rossumf4169812008-03-17 22:56:06 +0000789
790 Optional keyword arguments are encoding and errors, which are
791 used to decode 8-bit string instances pickled by Python 2.x.
792 These default to 'ASCII' and 'strict', respectively.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000793 """
Guido van Rossumfeea0782007-10-10 18:00:50 +0000794 self.readline = file.readline
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000795 self.read = file.read
796 self.memo = {}
Guido van Rossumf4169812008-03-17 22:56:06 +0000797 self.encoding = encoding
798 self.errors = errors
Guido van Rossuma48061a1995-01-10 00:31:14 +0000799
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000800 def load(self):
Guido van Rossum3a41c612003-01-28 15:10:22 +0000801 """Read a pickled object representation from the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000802
Guido van Rossum3a41c612003-01-28 15:10:22 +0000803 Return the reconstituted object hierarchy specified in the file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000804 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000805 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000806 self.stack = []
807 self.append = self.stack.append
808 read = self.read
809 dispatch = self.dispatch
810 try:
811 while 1:
812 key = read(1)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000813 if not key:
814 raise EOFError
Guido van Rossum98297ee2007-11-06 21:34:58 +0000815 assert isinstance(key, bytes_types)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000816 dispatch[key[0]](self)
Guido van Rossumb940e112007-01-10 16:19:56 +0000817 except _Stop as stopinst:
Guido van Rossumff871742000-12-13 18:11:56 +0000818 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000819
Tim Petersc23d18a2003-01-28 01:41:51 +0000820 # Return largest index k such that self.stack[k] is self.mark.
821 # If the stack doesn't contain a mark, eventually raises IndexError.
822 # This could be sped by maintaining another stack, of indices at which
823 # the mark appears. For that matter, the latter stack would suffice,
824 # and we wouldn't need to push mark objects on self.stack at all.
825 # Doing so is probably a good thing, though, since if the pickle is
826 # corrupt (or hostile) we may get a clue from finding self.mark embedded
827 # in unpickled objects.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000828 def marker(self):
829 stack = self.stack
830 mark = self.mark
831 k = len(stack)-1
832 while stack[k] is not mark: k = k-1
833 return k
834
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000835 def persistent_load(self, pid):
836 raise UnpickingError("unsupported persistent id encountered")
837
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000838 dispatch = {}
839
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000840 def load_proto(self):
841 proto = ord(self.read(1))
Guido van Rossumf4169812008-03-17 22:56:06 +0000842 if not 0 <= proto <= HIGHEST_PROTOCOL:
Guido van Rossum26d95c32007-08-27 23:18:54 +0000843 raise ValueError("unsupported pickle protocol: %d" % proto)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000844 dispatch[PROTO[0]] = load_proto
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000845
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000846 def load_persid(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000847 pid = self.readline()[:-1].decode("ascii")
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000848 self.append(self.persistent_load(pid))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000849 dispatch[PERSID[0]] = load_persid
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000850
851 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000852 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000853 self.append(self.persistent_load(pid))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000854 dispatch[BINPERSID[0]] = load_binpersid
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000855
856 def load_none(self):
857 self.append(None)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000858 dispatch[NONE[0]] = load_none
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000859
Guido van Rossum7d97d312003-01-28 04:25:27 +0000860 def load_false(self):
861 self.append(False)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000862 dispatch[NEWFALSE[0]] = load_false
Guido van Rossum7d97d312003-01-28 04:25:27 +0000863
864 def load_true(self):
865 self.append(True)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000866 dispatch[NEWTRUE[0]] = load_true
Guido van Rossum7d97d312003-01-28 04:25:27 +0000867
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000868 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000869 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000870 if data == FALSE[1:]:
871 val = False
872 elif data == TRUE[1:]:
873 val = True
874 else:
875 try:
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000876 val = int(data, 0)
Guido van Rossume2763392002-04-05 19:30:08 +0000877 except ValueError:
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000878 val = int(data, 0)
Guido van Rossume2763392002-04-05 19:30:08 +0000879 self.append(val)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000880 dispatch[INT[0]] = load_int
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000881
882 def load_binint(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000883 self.append(mloads(b'i' + self.read(4)))
884 dispatch[BININT[0]] = load_binint
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000885
886 def load_binint1(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000887 self.append(ord(self.read(1)))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000888 dispatch[BININT1[0]] = load_binint1
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000889
890 def load_binint2(self):
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000891 self.append(mloads(b'i' + self.read(2) + b'\000\000'))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000892 dispatch[BININT2[0]] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000893
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000894 def load_long(self):
Guido van Rossumfeea0782007-10-10 18:00:50 +0000895 val = self.readline()[:-1].decode("ascii")
896 self.append(int(val, 0))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000897 dispatch[LONG[0]] = load_long
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000898
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000899 def load_long1(self):
900 n = ord(self.read(1))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000901 data = self.read(n)
902 self.append(decode_long(data))
903 dispatch[LONG1[0]] = load_long1
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000904
905 def load_long4(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000906 n = mloads(b'i' + self.read(4))
907 data = self.read(n)
908 self.append(decode_long(data))
909 dispatch[LONG4[0]] = load_long4
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000910
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000911 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000912 self.append(float(self.readline()[:-1]))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000913 dispatch[FLOAT[0]] = load_float
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000914
Guido van Rossumd3703791998-10-22 20:15:36 +0000915 def load_binfloat(self, unpack=struct.unpack):
916 self.append(unpack('>d', self.read(8))[0])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000917 dispatch[BINFLOAT[0]] = load_binfloat
Guido van Rossumd3703791998-10-22 20:15:36 +0000918
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000919 def load_string(self):
Guido van Rossum98297ee2007-11-06 21:34:58 +0000920 orig = self.readline()
921 rep = orig[:-1]
Guido van Rossum26d95c32007-08-27 23:18:54 +0000922 for q in (b'"', b"'"): # double or single quote
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000923 if rep.startswith(q):
924 if not rep.endswith(q):
Guido van Rossum26d95c32007-08-27 23:18:54 +0000925 raise ValueError("insecure string pickle")
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000926 rep = rep[len(q):-len(q)]
927 break
928 else:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000929 raise ValueError("insecure string pickle: %r" % orig)
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000930 self.append(codecs.escape_decode(rep)[0]
931 .decode(self.encoding, self.errors))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000932 dispatch[STRING[0]] = load_string
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000933
934 def load_binstring(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000935 len = mloads(b'i' + self.read(4))
Guido van Rossumf4169812008-03-17 22:56:06 +0000936 data = self.read(len)
937 value = str(data, self.encoding, self.errors)
938 self.append(value)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000939 dispatch[BINSTRING[0]] = load_binstring
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000940
Guido van Rossumf4169812008-03-17 22:56:06 +0000941 def load_binbytes(self):
942 len = mloads(b'i' + self.read(4))
943 self.append(self.read(len))
944 dispatch[BINBYTES[0]] = load_binbytes
945
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000946 def load_unicode(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000947 self.append(str(self.readline()[:-1], 'raw-unicode-escape'))
948 dispatch[UNICODE[0]] = load_unicode
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000949
950 def load_binunicode(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000951 len = mloads(b'i' + self.read(4))
952 self.append(str(self.read(len), 'utf-8'))
953 dispatch[BINUNICODE[0]] = load_binunicode
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000954
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000955 def load_short_binstring(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000956 len = ord(self.read(1))
Guido van Rossumf4169812008-03-17 22:56:06 +0000957 data = bytes(self.read(len))
958 value = str(data, self.encoding, self.errors)
959 self.append(value)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000960 dispatch[SHORT_BINSTRING[0]] = load_short_binstring
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000961
Guido van Rossumf4169812008-03-17 22:56:06 +0000962 def load_short_binbytes(self):
963 len = ord(self.read(1))
964 self.append(bytes(self.read(len)))
965 dispatch[SHORT_BINBYTES[0]] = load_short_binbytes
966
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000967 def load_tuple(self):
968 k = self.marker()
969 self.stack[k:] = [tuple(self.stack[k+1:])]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000970 dispatch[TUPLE[0]] = load_tuple
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000971
972 def load_empty_tuple(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000973 self.append(())
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000974 dispatch[EMPTY_TUPLE[0]] = load_empty_tuple
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000975
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000976 def load_tuple1(self):
977 self.stack[-1] = (self.stack[-1],)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000978 dispatch[TUPLE1[0]] = load_tuple1
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000979
980 def load_tuple2(self):
981 self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000982 dispatch[TUPLE2[0]] = load_tuple2
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000983
984 def load_tuple3(self):
985 self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000986 dispatch[TUPLE3[0]] = load_tuple3
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000987
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000988 def load_empty_list(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000989 self.append([])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000990 dispatch[EMPTY_LIST[0]] = load_empty_list
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000991
992 def load_empty_dictionary(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000993 self.append({})
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000994 dispatch[EMPTY_DICT[0]] = load_empty_dictionary
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000995
996 def load_list(self):
997 k = self.marker()
998 self.stack[k:] = [self.stack[k+1:]]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000999 dispatch[LIST[0]] = load_list
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001000
1001 def load_dict(self):
1002 k = self.marker()
1003 d = {}
1004 items = self.stack[k+1:]
1005 for i in range(0, len(items), 2):
1006 key = items[i]
1007 value = items[i+1]
1008 d[key] = value
1009 self.stack[k:] = [d]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001010 dispatch[DICT[0]] = load_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001011
Tim Petersd01c1e92003-01-30 15:41:46 +00001012 # INST and OBJ differ only in how they get a class object. It's not
1013 # only sensible to do the rest in a common routine, the two routines
1014 # previously diverged and grew different bugs.
1015 # klass is the class to instantiate, and k points to the topmost mark
1016 # object, following which are the arguments for klass.__init__.
1017 def _instantiate(self, klass, k):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001018 args = tuple(self.stack[k+1:])
1019 del self.stack[k:]
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001020 instantiated = False
Tim Petersd01c1e92003-01-30 15:41:46 +00001021 if (not args and
Guido van Rossum13257902007-06-07 23:15:56 +00001022 isinstance(klass, type) and
Tim Petersd01c1e92003-01-30 15:41:46 +00001023 not hasattr(klass, "__getinitargs__")):
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001024 value = _EmptyClass()
1025 value.__class__ = klass
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001026 instantiated = True
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001027 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +00001028 try:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001029 value = klass(*args)
Guido van Rossumb940e112007-01-10 16:19:56 +00001030 except TypeError as err:
Guido van Rossum26d95c32007-08-27 23:18:54 +00001031 raise TypeError("in constructor for %s: %s" %
1032 (klass.__name__, str(err)), sys.exc_info()[2])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001033 self.append(value)
Tim Petersd01c1e92003-01-30 15:41:46 +00001034
1035 def load_inst(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001036 module = self.readline()[:-1].decode("ascii")
1037 name = self.readline()[:-1].decode("ascii")
Tim Petersd01c1e92003-01-30 15:41:46 +00001038 klass = self.find_class(module, name)
1039 self._instantiate(klass, self.marker())
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001040 dispatch[INST[0]] = load_inst
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001041
1042 def load_obj(self):
Tim Petersd01c1e92003-01-30 15:41:46 +00001043 # Stack is ... markobject classobject arg1 arg2 ...
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001044 k = self.marker()
Tim Petersd01c1e92003-01-30 15:41:46 +00001045 klass = self.stack.pop(k+1)
1046 self._instantiate(klass, k)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001047 dispatch[OBJ[0]] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001048
Guido van Rossum3a41c612003-01-28 15:10:22 +00001049 def load_newobj(self):
1050 args = self.stack.pop()
1051 cls = self.stack[-1]
1052 obj = cls.__new__(cls, *args)
Guido van Rossum533dbcf2003-01-28 17:55:05 +00001053 self.stack[-1] = obj
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001054 dispatch[NEWOBJ[0]] = load_newobj
Guido van Rossum3a41c612003-01-28 15:10:22 +00001055
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001056 def load_global(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001057 module = self.readline()[:-1].decode("utf-8")
1058 name = self.readline()[:-1].decode("utf-8")
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001059 klass = self.find_class(module, name)
1060 self.append(klass)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001061 dispatch[GLOBAL[0]] = load_global
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001062
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001063 def load_ext1(self):
1064 code = ord(self.read(1))
1065 self.get_extension(code)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001066 dispatch[EXT1[0]] = load_ext1
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001067
1068 def load_ext2(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001069 code = mloads(b'i' + self.read(2) + b'\000\000')
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001070 self.get_extension(code)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001071 dispatch[EXT2[0]] = load_ext2
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001072
1073 def load_ext4(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001074 code = mloads(b'i' + self.read(4))
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001075 self.get_extension(code)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001076 dispatch[EXT4[0]] = load_ext4
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001077
1078 def get_extension(self, code):
1079 nil = []
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001080 obj = _extension_cache.get(code, nil)
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001081 if obj is not nil:
1082 self.append(obj)
1083 return
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001084 key = _inverted_registry.get(code)
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001085 if not key:
1086 raise ValueError("unregistered extension code %d" % code)
1087 obj = self.find_class(*key)
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001088 _extension_cache[code] = obj
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001089 self.append(obj)
1090
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001091 def find_class(self, module, name):
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001092 # Subclasses may override this
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001093 __import__(module, level=0)
Barry Warsawbf4d9592001-11-15 23:42:58 +00001094 mod = sys.modules[module]
1095 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001096 return klass
1097
1098 def load_reduce(self):
1099 stack = self.stack
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001100 args = stack.pop()
1101 func = stack[-1]
Guido van Rossum99603b02007-07-20 00:22:32 +00001102 try:
1103 value = func(*args)
1104 except:
1105 print(sys.exc_info())
1106 print(func, args)
1107 raise
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001108 stack[-1] = value
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001109 dispatch[REDUCE[0]] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +00001110
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001111 def load_pop(self):
1112 del self.stack[-1]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001113 dispatch[POP[0]] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +00001114
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001115 def load_pop_mark(self):
1116 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001117 del self.stack[k:]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001118 dispatch[POP_MARK[0]] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001119
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001120 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +00001121 self.append(self.stack[-1])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001122 dispatch[DUP[0]] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +00001123
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001124 def load_get(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001125 i = int(self.readline()[:-1])
1126 self.append(self.memo[i])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001127 dispatch[GET[0]] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +00001128
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001129 def load_binget(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001130 i = self.read(1)[0]
1131 self.append(self.memo[i])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001132 dispatch[BINGET[0]] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001133
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001134 def load_long_binget(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001135 i = mloads(b'i' + self.read(4))
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001136 self.append(self.memo[i])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001137 dispatch[LONG_BINGET[0]] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001138
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001139 def load_put(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001140 i = int(self.readline()[:-1])
1141 self.memo[i] = self.stack[-1]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001142 dispatch[PUT[0]] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +00001143
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001144 def load_binput(self):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001145 i = self.read(1)[0]
1146 self.memo[i] = self.stack[-1]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001147 dispatch[BINPUT[0]] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001148
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001149 def load_long_binput(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001150 i = mloads(b'i' + self.read(4))
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001151 self.memo[i] = self.stack[-1]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001152 dispatch[LONG_BINPUT[0]] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001153
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001154 def load_append(self):
1155 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001156 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001157 list = stack[-1]
1158 list.append(value)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001159 dispatch[APPEND[0]] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +00001160
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001161 def load_appends(self):
1162 stack = self.stack
1163 mark = self.marker()
1164 list = stack[mark - 1]
Tim Peters209ad952003-01-28 01:44:45 +00001165 list.extend(stack[mark + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001166 del stack[mark:]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001167 dispatch[APPENDS[0]] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +00001168
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001169 def load_setitem(self):
1170 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001171 value = stack.pop()
1172 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001173 dict = stack[-1]
1174 dict[key] = value
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001175 dispatch[SETITEM[0]] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001176
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001177 def load_setitems(self):
1178 stack = self.stack
1179 mark = self.marker()
1180 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001181 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001182 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001183
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001184 del stack[mark:]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001185 dispatch[SETITEMS[0]] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001186
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001187 def load_build(self):
1188 stack = self.stack
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001189 state = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001190 inst = stack[-1]
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001191 setstate = getattr(inst, "__setstate__", None)
1192 if setstate:
1193 setstate(state)
1194 return
1195 slotstate = None
1196 if isinstance(state, tuple) and len(state) == 2:
1197 state, slotstate = state
1198 if state:
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001199 inst.__dict__.update(state)
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001200 if slotstate:
1201 for k, v in slotstate.items():
1202 setattr(inst, k, v)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001203 dispatch[BUILD[0]] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001204
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001205 def load_mark(self):
1206 self.append(self.mark)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001207 dispatch[MARK[0]] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001208
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001209 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001210 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001211 raise _Stop(value)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001212 dispatch[STOP[0]] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001213
Guido van Rossume467be61997-12-05 19:42:42 +00001214# Helper class for load_inst/load_obj
1215
1216class _EmptyClass:
1217 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001218
Tim Peters91149822003-01-31 03:43:58 +00001219# Encode/decode longs in linear time.
1220
1221import binascii as _binascii
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001222
1223def encode_long(x):
Tim Peters91149822003-01-31 03:43:58 +00001224 r"""Encode a long to a two's complement little-endian binary string.
Guido van Rossume2a383d2007-01-15 16:59:06 +00001225 Note that 0 is a special case, returning an empty string, to save a
Tim Peters4b23f2b2003-01-31 16:43:39 +00001226 byte in the LONG1 pickling context.
1227
Guido van Rossume2a383d2007-01-15 16:59:06 +00001228 >>> encode_long(0)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001229 b''
Guido van Rossume2a383d2007-01-15 16:59:06 +00001230 >>> encode_long(255)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001231 b'\xff\x00'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001232 >>> encode_long(32767)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001233 b'\xff\x7f'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001234 >>> encode_long(-256)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001235 b'\x00\xff'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001236 >>> encode_long(-32768)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001237 b'\x00\x80'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001238 >>> encode_long(-128)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001239 b'\x80'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001240 >>> encode_long(127)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001241 b'\x7f'
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001242 >>>
1243 """
Tim Peters91149822003-01-31 03:43:58 +00001244
1245 if x == 0:
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001246 return b''
Tim Peters91149822003-01-31 03:43:58 +00001247 if x > 0:
1248 ashex = hex(x)
1249 assert ashex.startswith("0x")
1250 njunkchars = 2 + ashex.endswith('L')
1251 nibbles = len(ashex) - njunkchars
1252 if nibbles & 1:
1253 # need an even # of nibbles for unhexlify
1254 ashex = "0x0" + ashex[2:]
Tim Peters4b23f2b2003-01-31 16:43:39 +00001255 elif int(ashex[2], 16) >= 8:
Tim Peters91149822003-01-31 03:43:58 +00001256 # "looks negative", so need a byte of sign bits
1257 ashex = "0x00" + ashex[2:]
1258 else:
1259 # Build the 256's-complement: (1L << nbytes) + x. The trick is
1260 # to find the number of bytes in linear time (although that should
1261 # really be a constant-time task).
1262 ashex = hex(-x)
1263 assert ashex.startswith("0x")
1264 njunkchars = 2 + ashex.endswith('L')
1265 nibbles = len(ashex) - njunkchars
1266 if nibbles & 1:
Tim Petersee1a53c2003-02-02 02:57:53 +00001267 # Extend to a full byte.
Tim Peters91149822003-01-31 03:43:58 +00001268 nibbles += 1
Tim Peters4b23f2b2003-01-31 16:43:39 +00001269 nbits = nibbles * 4
Guido van Rossume2a383d2007-01-15 16:59:06 +00001270 x += 1 << nbits
Tim Peters91149822003-01-31 03:43:58 +00001271 assert x > 0
1272 ashex = hex(x)
Tim Petersee1a53c2003-02-02 02:57:53 +00001273 njunkchars = 2 + ashex.endswith('L')
1274 newnibbles = len(ashex) - njunkchars
1275 if newnibbles < nibbles:
1276 ashex = "0x" + "0" * (nibbles - newnibbles) + ashex[2:]
1277 if int(ashex[2], 16) < 8:
Tim Peters91149822003-01-31 03:43:58 +00001278 # "looks positive", so need a byte of sign bits
Tim Petersee1a53c2003-02-02 02:57:53 +00001279 ashex = "0xff" + ashex[2:]
Tim Peters91149822003-01-31 03:43:58 +00001280
1281 if ashex.endswith('L'):
1282 ashex = ashex[2:-1]
1283 else:
1284 ashex = ashex[2:]
Tim Petersee1a53c2003-02-02 02:57:53 +00001285 assert len(ashex) & 1 == 0, (x, ashex)
Tim Peters91149822003-01-31 03:43:58 +00001286 binary = _binascii.unhexlify(ashex)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001287 return bytes(binary[::-1])
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001288
1289def decode_long(data):
1290 r"""Decode a long from a two's complement little-endian binary string.
Tim Peters4b23f2b2003-01-31 16:43:39 +00001291
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001292 >>> decode_long(b'')
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001293 0
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001294 >>> decode_long(b"\xff\x00")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001295 255
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001296 >>> decode_long(b"\xff\x7f")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001297 32767
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001298 >>> decode_long(b"\x00\xff")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001299 -256
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001300 >>> decode_long(b"\x00\x80")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001301 -32768
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001302 >>> decode_long(b"\x80")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001303 -128
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001304 >>> decode_long(b"\x7f")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001305 127
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001306 """
Tim Peters91149822003-01-31 03:43:58 +00001307
Tim Peters4b23f2b2003-01-31 16:43:39 +00001308 nbytes = len(data)
1309 if nbytes == 0:
Guido van Rossume2a383d2007-01-15 16:59:06 +00001310 return 0
Tim Peters91149822003-01-31 03:43:58 +00001311 ashex = _binascii.hexlify(data[::-1])
Guido van Rossume2a383d2007-01-15 16:59:06 +00001312 n = int(ashex, 16) # quadratic time before Python 2.3; linear now
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001313 if data[-1] >= 0x80:
Guido van Rossume2a383d2007-01-15 16:59:06 +00001314 n -= 1 << (nbytes * 8)
Tim Peters91149822003-01-31 03:43:58 +00001315 return n
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001316
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001317# Use the faster _pickle if possible
1318try:
1319 from _pickle import *
1320except ImportError:
1321 Pickler, Unpickler = _Pickler, _Unpickler
1322
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001323# Shorthands
1324
Raymond Hettinger3489cad2004-12-05 05:20:42 +00001325def dump(obj, file, protocol=None):
1326 Pickler(file, protocol).dump(obj)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001327
Raymond Hettinger3489cad2004-12-05 05:20:42 +00001328def dumps(obj, protocol=None):
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001329 f = io.BytesIO()
1330 Pickler(f, protocol).dump(obj)
1331 res = f.getvalue()
Guido van Rossum98297ee2007-11-06 21:34:58 +00001332 assert isinstance(res, bytes_types)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001333 return res
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001334
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001335def load(file, *, encoding="ASCII", errors="strict"):
1336 return Unpickler(file, encoding=encoding, errors=errors).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001337
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001338def loads(s, *, encoding="ASCII", errors="strict"):
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001339 if isinstance(s, str):
1340 raise TypeError("Can't load pickle from unicode string")
1341 file = io.BytesIO(s)
Alexandre Vassalottica2d6102008-06-12 18:26:05 +00001342 return Unpickler(file, encoding=encoding, errors=errors).load()
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001343
1344# Doctest
1345
1346def _test():
1347 import doctest
1348 return doctest.testmod()
1349
1350if __name__ == "__main__":
1351 _test()