blob: d7bf24e69ef8a581f9b54faeef33c24f387a33ca [file] [log] [blame]
Guido van Rossum54f22ed2000-02-04 15:10:34 +00001"""Create portable serialized representations of Python objects.
Guido van Rossuma48061a1995-01-10 00:31:14 +00002
Guido van Rossume467be61997-12-05 19:42:42 +00003See module copy_reg 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
Guido van Rossum443ada42003-02-18 22:49:10 +000029from copy_reg import dispatch_table
Guido van Rossumd4b920c2003-02-04 01:54:49 +000030from copy_reg 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
42bytes_types = (bytes, buffer, memoryview)
43
Tim Petersc0c12b52003-01-29 00:56:17 +000044# These are purely informational; no code uses these.
Guido van Rossumf29d3d62003-01-27 22:47:53 +000045format_version = "2.0" # File format version we write
46compatible_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
51 ] # Old format versions we can read
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000052
Guido van Rossum99603b02007-07-20 00:22:32 +000053# This is the highest protocol number we know how to read.
Tim Peters8587b3c2003-02-13 15:44:41 +000054HIGHEST_PROTOCOL = 2
55
Guido van Rossum2e6a4b32007-05-04 19:56:22 +000056# The protocol we write by default. May be less than HIGHEST_PROTOCOL.
57DEFAULT_PROTOCOL = 2
58
Guido van Rossume0b90422003-01-28 03:17:21 +000059# Why use struct.pack() for pickling but marshal.loads() for
Tim Petersc0c12b52003-01-29 00:56:17 +000060# unpickling? struct.pack() is 40% faster than marshal.dumps(), but
Guido van Rossume0b90422003-01-28 03:17:21 +000061# marshal.loads() is twice as fast as struct.unpack()!
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000062mloads = marshal.loads
Guido van Rossum0c891ce1995-03-14 15:09:05 +000063
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000064class PickleError(Exception):
Neal Norwitzefbb67b2002-05-30 12:12:04 +000065 """A common base class for the other pickling exceptions."""
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000066 pass
67
68class PicklingError(PickleError):
69 """This exception is raised when an unpicklable object is passed to the
70 dump() method.
71
72 """
73 pass
74
75class UnpicklingError(PickleError):
76 """This exception is raised when there is a problem unpickling an object,
77 such as a security violation.
78
79 Note that other exceptions may also be raised during unpickling, including
80 (but not necessarily limited to) AttributeError, EOFError, ImportError,
81 and IndexError.
82
83 """
84 pass
Guido van Rossum7849da81995-03-09 14:08:35 +000085
Tim Petersc0c12b52003-01-29 00:56:17 +000086# An instance of _Stop is raised by Unpickler.load_stop() in response to
87# the STOP opcode, passing the object that is the result of unpickling.
Guido van Rossumff871742000-12-13 18:11:56 +000088class _Stop(Exception):
89 def __init__(self, value):
90 self.value = value
91
Guido van Rossum533dbcf2003-01-28 17:55:05 +000092# Jython has PyStringMap; it's a dict subclass with string keys
Jeremy Hylton2b9d0291998-05-27 22:38:22 +000093try:
94 from org.python.core import PyStringMap
95except ImportError:
96 PyStringMap = None
97
Tim Peters22a449a2003-01-27 20:16:36 +000098# Pickle opcodes. See pickletools.py for extensive docs. The listing
99# here is in kind-of alphabetical order of 1-character pickle code.
100# pickletools groups them by purpose.
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000101
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000102MARK = b'(' # push special markobject on stack
103STOP = b'.' # every pickle ends with STOP
104POP = b'0' # discard topmost stack item
105POP_MARK = b'1' # discard stack top through topmost markobject
106DUP = b'2' # duplicate top stack item
107FLOAT = b'F' # push float object; decimal string argument
108INT = b'I' # push integer or bool; decimal string argument
109BININT = b'J' # push four-byte signed int
110BININT1 = b'K' # push 1-byte unsigned int
111LONG = b'L' # push long; decimal string argument
112BININT2 = b'M' # push 2-byte unsigned int
113NONE = b'N' # push None
114PERSID = b'P' # push persistent object; id is taken from string arg
115BINPERSID = b'Q' # " " " ; " " " " stack
116REDUCE = b'R' # apply callable to argtuple, both on stack
117STRING = b'S' # push string; NL-terminated string argument
118BINSTRING = b'T' # push string; counted binary string argument
119SHORT_BINSTRING= b'U' # " " ; " " " " < 256 bytes
120UNICODE = b'V' # push Unicode string; raw-unicode-escaped'd argument
121BINUNICODE = b'X' # " " " ; counted UTF-8 string argument
122APPEND = b'a' # append stack top to list below it
123BUILD = b'b' # call __setstate__ or __dict__.update()
124GLOBAL = b'c' # push self.find_class(modname, name); 2 string args
125DICT = b'd' # build a dict from stack items
126EMPTY_DICT = b'}' # push empty dict
127APPENDS = b'e' # extend list on stack by topmost stack slice
128GET = b'g' # push item from memo on stack; index is string arg
129BINGET = b'h' # " " " " " " ; " " 1-byte arg
130INST = b'i' # build & push class instance
131LONG_BINGET = b'j' # push item from memo on stack; index is 4-byte arg
132LIST = b'l' # build list from topmost stack items
133EMPTY_LIST = b']' # push empty list
134OBJ = b'o' # build & push class instance
135PUT = b'p' # store stack top in memo; index is string arg
136BINPUT = b'q' # " " " " " ; " " 1-byte arg
137LONG_BINPUT = b'r' # " " " " " ; " " 4-byte arg
138SETITEM = b's' # add key+value pair to dict
139TUPLE = b't' # build tuple from topmost stack items
140EMPTY_TUPLE = b')' # push empty tuple
141SETITEMS = b'u' # modify dict by adding topmost key+value pairs
142BINFLOAT = b'G' # push float; arg is 8-byte float encoding
Tim Peters22a449a2003-01-27 20:16:36 +0000143
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000144TRUE = b'I01\n' # not an opcode; see INT docs in pickletools.py
145FALSE = b'I00\n' # not an opcode; see INT docs in pickletools.py
Guido van Rossum77f6a652002-04-03 22:41:51 +0000146
Guido van Rossum586c9e82003-01-29 06:16:12 +0000147# Protocol 2
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000148
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000149PROTO = b'\x80' # identify pickle protocol
150NEWOBJ = b'\x81' # build object by applying cls.__new__ to argtuple
151EXT1 = b'\x82' # push object from extension registry; 1-byte index
152EXT2 = b'\x83' # ditto, but 2-byte index
153EXT4 = b'\x84' # ditto, but 4-byte index
154TUPLE1 = b'\x85' # build 1-tuple from stack top
155TUPLE2 = b'\x86' # build 2-tuple from two topmost stack items
156TUPLE3 = b'\x87' # build 3-tuple from three topmost stack items
157NEWTRUE = b'\x88' # push True
158NEWFALSE = b'\x89' # push False
159LONG1 = b'\x8a' # push long from < 256 bytes
160LONG4 = b'\x8b' # push really big long
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000161
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000162_tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3]
163
Guido van Rossuma48061a1995-01-10 00:31:14 +0000164
Skip Montanaro23bafc62001-02-18 03:10:09 +0000165__all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
166
Guido van Rossum1be31752003-01-28 15:19:53 +0000167
168# Pickling machinery
169
Guido van Rossuma48061a1995-01-10 00:31:14 +0000170class Pickler:
171
Raymond Hettinger3489cad2004-12-05 05:20:42 +0000172 def __init__(self, file, protocol=None):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000173 """This takes a binary file for writing a pickle data stream.
174
175 All protocols now read and write bytes.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000176
Guido van Rossumcf117b02003-02-09 17:19:41 +0000177 The optional protocol argument tells the pickler to use the
178 given protocol; supported protocols are 0, 1, 2. The default
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000179 protocol is 2; it's been supported for many years now.
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000180
181 Protocol 1 is more efficient than protocol 0; protocol 2 is
Guido van Rossum7eff63a2003-01-31 19:42:31 +0000182 more efficient than protocol 1.
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000183
Guido van Rossum7eff63a2003-01-31 19:42:31 +0000184 Specifying a negative protocol version selects the highest
Tim Peters5bd2a792003-02-01 16:45:06 +0000185 protocol version supported. The higher the protocol used, the
186 more recent the version of Python needed to read the pickle
187 produced.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000188
189 The file parameter must have a write() method that accepts a single
190 string argument. It can thus be an open file object, a StringIO
191 object, or any other custom object that meets this interface.
192
193 """
Guido van Rossumcf117b02003-02-09 17:19:41 +0000194 if protocol is None:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000195 protocol = DEFAULT_PROTOCOL
Guido van Rossumcf117b02003-02-09 17:19:41 +0000196 if protocol < 0:
Tim Peters8587b3c2003-02-13 15:44:41 +0000197 protocol = HIGHEST_PROTOCOL
198 elif not 0 <= protocol <= HIGHEST_PROTOCOL:
199 raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000200 self.write = file.write
201 self.memo = {}
Guido van Rossumcf117b02003-02-09 17:19:41 +0000202 self.proto = int(protocol)
203 self.bin = protocol >= 1
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000204 self.fast = 0
Guido van Rossuma48061a1995-01-10 00:31:14 +0000205
Fred Drake7f781c92002-05-01 20:33:53 +0000206 def clear_memo(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000207 """Clears the pickler's "memo".
208
209 The memo is the data structure that remembers which objects the
Tim Petersb377f8a2003-01-28 00:23:36 +0000210 pickler has already seen, so that shared or recursive objects are
211 pickled by reference and not by value. This method is useful when
212 re-using picklers.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000213
214 """
Fred Drake7f781c92002-05-01 20:33:53 +0000215 self.memo.clear()
216
Guido van Rossum3a41c612003-01-28 15:10:22 +0000217 def dump(self, obj):
Tim Peters5bd2a792003-02-01 16:45:06 +0000218 """Write a pickled representation of obj to the open file."""
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000219 if self.proto >= 2:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000220 self.write(PROTO + bytes([self.proto]))
Guido van Rossum3a41c612003-01-28 15:10:22 +0000221 self.save(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000222 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000223
Jeremy Hylton3422c992003-01-24 19:29:52 +0000224 def memoize(self, obj):
225 """Store an object in the memo."""
226
Tim Peterse46b73f2003-01-27 21:22:10 +0000227 # The Pickler memo is a dictionary mapping object ids to 2-tuples
228 # that contain the Unpickler memo key and the object being memoized.
229 # The memo key is written to the pickle and will become
Jeremy Hylton3422c992003-01-24 19:29:52 +0000230 # the key in the Unpickler's memo. The object is stored in the
Tim Peterse46b73f2003-01-27 21:22:10 +0000231 # Pickler memo so that transient objects are kept alive during
232 # pickling.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000233
Tim Peterse46b73f2003-01-27 21:22:10 +0000234 # The use of the Unpickler memo length as the memo key is just a
235 # convention. The only requirement is that the memo values be unique.
236 # But there appears no advantage to any other scheme, and this
Tim Peterscbd0a322003-01-28 00:24:43 +0000237 # scheme allows the Unpickler memo to be implemented as a plain (but
Tim Peterse46b73f2003-01-27 21:22:10 +0000238 # growable) array, indexed by memo key.
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000239 if self.fast:
240 return
Guido van Rossum9b40e802003-01-30 06:37:41 +0000241 assert id(obj) not in self.memo
Jeremy Hylton3422c992003-01-24 19:29:52 +0000242 memo_len = len(self.memo)
243 self.write(self.put(memo_len))
Tim Peters518df0d2003-01-28 01:00:38 +0000244 self.memo[id(obj)] = memo_len, obj
Jeremy Hylton3422c992003-01-24 19:29:52 +0000245
Tim Petersbb38e302003-01-27 21:25:41 +0000246 # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000247 def put(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000248 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000249 if i < 256:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000250 return BINPUT + bytes([i])
Guido van Rossum5c938d02003-01-28 03:03:08 +0000251 else:
252 return LONG_BINPUT + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000253
Guido van Rossum39478e82007-08-27 17:23:59 +0000254 return PUT + repr(i).encode("ascii") + b'\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000255
Tim Petersbb38e302003-01-27 21:25:41 +0000256 # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000257 def get(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000258 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000259 if i < 256:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000260 return BINGET + bytes([i])
Guido van Rossum5c938d02003-01-28 03:03:08 +0000261 else:
262 return LONG_BINGET + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000263
Guido van Rossum39478e82007-08-27 17:23:59 +0000264 return GET + repr(i).encode("ascii") + b'\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000265
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000266 def save(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000267 # Check for persistent id (defined by a subclass)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000268 pid = self.persistent_id(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000269 if pid:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000270 self.save_pers(pid)
271 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000272
Guido van Rossumbc64e222003-01-28 16:34:19 +0000273 # Check the memo
274 x = self.memo.get(id(obj))
275 if x:
276 self.write(self.get(x[0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000277 return
278
Guido van Rossumbc64e222003-01-28 16:34:19 +0000279 # Check the type dispatch table
Guido van Rossum3a41c612003-01-28 15:10:22 +0000280 t = type(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000281 f = self.dispatch.get(t)
282 if f:
283 f(self, obj) # Call unbound method with explicit self
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000284 return
285
Guido van Rossumbc64e222003-01-28 16:34:19 +0000286 # Check for a class with a custom metaclass; treat as regular class
Tim Petersb32a8312003-01-28 00:48:09 +0000287 try:
Guido van Rossum13257902007-06-07 23:15:56 +0000288 issc = issubclass(t, type)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000289 except TypeError: # t is not a class (old Boost; see SF #502085)
Tim Petersb32a8312003-01-28 00:48:09 +0000290 issc = 0
291 if issc:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000292 self.save_global(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000293 return
294
Guido van Rossumbc64e222003-01-28 16:34:19 +0000295 # Check copy_reg.dispatch_table
296 reduce = dispatch_table.get(t)
Guido van Rossumc53f0092003-02-18 22:05:12 +0000297 if reduce:
298 rv = reduce(obj)
299 else:
300 # Check for a __reduce_ex__ method, fall back to __reduce__
301 reduce = getattr(obj, "__reduce_ex__", None)
302 if reduce:
303 rv = reduce(self.proto)
304 else:
305 reduce = getattr(obj, "__reduce__", None)
306 if reduce:
307 rv = reduce()
308 else:
309 raise PicklingError("Can't pickle %r object: %r" %
310 (t.__name__, obj))
Tim Petersb32a8312003-01-28 00:48:09 +0000311
Guido van Rossumbc64e222003-01-28 16:34:19 +0000312 # Check for string returned by reduce(), meaning "save as global"
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000313 if isinstance(rv, str):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000314 self.save_global(obj, rv)
Tim Petersb32a8312003-01-28 00:48:09 +0000315 return
316
Guido van Rossumbc64e222003-01-28 16:34:19 +0000317 # Assert that reduce() returned a tuple
Guido van Rossum13257902007-06-07 23:15:56 +0000318 if not isinstance(rv, tuple):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000319 raise PicklingError("%s must return string or tuple" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000320
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000321 # Assert that it returned an appropriately sized tuple
Guido van Rossumbc64e222003-01-28 16:34:19 +0000322 l = len(rv)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000323 if not (2 <= l <= 5):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000324 raise PicklingError("Tuple returned by %s must have "
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000325 "two to five elements" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000326
Guido van Rossumbc64e222003-01-28 16:34:19 +0000327 # Save the reduce() output and finally memoize the object
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000328 self.save_reduce(obj=obj, *rv)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000329
Guido van Rossum3a41c612003-01-28 15:10:22 +0000330 def persistent_id(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000331 # This exists so a subclass can override it
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000332 return None
333
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000334 def save_pers(self, pid):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000335 # Save a persistent id reference
Tim Petersbd1cdb92003-01-28 01:03:10 +0000336 if self.bin:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000337 self.save(pid)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000338 self.write(BINPERSID)
Tim Petersbd1cdb92003-01-28 01:03:10 +0000339 else:
Guido van Rossum39478e82007-08-27 17:23:59 +0000340 self.write(PERSID + str(pid).encode("ascii") + b'\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000341
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000342 def save_reduce(self, func, args, state=None,
343 listitems=None, dictitems=None, obj=None):
Jeremy Hyltone3a565e2003-06-29 16:59:59 +0000344 # This API is called by some subclasses
Guido van Rossumbc64e222003-01-28 16:34:19 +0000345
346 # Assert that args is a tuple or None
Guido van Rossum13257902007-06-07 23:15:56 +0000347 if not isinstance(args, tuple):
Raymond Hettingera6b45cc2004-12-07 07:05:57 +0000348 raise PicklingError("args from reduce() should be a tuple")
Guido van Rossumbc64e222003-01-28 16:34:19 +0000349
350 # Assert that func is callable
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000351 if not hasattr(func, '__call__'):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000352 raise PicklingError("func from reduce should be callable")
353
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000354 save = self.save
Guido van Rossumbc64e222003-01-28 16:34:19 +0000355 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000356
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000357 # Protocol 2 special case: if func's name is __newobj__, use NEWOBJ
358 if self.proto >= 2 and getattr(func, "__name__", "") == "__newobj__":
359 # A __reduce__ implementation can direct protocol 2 to
360 # use the more efficient NEWOBJ opcode, while still
361 # allowing protocol 0 and 1 to work normally. For this to
362 # work, the function returned by __reduce__ should be
363 # called __newobj__, and its first argument should be a
364 # new-style class. The implementation for __newobj__
365 # should be as follows, although pickle has no way to
366 # verify this:
367 #
368 # def __newobj__(cls, *args):
369 # return cls.__new__(cls, *args)
370 #
371 # Protocols 0 and 1 will pickle a reference to __newobj__,
372 # while protocol 2 (and above) will pickle a reference to
373 # cls, the remaining args tuple, and the NEWOBJ code,
374 # which calls cls.__new__(cls, *args) at unpickling time
375 # (see load_newobj below). If __reduce__ returns a
376 # three-tuple, the state from the third tuple item will be
377 # pickled regardless of the protocol, calling __setstate__
378 # at unpickling time (see load_build below).
379 #
380 # Note that no standard __newobj__ implementation exists;
381 # you have to provide your own. This is to enforce
382 # compatibility with Python 2.2 (pickles written using
383 # protocol 0 or 1 in Python 2.3 should be unpicklable by
384 # Python 2.2).
385 cls = args[0]
386 if not hasattr(cls, "__new__"):
387 raise PicklingError(
388 "args[0] from __newobj__ args has no __new__")
Guido van Rossumf7f45172003-01-31 17:17:49 +0000389 if obj is not None and cls is not obj.__class__:
390 raise PicklingError(
391 "args[0] from __newobj__ args has the wrong class")
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000392 args = args[1:]
393 save(cls)
394 save(args)
395 write(NEWOBJ)
396 else:
397 save(func)
398 save(args)
399 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000400
Guido van Rossumf7f45172003-01-31 17:17:49 +0000401 if obj is not None:
402 self.memoize(obj)
403
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000404 # More new special cases (that work with older protocols as
405 # well): when __reduce__ returns a tuple with 4 or 5 items,
406 # the 4th and 5th item should be iterators that provide list
407 # items and dict items (as (key, value) tuples), or None.
408
409 if listitems is not None:
410 self._batch_appends(listitems)
411
412 if dictitems is not None:
413 self._batch_setitems(dictitems)
414
Tim Petersc32d8242001-04-10 02:48:53 +0000415 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000416 save(state)
417 write(BUILD)
418
Guido van Rossumbc64e222003-01-28 16:34:19 +0000419 # Methods below this point are dispatched through the dispatch table
420
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000421 dispatch = {}
422
Guido van Rossum3a41c612003-01-28 15:10:22 +0000423 def save_none(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000424 self.write(NONE)
Guido van Rossum13257902007-06-07 23:15:56 +0000425 dispatch[type(None)] = save_none
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000426
Guido van Rossum3a41c612003-01-28 15:10:22 +0000427 def save_bool(self, obj):
Guido van Rossum7d97d312003-01-28 04:25:27 +0000428 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000429 self.write(obj and NEWTRUE or NEWFALSE)
Guido van Rossum7d97d312003-01-28 04:25:27 +0000430 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000431 self.write(obj and TRUE or FALSE)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000432 dispatch[bool] = save_bool
433
Guido van Rossum3a41c612003-01-28 15:10:22 +0000434 def save_int(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000435 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000436 # If the int is small enough to fit in a signed 4-byte 2's-comp
437 # format, we can store it more efficiently than the general
438 # case.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000439 # First one- and two-byte unsigned ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000440 if obj >= 0:
441 if obj <= 0xff:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000442 self.write(BININT1 + bytes([obj]))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000443 return
Guido van Rossum3a41c612003-01-28 15:10:22 +0000444 if obj <= 0xffff:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000445 self.write(BININT2 + bytes([obj&0xff, obj>>8]))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000446 return
447 # Next check for 4-byte signed ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000448 high_bits = obj >> 31 # note that Python shift sign-extends
Tim Petersd95c2df2003-01-28 03:41:54 +0000449 if high_bits == 0 or high_bits == -1:
Tim Peters44714002001-04-10 05:02:52 +0000450 # All high bits are copies of bit 2**31, so the value
451 # fits in a 4-byte signed int.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000452 self.write(BININT + pack("<i", obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000453 return
Tim Peters44714002001-04-10 05:02:52 +0000454 # Text pickle, or int too big to fit in signed 4-byte format.
Guido van Rossum39478e82007-08-27 17:23:59 +0000455 self.write(INT + repr(obj).encode("ascii") + b'\n')
Guido van Rossumddefaf32007-01-14 03:31:43 +0000456 # XXX save_int is merged into save_long
Guido van Rossum13257902007-06-07 23:15:56 +0000457 # dispatch[int] = save_int
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000458
Guido van Rossum3a41c612003-01-28 15:10:22 +0000459 def save_long(self, obj, pack=struct.pack):
Guido van Rossumddefaf32007-01-14 03:31:43 +0000460 if self.bin:
461 # If the int is small enough to fit in a signed 4-byte 2's-comp
462 # format, we can store it more efficiently than the general
463 # case.
464 # First one- and two-byte unsigned ints:
465 if obj >= 0:
466 if obj <= 0xff:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000467 self.write(BININT1 + bytes([obj]))
Guido van Rossumddefaf32007-01-14 03:31:43 +0000468 return
469 if obj <= 0xffff:
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000470 self.write(BININT2 + bytes([obj&0xff, obj>>8]))
Guido van Rossumddefaf32007-01-14 03:31:43 +0000471 return
472 # Next check for 4-byte signed ints:
473 high_bits = obj >> 31 # note that Python shift sign-extends
474 if high_bits == 0 or high_bits == -1:
475 # All high bits are copies of bit 2**31, so the value
476 # fits in a 4-byte signed int.
477 self.write(BININT + pack("<i", obj))
478 return
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000479 if self.proto >= 2:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000480 encoded = encode_long(obj)
481 n = len(encoded)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000482 if n < 256:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000483 self.write(LONG1 + bytes([n]) + encoded)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000484 else:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000485 self.write(LONG4 + pack("<i", n) + encoded)
Tim Petersee1a53c2003-02-02 02:57:53 +0000486 return
Guido van Rossum39478e82007-08-27 17:23:59 +0000487 self.write(LONG + repr(obj).encode("ascii") + b'\n')
Guido van Rossum13257902007-06-07 23:15:56 +0000488 dispatch[int] = save_long
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000489
Guido van Rossum3a41c612003-01-28 15:10:22 +0000490 def save_float(self, obj, pack=struct.pack):
Guido van Rossumd3703791998-10-22 20:15:36 +0000491 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000492 self.write(BINFLOAT + pack('>d', obj))
Guido van Rossumd3703791998-10-22 20:15:36 +0000493 else:
Guido van Rossum39478e82007-08-27 17:23:59 +0000494 self.write(FLOAT + repr(obj).encode("ascii") + b'\n')
Guido van Rossum13257902007-06-07 23:15:56 +0000495 dispatch[float] = save_float
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000496
Guido van Rossum3a41c612003-01-28 15:10:22 +0000497 def save_string(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000498 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000499 n = len(obj)
Tim Petersbbf63cd2003-01-27 21:15:36 +0000500 if n < 256:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000501 self.write(SHORT_BINSTRING + bytes([n]) + bytes(obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000502 else:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000503 self.write(BINSTRING + pack("<i", n) + bytes(obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000504 else:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000505 # Strip leading 'b' due to repr() of bytes() returning b'...'
506 self.write(STRING + repr(obj).lstrip("b").encode("ascii") + b'\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000507 self.memoize(obj)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000508 dispatch[bytes] = save_string
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000509
Guido van Rossum3a41c612003-01-28 15:10:22 +0000510 def save_unicode(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000511 if self.bin:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000512 encoded = obj.encode('utf-8')
513 n = len(encoded)
514 self.write(BINUNICODE + pack("<i", n) + encoded)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000515 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000516 obj = obj.replace("\\", "\\u005c")
517 obj = obj.replace("\n", "\\u000a")
Guido van Rossum1255ed62007-05-04 20:30:19 +0000518 self.write(UNICODE + bytes(obj.encode('raw-unicode-escape')) +
519 b'\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000520 self.memoize(obj)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000521 dispatch[str] = save_unicode
Tim Peters658cba62001-02-09 20:06:00 +0000522
Guido van Rossum3a41c612003-01-28 15:10:22 +0000523 def save_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000524 write = self.write
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000525 proto = self.proto
526
Guido van Rossum3a41c612003-01-28 15:10:22 +0000527 n = len(obj)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000528 if n == 0:
529 if proto:
530 write(EMPTY_TUPLE)
531 else:
532 write(MARK + TUPLE)
Tim Petersd97da802003-01-28 05:48:29 +0000533 return
534
535 save = self.save
536 memo = self.memo
537 if n <= 3 and proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000538 for element in obj:
Tim Petersd97da802003-01-28 05:48:29 +0000539 save(element)
540 # Subtle. Same as in the big comment below.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000541 if id(obj) in memo:
542 get = self.get(memo[id(obj)][0])
Tim Petersd97da802003-01-28 05:48:29 +0000543 write(POP * n + get)
544 else:
545 write(_tuplesize2code[n])
Guido van Rossum3a41c612003-01-28 15:10:22 +0000546 self.memoize(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000547 return
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000548
Tim Peters1d63c9f2003-02-02 20:29:39 +0000549 # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple
Tim Petersff57bff2003-01-28 05:34:53 +0000550 # has more than 3 elements.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000551 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000552 for element in obj:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000553 save(element)
554
Tim Peters1d63c9f2003-02-02 20:29:39 +0000555 if id(obj) in memo:
Tim Petersf558da02003-01-28 02:09:55 +0000556 # Subtle. d was not in memo when we entered save_tuple(), so
557 # the process of saving the tuple's elements must have saved
558 # the tuple itself: the tuple is recursive. The proper action
559 # now is to throw away everything we put on the stack, and
560 # simply GET the tuple (it's already constructed). This check
561 # could have been done in the "for element" loop instead, but
562 # recursive tuples are a rare thing.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000563 get = self.get(memo[id(obj)][0])
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000564 if proto:
Tim Petersf558da02003-01-28 02:09:55 +0000565 write(POP_MARK + get)
566 else: # proto 0 -- POP_MARK not available
Tim Petersd97da802003-01-28 05:48:29 +0000567 write(POP * (n+1) + get)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000568 return
569
Tim Peters1d63c9f2003-02-02 20:29:39 +0000570 # No recursion.
Tim Peters518df0d2003-01-28 01:00:38 +0000571 self.write(TUPLE)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000572 self.memoize(obj)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000573
Guido van Rossum13257902007-06-07 23:15:56 +0000574 dispatch[tuple] = save_tuple
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000575
Tim Petersa6ae9a22003-01-28 16:58:41 +0000576 # save_empty_tuple() isn't used by anything in Python 2.3. However, I
577 # found a Pickler subclass in Zope3 that calls it, so it's not harmless
578 # to remove it.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000579 def save_empty_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000580 self.write(EMPTY_TUPLE)
581
Guido van Rossum3a41c612003-01-28 15:10:22 +0000582 def save_list(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000583 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000584
Tim Petersc32d8242001-04-10 02:48:53 +0000585 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000586 write(EMPTY_LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000587 else: # proto 0 -- can't use EMPTY_LIST
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000588 write(MARK + LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000589
590 self.memoize(obj)
591 self._batch_appends(iter(obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000592
Guido van Rossum13257902007-06-07 23:15:56 +0000593 dispatch[list] = save_list
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000594
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000595 _BATCHSIZE = 1000
596
597 def _batch_appends(self, items):
598 # Helper to batch up APPENDS sequences
599 save = self.save
600 write = self.write
601
602 if not self.bin:
603 for x in items:
604 save(x)
605 write(APPEND)
606 return
607
Guido van Rossum805365e2007-05-07 22:24:25 +0000608 r = range(self._BATCHSIZE)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000609 while items is not None:
610 tmp = []
611 for i in r:
612 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000613 x = next(items)
Guido van Rossum5aac4e62003-02-06 22:57:00 +0000614 tmp.append(x)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000615 except StopIteration:
616 items = None
617 break
618 n = len(tmp)
619 if n > 1:
620 write(MARK)
621 for x in tmp:
622 save(x)
623 write(APPENDS)
624 elif n:
625 save(tmp[0])
626 write(APPEND)
627 # else tmp is empty, and we're done
628
Guido van Rossum3a41c612003-01-28 15:10:22 +0000629 def save_dict(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000630 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000631
Tim Petersc32d8242001-04-10 02:48:53 +0000632 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000633 write(EMPTY_DICT)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000634 else: # proto 0 -- can't use EMPTY_DICT
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000635 write(MARK + DICT)
636
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000637 self.memoize(obj)
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000638 self._batch_setitems(iter(obj.items()))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000639
Guido van Rossum13257902007-06-07 23:15:56 +0000640 dispatch[dict] = save_dict
641 if PyStringMap is not None:
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000642 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000643
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000644 def _batch_setitems(self, items):
645 # Helper to batch up SETITEMS sequences; proto >= 1 only
646 save = self.save
647 write = self.write
648
649 if not self.bin:
650 for k, v in items:
651 save(k)
652 save(v)
653 write(SETITEM)
654 return
655
Guido van Rossum805365e2007-05-07 22:24:25 +0000656 r = range(self._BATCHSIZE)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000657 while items is not None:
658 tmp = []
659 for i in r:
660 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000661 tmp.append(next(items))
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000662 except StopIteration:
663 items = None
664 break
665 n = len(tmp)
666 if n > 1:
667 write(MARK)
668 for k, v in tmp:
669 save(k)
670 save(v)
671 write(SETITEMS)
672 elif n:
673 k, v = tmp[0]
674 save(k)
675 save(v)
676 write(SETITEM)
677 # else tmp is empty, and we're done
678
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000679 def save_global(self, obj, name=None, pack=struct.pack):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000680 write = self.write
681 memo = self.memo
682
Tim Petersc32d8242001-04-10 02:48:53 +0000683 if name is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000684 name = obj.__name__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000685
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000686 module = getattr(obj, "__module__", None)
687 if module is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000688 module = whichmodule(obj, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000689
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000690 try:
691 __import__(module)
692 mod = sys.modules[module]
693 klass = getattr(mod, name)
694 except (ImportError, KeyError, AttributeError):
695 raise PicklingError(
696 "Can't pickle %r: it's not found as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000697 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000698 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000699 if klass is not obj:
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000700 raise PicklingError(
701 "Can't pickle %r: it's not the same object as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000702 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000703
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000704 if self.proto >= 2:
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000705 code = _extension_registry.get((module, name))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000706 if code:
707 assert code > 0
708 if code <= 0xff:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000709 write(EXT1 + bytes([code]))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000710 elif code <= 0xffff:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000711 write(EXT2 + bytes([code&0xff, code>>8]))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000712 else:
713 write(EXT4 + pack("<i", code))
714 return
715
Guido van Rossum39478e82007-08-27 17:23:59 +0000716 write(GLOBAL + bytes(module, "utf-8") + b'\n' +
717 bytes(name, "utf-8") + b'\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000718 self.memoize(obj)
Tim Peters3b769832003-01-28 03:51:36 +0000719
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000720 dispatch[FunctionType] = save_global
721 dispatch[BuiltinFunctionType] = save_global
Guido van Rossum13257902007-06-07 23:15:56 +0000722 dispatch[type] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000723
Guido van Rossum1be31752003-01-28 15:19:53 +0000724# Pickling helpers
Guido van Rossuma48061a1995-01-10 00:31:14 +0000725
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000726def _keep_alive(x, memo):
727 """Keeps a reference to the object x in the memo.
728
729 Because we remember objects by their id, we have
730 to assure that possibly temporary objects are kept
731 alive by referencing them.
732 We store a reference at the id of the memo, which should
733 normally not be used unless someone tries to deepcopy
734 the memo itself...
735 """
736 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000737 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000738 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000739 # aha, this is the first one :-)
740 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000741
742
Tim Petersc0c12b52003-01-29 00:56:17 +0000743# A cache for whichmodule(), mapping a function object to the name of
744# the module in which the function was found.
745
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000746classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000747
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000748def whichmodule(func, funcname):
749 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000750
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000751 Search sys.modules for the module.
752 Cache in classmap.
753 Return a module name.
Tim Petersc0c12b52003-01-29 00:56:17 +0000754 If the function cannot be found, return "__main__".
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000755 """
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000756 # Python functions should always get an __module__ from their globals.
757 mod = getattr(func, "__module__", None)
758 if mod is not None:
759 return mod
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000760 if func in classmap:
761 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000762
Guido van Rossum634e53f2007-02-26 07:07:02 +0000763 for name, module in list(sys.modules.items()):
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000764 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000765 continue # skip dummy package entries
Jeremy Hyltoncc1fccb2003-02-06 16:23:01 +0000766 if name != '__main__' and getattr(module, funcname, None) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000767 break
768 else:
769 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000770 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000771 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000772
773
Guido van Rossum1be31752003-01-28 15:19:53 +0000774# Unpickling machinery
775
Guido van Rossuma48061a1995-01-10 00:31:14 +0000776class Unpickler:
777
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000778 def __init__(self, file):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000779 """This takes a binary file for reading a pickle data stream.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000780
Tim Peters5bd2a792003-02-01 16:45:06 +0000781 The protocol version of the pickle is detected automatically, so no
782 proto argument is needed.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000783
Guido van Rossumfeea0782007-10-10 18:00:50 +0000784 The file-like object must have two methods, a read() method
785 that takes an integer argument, and a readline() method that
786 requires no arguments. Both methods should return bytes.
787 Thus file-like object can be a binary file object opened for
788 reading, a BytesIO object, or any other custom object that
789 meets this interface.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000790 """
Guido van Rossumfeea0782007-10-10 18:00:50 +0000791 self.readline = file.readline
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000792 self.read = file.read
793 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000794
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000795 def load(self):
Guido van Rossum3a41c612003-01-28 15:10:22 +0000796 """Read a pickled object representation from the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000797
Guido van Rossum3a41c612003-01-28 15:10:22 +0000798 Return the reconstituted object hierarchy specified in the file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000799 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000800 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000801 self.stack = []
802 self.append = self.stack.append
803 read = self.read
804 dispatch = self.dispatch
805 try:
806 while 1:
807 key = read(1)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000808 if not key:
809 raise EOFError
Guido van Rossum98297ee2007-11-06 21:34:58 +0000810 assert isinstance(key, bytes_types)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000811 dispatch[key[0]](self)
Guido van Rossumb940e112007-01-10 16:19:56 +0000812 except _Stop as stopinst:
Guido van Rossumff871742000-12-13 18:11:56 +0000813 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000814
Tim Petersc23d18a2003-01-28 01:41:51 +0000815 # Return largest index k such that self.stack[k] is self.mark.
816 # If the stack doesn't contain a mark, eventually raises IndexError.
817 # This could be sped by maintaining another stack, of indices at which
818 # the mark appears. For that matter, the latter stack would suffice,
819 # and we wouldn't need to push mark objects on self.stack at all.
820 # Doing so is probably a good thing, though, since if the pickle is
821 # corrupt (or hostile) we may get a clue from finding self.mark embedded
822 # in unpickled objects.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000823 def marker(self):
824 stack = self.stack
825 mark = self.mark
826 k = len(stack)-1
827 while stack[k] is not mark: k = k-1
828 return k
829
830 dispatch = {}
831
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000832 def load_proto(self):
833 proto = ord(self.read(1))
834 if not 0 <= proto <= 2:
Guido van Rossum26d95c32007-08-27 23:18:54 +0000835 raise ValueError("unsupported pickle protocol: %d" % proto)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000836 dispatch[PROTO[0]] = load_proto
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000837
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000838 def load_persid(self):
839 pid = self.readline()[:-1]
840 self.append(self.persistent_load(pid))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000841 dispatch[PERSID[0]] = load_persid
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000842
843 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000844 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000845 self.append(self.persistent_load(pid))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000846 dispatch[BINPERSID[0]] = load_binpersid
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000847
848 def load_none(self):
849 self.append(None)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000850 dispatch[NONE[0]] = load_none
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000851
Guido van Rossum7d97d312003-01-28 04:25:27 +0000852 def load_false(self):
853 self.append(False)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000854 dispatch[NEWFALSE[0]] = load_false
Guido van Rossum7d97d312003-01-28 04:25:27 +0000855
856 def load_true(self):
857 self.append(True)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000858 dispatch[NEWTRUE[0]] = load_true
Guido van Rossum7d97d312003-01-28 04:25:27 +0000859
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000860 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000861 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000862 if data == FALSE[1:]:
863 val = False
864 elif data == TRUE[1:]:
865 val = True
866 else:
867 try:
868 val = int(data)
869 except ValueError:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000870 val = int(data)
Guido van Rossume2763392002-04-05 19:30:08 +0000871 self.append(val)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000872 dispatch[INT[0]] = load_int
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000873
874 def load_binint(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000875 self.append(mloads(b'i' + self.read(4)))
876 dispatch[BININT[0]] = load_binint
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000877
878 def load_binint1(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000879 self.append(ord(self.read(1)))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000880 dispatch[BININT1[0]] = load_binint1
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000881
882 def load_binint2(self):
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000883 self.append(mloads(b'i' + self.read(2) + b'\000\000'))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000884 dispatch[BININT2[0]] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000885
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000886 def load_long(self):
Guido van Rossumfeea0782007-10-10 18:00:50 +0000887 val = self.readline()[:-1].decode("ascii")
888 self.append(int(val, 0))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000889 dispatch[LONG[0]] = load_long
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000890
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000891 def load_long1(self):
892 n = ord(self.read(1))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000893 data = self.read(n)
894 self.append(decode_long(data))
895 dispatch[LONG1[0]] = load_long1
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000896
897 def load_long4(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000898 n = mloads(b'i' + self.read(4))
899 data = self.read(n)
900 self.append(decode_long(data))
901 dispatch[LONG4[0]] = load_long4
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000902
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000903 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000904 self.append(float(self.readline()[:-1]))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000905 dispatch[FLOAT[0]] = load_float
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000906
Guido van Rossumd3703791998-10-22 20:15:36 +0000907 def load_binfloat(self, unpack=struct.unpack):
908 self.append(unpack('>d', self.read(8))[0])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000909 dispatch[BINFLOAT[0]] = load_binfloat
Guido van Rossumd3703791998-10-22 20:15:36 +0000910
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000911 def load_string(self):
Guido van Rossum98297ee2007-11-06 21:34:58 +0000912 orig = self.readline()
913 rep = orig[:-1]
Guido van Rossum26d95c32007-08-27 23:18:54 +0000914 for q in (b'"', b"'"): # double or single quote
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000915 if rep.startswith(q):
916 if not rep.endswith(q):
Guido van Rossum26d95c32007-08-27 23:18:54 +0000917 raise ValueError("insecure string pickle")
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000918 rep = rep[len(q):-len(q)]
919 break
920 else:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000921 raise ValueError("insecure string pickle: %r" % orig)
922 self.append(codecs.escape_decode(rep)[0])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000923 dispatch[STRING[0]] = load_string
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000924
925 def load_binstring(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000926 len = mloads(b'i' + self.read(4))
Guido van Rossum98297ee2007-11-06 21:34:58 +0000927 self.append(self.read(len))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000928 dispatch[BINSTRING[0]] = load_binstring
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000929
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000930 def load_unicode(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000931 self.append(str(self.readline()[:-1], 'raw-unicode-escape'))
932 dispatch[UNICODE[0]] = load_unicode
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000933
934 def load_binunicode(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000935 len = mloads(b'i' + self.read(4))
936 self.append(str(self.read(len), 'utf-8'))
937 dispatch[BINUNICODE[0]] = load_binunicode
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000938
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000939 def load_short_binstring(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000940 len = ord(self.read(1))
Guido van Rossum98297ee2007-11-06 21:34:58 +0000941 self.append(bytes(self.read(len)))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000942 dispatch[SHORT_BINSTRING[0]] = load_short_binstring
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000943
944 def load_tuple(self):
945 k = self.marker()
946 self.stack[k:] = [tuple(self.stack[k+1:])]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000947 dispatch[TUPLE[0]] = load_tuple
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000948
949 def load_empty_tuple(self):
950 self.stack.append(())
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000951 dispatch[EMPTY_TUPLE[0]] = load_empty_tuple
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000952
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000953 def load_tuple1(self):
954 self.stack[-1] = (self.stack[-1],)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000955 dispatch[TUPLE1[0]] = load_tuple1
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000956
957 def load_tuple2(self):
958 self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000959 dispatch[TUPLE2[0]] = load_tuple2
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000960
961 def load_tuple3(self):
962 self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000963 dispatch[TUPLE3[0]] = load_tuple3
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000964
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000965 def load_empty_list(self):
966 self.stack.append([])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000967 dispatch[EMPTY_LIST[0]] = load_empty_list
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000968
969 def load_empty_dictionary(self):
970 self.stack.append({})
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000971 dispatch[EMPTY_DICT[0]] = load_empty_dictionary
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000972
973 def load_list(self):
974 k = self.marker()
975 self.stack[k:] = [self.stack[k+1:]]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000976 dispatch[LIST[0]] = load_list
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000977
978 def load_dict(self):
979 k = self.marker()
980 d = {}
981 items = self.stack[k+1:]
982 for i in range(0, len(items), 2):
983 key = items[i]
984 value = items[i+1]
985 d[key] = value
986 self.stack[k:] = [d]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000987 dispatch[DICT[0]] = load_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000988
Tim Petersd01c1e92003-01-30 15:41:46 +0000989 # INST and OBJ differ only in how they get a class object. It's not
990 # only sensible to do the rest in a common routine, the two routines
991 # previously diverged and grew different bugs.
992 # klass is the class to instantiate, and k points to the topmost mark
993 # object, following which are the arguments for klass.__init__.
994 def _instantiate(self, klass, k):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000995 args = tuple(self.stack[k+1:])
996 del self.stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000997 instantiated = 0
Tim Petersd01c1e92003-01-30 15:41:46 +0000998 if (not args and
Guido van Rossum13257902007-06-07 23:15:56 +0000999 isinstance(klass, type) and
Tim Petersd01c1e92003-01-30 15:41:46 +00001000 not hasattr(klass, "__getinitargs__")):
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001001 value = _EmptyClass()
1002 value.__class__ = klass
1003 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001004 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +00001005 try:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001006 value = klass(*args)
Guido van Rossumb940e112007-01-10 16:19:56 +00001007 except TypeError as err:
Guido van Rossum26d95c32007-08-27 23:18:54 +00001008 raise TypeError("in constructor for %s: %s" %
1009 (klass.__name__, str(err)), sys.exc_info()[2])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001010 self.append(value)
Tim Petersd01c1e92003-01-30 15:41:46 +00001011
1012 def load_inst(self):
1013 module = self.readline()[:-1]
1014 name = self.readline()[:-1]
1015 klass = self.find_class(module, name)
1016 self._instantiate(klass, self.marker())
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001017 dispatch[INST[0]] = load_inst
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001018
1019 def load_obj(self):
Tim Petersd01c1e92003-01-30 15:41:46 +00001020 # Stack is ... markobject classobject arg1 arg2 ...
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001021 k = self.marker()
Tim Petersd01c1e92003-01-30 15:41:46 +00001022 klass = self.stack.pop(k+1)
1023 self._instantiate(klass, k)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001024 dispatch[OBJ[0]] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001025
Guido van Rossum3a41c612003-01-28 15:10:22 +00001026 def load_newobj(self):
1027 args = self.stack.pop()
1028 cls = self.stack[-1]
1029 obj = cls.__new__(cls, *args)
Guido van Rossum533dbcf2003-01-28 17:55:05 +00001030 self.stack[-1] = obj
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001031 dispatch[NEWOBJ[0]] = load_newobj
Guido van Rossum3a41c612003-01-28 15:10:22 +00001032
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001033 def load_global(self):
1034 module = self.readline()[:-1]
1035 name = self.readline()[:-1]
1036 klass = self.find_class(module, name)
1037 self.append(klass)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001038 dispatch[GLOBAL[0]] = load_global
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001039
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001040 def load_ext1(self):
1041 code = ord(self.read(1))
1042 self.get_extension(code)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001043 dispatch[EXT1[0]] = load_ext1
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001044
1045 def load_ext2(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001046 code = mloads(b'i' + self.read(2) + b'\000\000')
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001047 self.get_extension(code)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001048 dispatch[EXT2[0]] = load_ext2
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001049
1050 def load_ext4(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001051 code = mloads(b'i' + self.read(4))
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001052 self.get_extension(code)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001053 dispatch[EXT4[0]] = load_ext4
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001054
1055 def get_extension(self, code):
1056 nil = []
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001057 obj = _extension_cache.get(code, nil)
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001058 if obj is not nil:
1059 self.append(obj)
1060 return
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001061 key = _inverted_registry.get(code)
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001062 if not key:
1063 raise ValueError("unregistered extension code %d" % code)
1064 obj = self.find_class(*key)
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001065 _extension_cache[code] = obj
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001066 self.append(obj)
1067
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001068 def find_class(self, module, name):
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001069 # Subclasses may override this
Guido van Rossum98297ee2007-11-06 21:34:58 +00001070 if isinstance(module, bytes_types):
Guido van Rossumfeea0782007-10-10 18:00:50 +00001071 module = module.decode("utf-8")
Guido van Rossum98297ee2007-11-06 21:34:58 +00001072 if isinstance(name, bytes_types):
Guido van Rossumfeea0782007-10-10 18:00:50 +00001073 name = name.decode("utf-8")
Barry Warsawbf4d9592001-11-15 23:42:58 +00001074 __import__(module)
1075 mod = sys.modules[module]
1076 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001077 return klass
1078
1079 def load_reduce(self):
1080 stack = self.stack
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001081 args = stack.pop()
1082 func = stack[-1]
Guido van Rossum99603b02007-07-20 00:22:32 +00001083 try:
1084 value = func(*args)
1085 except:
1086 print(sys.exc_info())
1087 print(func, args)
1088 raise
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001089 stack[-1] = value
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001090 dispatch[REDUCE[0]] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +00001091
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001092 def load_pop(self):
1093 del self.stack[-1]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001094 dispatch[POP[0]] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +00001095
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001096 def load_pop_mark(self):
1097 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001098 del self.stack[k:]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001099 dispatch[POP_MARK[0]] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001100
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001101 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +00001102 self.append(self.stack[-1])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001103 dispatch[DUP[0]] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +00001104
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001105 def load_get(self):
Guido van Rossum98297ee2007-11-06 21:34:58 +00001106 self.append(self.memo[self.readline()[:-1].decode("ascii")])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001107 dispatch[GET[0]] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +00001108
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001109 def load_binget(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001110 i = ord(self.read(1))
Walter Dörwald70a6b492004-02-12 17:35:32 +00001111 self.append(self.memo[repr(i)])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001112 dispatch[BINGET[0]] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001113
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001114 def load_long_binget(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001115 i = mloads(b'i' + self.read(4))
Walter Dörwald70a6b492004-02-12 17:35:32 +00001116 self.append(self.memo[repr(i)])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001117 dispatch[LONG_BINGET[0]] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001118
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001119 def load_put(self):
Guido van Rossum98297ee2007-11-06 21:34:58 +00001120 self.memo[self.readline()[:-1].decode("ascii")] = self.stack[-1]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001121 dispatch[PUT[0]] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +00001122
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001123 def load_binput(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001124 i = ord(self.read(1))
Walter Dörwald70a6b492004-02-12 17:35:32 +00001125 self.memo[repr(i)] = self.stack[-1]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001126 dispatch[BINPUT[0]] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001127
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001128 def load_long_binput(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001129 i = mloads(b'i' + self.read(4))
Walter Dörwald70a6b492004-02-12 17:35:32 +00001130 self.memo[repr(i)] = self.stack[-1]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001131 dispatch[LONG_BINPUT[0]] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001132
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001133 def load_append(self):
1134 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001135 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001136 list = stack[-1]
1137 list.append(value)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001138 dispatch[APPEND[0]] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +00001139
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001140 def load_appends(self):
1141 stack = self.stack
1142 mark = self.marker()
1143 list = stack[mark - 1]
Tim Peters209ad952003-01-28 01:44:45 +00001144 list.extend(stack[mark + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001145 del stack[mark:]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001146 dispatch[APPENDS[0]] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +00001147
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001148 def load_setitem(self):
1149 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001150 value = stack.pop()
1151 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001152 dict = stack[-1]
1153 dict[key] = value
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001154 dispatch[SETITEM[0]] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001155
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001156 def load_setitems(self):
1157 stack = self.stack
1158 mark = self.marker()
1159 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001160 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001161 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001162
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001163 del stack[mark:]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001164 dispatch[SETITEMS[0]] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001165
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001166 def load_build(self):
1167 stack = self.stack
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001168 state = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001169 inst = stack[-1]
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001170 setstate = getattr(inst, "__setstate__", None)
1171 if setstate:
1172 setstate(state)
1173 return
1174 slotstate = None
1175 if isinstance(state, tuple) and len(state) == 2:
1176 state, slotstate = state
1177 if state:
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001178 inst.__dict__.update(state)
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001179 if slotstate:
1180 for k, v in slotstate.items():
1181 setattr(inst, k, v)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001182 dispatch[BUILD[0]] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001183
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001184 def load_mark(self):
1185 self.append(self.mark)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001186 dispatch[MARK[0]] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001187
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001188 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001189 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001190 raise _Stop(value)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001191 dispatch[STOP[0]] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001192
Guido van Rossume467be61997-12-05 19:42:42 +00001193# Helper class for load_inst/load_obj
1194
1195class _EmptyClass:
1196 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001197
Tim Peters91149822003-01-31 03:43:58 +00001198# Encode/decode longs in linear time.
1199
1200import binascii as _binascii
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001201
1202def encode_long(x):
Tim Peters91149822003-01-31 03:43:58 +00001203 r"""Encode a long to a two's complement little-endian binary string.
Guido van Rossume2a383d2007-01-15 16:59:06 +00001204 Note that 0 is a special case, returning an empty string, to save a
Tim Peters4b23f2b2003-01-31 16:43:39 +00001205 byte in the LONG1 pickling context.
1206
Guido van Rossume2a383d2007-01-15 16:59:06 +00001207 >>> encode_long(0)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001208 b''
Guido van Rossume2a383d2007-01-15 16:59:06 +00001209 >>> encode_long(255)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001210 b'\xff\x00'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001211 >>> encode_long(32767)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001212 b'\xff\x7f'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001213 >>> encode_long(-256)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001214 b'\x00\xff'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001215 >>> encode_long(-32768)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001216 b'\x00\x80'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001217 >>> encode_long(-128)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001218 b'\x80'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001219 >>> encode_long(127)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001220 b'\x7f'
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001221 >>>
1222 """
Tim Peters91149822003-01-31 03:43:58 +00001223
1224 if x == 0:
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001225 return b''
Tim Peters91149822003-01-31 03:43:58 +00001226 if x > 0:
1227 ashex = hex(x)
1228 assert ashex.startswith("0x")
1229 njunkchars = 2 + ashex.endswith('L')
1230 nibbles = len(ashex) - njunkchars
1231 if nibbles & 1:
1232 # need an even # of nibbles for unhexlify
1233 ashex = "0x0" + ashex[2:]
Tim Peters4b23f2b2003-01-31 16:43:39 +00001234 elif int(ashex[2], 16) >= 8:
Tim Peters91149822003-01-31 03:43:58 +00001235 # "looks negative", so need a byte of sign bits
1236 ashex = "0x00" + ashex[2:]
1237 else:
1238 # Build the 256's-complement: (1L << nbytes) + x. The trick is
1239 # to find the number of bytes in linear time (although that should
1240 # really be a constant-time task).
1241 ashex = hex(-x)
1242 assert ashex.startswith("0x")
1243 njunkchars = 2 + ashex.endswith('L')
1244 nibbles = len(ashex) - njunkchars
1245 if nibbles & 1:
Tim Petersee1a53c2003-02-02 02:57:53 +00001246 # Extend to a full byte.
Tim Peters91149822003-01-31 03:43:58 +00001247 nibbles += 1
Tim Peters4b23f2b2003-01-31 16:43:39 +00001248 nbits = nibbles * 4
Guido van Rossume2a383d2007-01-15 16:59:06 +00001249 x += 1 << nbits
Tim Peters91149822003-01-31 03:43:58 +00001250 assert x > 0
1251 ashex = hex(x)
Tim Petersee1a53c2003-02-02 02:57:53 +00001252 njunkchars = 2 + ashex.endswith('L')
1253 newnibbles = len(ashex) - njunkchars
1254 if newnibbles < nibbles:
1255 ashex = "0x" + "0" * (nibbles - newnibbles) + ashex[2:]
1256 if int(ashex[2], 16) < 8:
Tim Peters91149822003-01-31 03:43:58 +00001257 # "looks positive", so need a byte of sign bits
Tim Petersee1a53c2003-02-02 02:57:53 +00001258 ashex = "0xff" + ashex[2:]
Tim Peters91149822003-01-31 03:43:58 +00001259
1260 if ashex.endswith('L'):
1261 ashex = ashex[2:-1]
1262 else:
1263 ashex = ashex[2:]
Tim Petersee1a53c2003-02-02 02:57:53 +00001264 assert len(ashex) & 1 == 0, (x, ashex)
Tim Peters91149822003-01-31 03:43:58 +00001265 binary = _binascii.unhexlify(ashex)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001266 return bytes(binary[::-1])
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001267
1268def decode_long(data):
1269 r"""Decode a long from a two's complement little-endian binary string.
Tim Peters4b23f2b2003-01-31 16:43:39 +00001270
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001271 >>> decode_long(b'')
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001272 0
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001273 >>> decode_long(b"\xff\x00")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001274 255
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001275 >>> decode_long(b"\xff\x7f")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001276 32767
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001277 >>> decode_long(b"\x00\xff")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001278 -256
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001279 >>> decode_long(b"\x00\x80")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001280 -32768
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001281 >>> decode_long(b"\x80")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001282 -128
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001283 >>> decode_long(b"\x7f")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001284 127
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001285 """
Tim Peters91149822003-01-31 03:43:58 +00001286
Tim Peters4b23f2b2003-01-31 16:43:39 +00001287 nbytes = len(data)
1288 if nbytes == 0:
Guido van Rossume2a383d2007-01-15 16:59:06 +00001289 return 0
Tim Peters91149822003-01-31 03:43:58 +00001290 ashex = _binascii.hexlify(data[::-1])
Guido van Rossume2a383d2007-01-15 16:59:06 +00001291 n = int(ashex, 16) # quadratic time before Python 2.3; linear now
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001292 if data[-1] >= 0x80:
Guido van Rossume2a383d2007-01-15 16:59:06 +00001293 n -= 1 << (nbytes * 8)
Tim Peters91149822003-01-31 03:43:58 +00001294 return n
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001295
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001296# Shorthands
1297
Raymond Hettinger3489cad2004-12-05 05:20:42 +00001298def dump(obj, file, protocol=None):
1299 Pickler(file, protocol).dump(obj)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001300
Raymond Hettinger3489cad2004-12-05 05:20:42 +00001301def dumps(obj, protocol=None):
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001302 f = io.BytesIO()
1303 Pickler(f, protocol).dump(obj)
1304 res = f.getvalue()
Guido van Rossum98297ee2007-11-06 21:34:58 +00001305 assert isinstance(res, bytes_types)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001306 return res
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001307
1308def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001309 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001310
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001311def loads(s):
1312 if isinstance(s, str):
1313 raise TypeError("Can't load pickle from unicode string")
1314 file = io.BytesIO(s)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001315 return Unpickler(file).load()
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001316
1317# Doctest
1318
1319def _test():
1320 import doctest
1321 return doctest.testmod()
1322
1323if __name__ == "__main__":
1324 _test()