blob: c158b8da0f630af8ebedd691b8c03c72d6257ecb [file] [log] [blame]
Guido van Rossum54f22ed2000-02-04 15:10:34 +00001"""Create portable serialized representations of Python objects.
Guido van Rossuma48061a1995-01-10 00:31:14 +00002
Guido van Rossume467be61997-12-05 19:42:42 +00003See module cPickle for a (much) faster implementation.
4See module copy_reg for a mechanism for registering custom picklers.
Tim Peters22a449a2003-01-27 20:16:36 +00005See module pickletools source for extensive comments.
Guido van Rossuma48061a1995-01-10 00:31:14 +00006
Guido van Rossume467be61997-12-05 19:42:42 +00007Classes:
Guido van Rossuma48061a1995-01-10 00:31:14 +00008
Guido van Rossume467be61997-12-05 19:42:42 +00009 Pickler
10 Unpickler
Guido van Rossuma48061a1995-01-10 00:31:14 +000011
Guido van Rossume467be61997-12-05 19:42:42 +000012Functions:
Guido van Rossuma48061a1995-01-10 00:31:14 +000013
Guido van Rossume467be61997-12-05 19:42:42 +000014 dump(object, file)
15 dumps(object) -> string
16 load(file) -> object
17 loads(string) -> object
Guido van Rossuma48061a1995-01-10 00:31:14 +000018
Guido van Rossume467be61997-12-05 19:42:42 +000019Misc variables:
Guido van Rossuma48061a1995-01-10 00:31:14 +000020
Fred Drakefe82acc1998-02-13 03:24:48 +000021 __version__
Guido van Rossume467be61997-12-05 19:42:42 +000022 format_version
23 compatible_formats
Guido van Rossuma48061a1995-01-10 00:31:14 +000024
Guido van Rossuma48061a1995-01-10 00:31:14 +000025"""
26
Guido van Rossum743d17e1998-09-15 20:25:57 +000027__version__ = "$Revision$" # Code version
Guido van Rossuma48061a1995-01-10 00:31:14 +000028
Guido van Rossum13257902007-06-07 23:15:56 +000029from types import FunctionType, BuiltinFunctionType
Guido van Rossum443ada42003-02-18 22:49:10 +000030from copy_reg import dispatch_table
Guido van Rossumd4b920c2003-02-04 01:54:49 +000031from copy_reg import _extension_registry, _inverted_registry, _extension_cache
Guido van Rossumd3703791998-10-22 20:15:36 +000032import marshal
33import sys
34import struct
Skip Montanaro23bafc62001-02-18 03:10:09 +000035import re
Guido van Rossum2e6a4b32007-05-04 19:56:22 +000036import io
Walter Dörwald42748a82007-06-12 16:40:17 +000037import codecs
Guido van Rossuma48061a1995-01-10 00:31:14 +000038
Skip Montanaro352674d2001-02-07 23:14:30 +000039__all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler",
40 "Unpickler", "dump", "dumps", "load", "loads"]
41
Tim Petersc0c12b52003-01-29 00:56:17 +000042# These are purely informational; no code uses these.
Guido van Rossumf29d3d62003-01-27 22:47:53 +000043format_version = "2.0" # File format version we write
44compatible_formats = ["1.0", # Original protocol 0
Guido van Rossumbc64e222003-01-28 16:34:19 +000045 "1.1", # Protocol 0 with INST added
Guido van Rossumf29d3d62003-01-27 22:47:53 +000046 "1.2", # Original protocol 1
47 "1.3", # Protocol 1 with BINFLOAT added
48 "2.0", # Protocol 2
49 ] # Old format versions we can read
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000050
Tim Peters8587b3c2003-02-13 15:44:41 +000051# Keep in synch with cPickle. This is the highest protocol number we
52# know how to read.
53HIGHEST_PROTOCOL = 2
54
Guido van Rossum2e6a4b32007-05-04 19:56:22 +000055# The protocol we write by default. May be less than HIGHEST_PROTOCOL.
56DEFAULT_PROTOCOL = 2
57
Guido van Rossume0b90422003-01-28 03:17:21 +000058# Why use struct.pack() for pickling but marshal.loads() for
Tim Petersc0c12b52003-01-29 00:56:17 +000059# unpickling? struct.pack() is 40% faster than marshal.dumps(), but
Guido van Rossume0b90422003-01-28 03:17:21 +000060# marshal.loads() is twice as fast as struct.unpack()!
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000061mloads = marshal.loads
Guido van Rossum0c891ce1995-03-14 15:09:05 +000062
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000063class PickleError(Exception):
Neal Norwitzefbb67b2002-05-30 12:12:04 +000064 """A common base class for the other pickling exceptions."""
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000065 pass
66
67class PicklingError(PickleError):
68 """This exception is raised when an unpicklable object is passed to the
69 dump() method.
70
71 """
72 pass
73
74class UnpicklingError(PickleError):
75 """This exception is raised when there is a problem unpickling an object,
76 such as a security violation.
77
78 Note that other exceptions may also be raised during unpickling, including
79 (but not necessarily limited to) AttributeError, EOFError, ImportError,
80 and IndexError.
81
82 """
83 pass
Guido van Rossum7849da81995-03-09 14:08:35 +000084
Tim Petersc0c12b52003-01-29 00:56:17 +000085# An instance of _Stop is raised by Unpickler.load_stop() in response to
86# the STOP opcode, passing the object that is the result of unpickling.
Guido van Rossumff871742000-12-13 18:11:56 +000087class _Stop(Exception):
88 def __init__(self, value):
89 self.value = value
90
Guido van Rossum533dbcf2003-01-28 17:55:05 +000091# Jython has PyStringMap; it's a dict subclass with string keys
Jeremy Hylton2b9d0291998-05-27 22:38:22 +000092try:
93 from org.python.core import PyStringMap
94except ImportError:
95 PyStringMap = None
96
Tim Peters22a449a2003-01-27 20:16:36 +000097# Pickle opcodes. See pickletools.py for extensive docs. The listing
98# here is in kind-of alphabetical order of 1-character pickle code.
99# pickletools groups them by purpose.
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000100
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000101MARK = b'(' # push special markobject on stack
102STOP = b'.' # every pickle ends with STOP
103POP = b'0' # discard topmost stack item
104POP_MARK = b'1' # discard stack top through topmost markobject
105DUP = b'2' # duplicate top stack item
106FLOAT = b'F' # push float object; decimal string argument
107INT = b'I' # push integer or bool; decimal string argument
108BININT = b'J' # push four-byte signed int
109BININT1 = b'K' # push 1-byte unsigned int
110LONG = b'L' # push long; decimal string argument
111BININT2 = b'M' # push 2-byte unsigned int
112NONE = b'N' # push None
113PERSID = b'P' # push persistent object; id is taken from string arg
114BINPERSID = b'Q' # " " " ; " " " " stack
115REDUCE = b'R' # apply callable to argtuple, both on stack
116STRING = b'S' # push string; NL-terminated string argument
117BINSTRING = b'T' # push string; counted binary string argument
118SHORT_BINSTRING= b'U' # " " ; " " " " < 256 bytes
119UNICODE = b'V' # push Unicode string; raw-unicode-escaped'd argument
120BINUNICODE = b'X' # " " " ; counted UTF-8 string argument
121APPEND = b'a' # append stack top to list below it
122BUILD = b'b' # call __setstate__ or __dict__.update()
123GLOBAL = b'c' # push self.find_class(modname, name); 2 string args
124DICT = b'd' # build a dict from stack items
125EMPTY_DICT = b'}' # push empty dict
126APPENDS = b'e' # extend list on stack by topmost stack slice
127GET = b'g' # push item from memo on stack; index is string arg
128BINGET = b'h' # " " " " " " ; " " 1-byte arg
129INST = b'i' # build & push class instance
130LONG_BINGET = b'j' # push item from memo on stack; index is 4-byte arg
131LIST = b'l' # build list from topmost stack items
132EMPTY_LIST = b']' # push empty list
133OBJ = b'o' # build & push class instance
134PUT = b'p' # store stack top in memo; index is string arg
135BINPUT = b'q' # " " " " " ; " " 1-byte arg
136LONG_BINPUT = b'r' # " " " " " ; " " 4-byte arg
137SETITEM = b's' # add key+value pair to dict
138TUPLE = b't' # build tuple from topmost stack items
139EMPTY_TUPLE = b')' # push empty tuple
140SETITEMS = b'u' # modify dict by adding topmost key+value pairs
141BINFLOAT = b'G' # push float; arg is 8-byte float encoding
Tim Peters22a449a2003-01-27 20:16:36 +0000142
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000143TRUE = b'I01\n' # not an opcode; see INT docs in pickletools.py
144FALSE = b'I00\n' # not an opcode; see INT docs in pickletools.py
Guido van Rossum77f6a652002-04-03 22:41:51 +0000145
Guido van Rossum586c9e82003-01-29 06:16:12 +0000146# Protocol 2
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000147
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000148PROTO = b'\x80' # identify pickle protocol
149NEWOBJ = b'\x81' # build object by applying cls.__new__ to argtuple
150EXT1 = b'\x82' # push object from extension registry; 1-byte index
151EXT2 = b'\x83' # ditto, but 2-byte index
152EXT4 = b'\x84' # ditto, but 4-byte index
153TUPLE1 = b'\x85' # build 1-tuple from stack top
154TUPLE2 = b'\x86' # build 2-tuple from two topmost stack items
155TUPLE3 = b'\x87' # build 3-tuple from three topmost stack items
156NEWTRUE = b'\x88' # push True
157NEWFALSE = b'\x89' # push False
158LONG1 = b'\x8a' # push long from < 256 bytes
159LONG4 = b'\x8b' # push really big long
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000160
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000161_tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3]
162
Guido van Rossuma48061a1995-01-10 00:31:14 +0000163
Skip Montanaro23bafc62001-02-18 03:10:09 +0000164__all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
165
Guido van Rossum1be31752003-01-28 15:19:53 +0000166
167# Pickling machinery
168
Guido van Rossuma48061a1995-01-10 00:31:14 +0000169class Pickler:
170
Raymond Hettinger3489cad2004-12-05 05:20:42 +0000171 def __init__(self, file, protocol=None):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000172 """This takes a binary file for writing a pickle data stream.
173
174 All protocols now read and write bytes.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000175
Guido van Rossumcf117b02003-02-09 17:19:41 +0000176 The optional protocol argument tells the pickler to use the
177 given protocol; supported protocols are 0, 1, 2. The default
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000178 protocol is 2; it's been supported for many years now.
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000179
180 Protocol 1 is more efficient than protocol 0; protocol 2 is
Guido van Rossum7eff63a2003-01-31 19:42:31 +0000181 more efficient than protocol 1.
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000182
Guido van Rossum7eff63a2003-01-31 19:42:31 +0000183 Specifying a negative protocol version selects the highest
Tim Peters5bd2a792003-02-01 16:45:06 +0000184 protocol version supported. The higher the protocol used, the
185 more recent the version of Python needed to read the pickle
186 produced.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000187
188 The file parameter must have a write() method that accepts a single
189 string argument. It can thus be an open file object, a StringIO
190 object, or any other custom object that meets this interface.
191
192 """
Guido van Rossumcf117b02003-02-09 17:19:41 +0000193 if protocol is None:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000194 protocol = DEFAULT_PROTOCOL
Guido van Rossumcf117b02003-02-09 17:19:41 +0000195 if protocol < 0:
Tim Peters8587b3c2003-02-13 15:44:41 +0000196 protocol = HIGHEST_PROTOCOL
197 elif not 0 <= protocol <= HIGHEST_PROTOCOL:
198 raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000199 self.write = file.write
200 self.memo = {}
Guido van Rossumcf117b02003-02-09 17:19:41 +0000201 self.proto = int(protocol)
202 self.bin = protocol >= 1
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000203 self.fast = 0
Guido van Rossuma48061a1995-01-10 00:31:14 +0000204
Fred Drake7f781c92002-05-01 20:33:53 +0000205 def clear_memo(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000206 """Clears the pickler's "memo".
207
208 The memo is the data structure that remembers which objects the
Tim Petersb377f8a2003-01-28 00:23:36 +0000209 pickler has already seen, so that shared or recursive objects are
210 pickled by reference and not by value. This method is useful when
211 re-using picklers.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000212
213 """
Fred Drake7f781c92002-05-01 20:33:53 +0000214 self.memo.clear()
215
Guido van Rossum3a41c612003-01-28 15:10:22 +0000216 def dump(self, obj):
Tim Peters5bd2a792003-02-01 16:45:06 +0000217 """Write a pickled representation of obj to the open file."""
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000218 if self.proto >= 2:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000219 self.write(PROTO + bytes([self.proto]))
Guido van Rossum3a41c612003-01-28 15:10:22 +0000220 self.save(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000221 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000222
Jeremy Hylton3422c992003-01-24 19:29:52 +0000223 def memoize(self, obj):
224 """Store an object in the memo."""
225
Tim Peterse46b73f2003-01-27 21:22:10 +0000226 # The Pickler memo is a dictionary mapping object ids to 2-tuples
227 # that contain the Unpickler memo key and the object being memoized.
228 # The memo key is written to the pickle and will become
Jeremy Hylton3422c992003-01-24 19:29:52 +0000229 # the key in the Unpickler's memo. The object is stored in the
Tim Peterse46b73f2003-01-27 21:22:10 +0000230 # Pickler memo so that transient objects are kept alive during
231 # pickling.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000232
Tim Peterse46b73f2003-01-27 21:22:10 +0000233 # The use of the Unpickler memo length as the memo key is just a
234 # convention. The only requirement is that the memo values be unique.
235 # But there appears no advantage to any other scheme, and this
Tim Peterscbd0a322003-01-28 00:24:43 +0000236 # scheme allows the Unpickler memo to be implemented as a plain (but
Tim Peterse46b73f2003-01-27 21:22:10 +0000237 # growable) array, indexed by memo key.
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000238 if self.fast:
239 return
Guido van Rossum9b40e802003-01-30 06:37:41 +0000240 assert id(obj) not in self.memo
Jeremy Hylton3422c992003-01-24 19:29:52 +0000241 memo_len = len(self.memo)
242 self.write(self.put(memo_len))
Tim Peters518df0d2003-01-28 01:00:38 +0000243 self.memo[id(obj)] = memo_len, obj
Jeremy Hylton3422c992003-01-24 19:29:52 +0000244
Tim Petersbb38e302003-01-27 21:25:41 +0000245 # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000246 def put(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000247 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000248 if i < 256:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000249 return BINPUT + bytes([i])
Guido van Rossum5c938d02003-01-28 03:03:08 +0000250 else:
251 return LONG_BINPUT + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000252
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000253 return PUT + bytes(repr(i)) + b'\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000254
Tim Petersbb38e302003-01-27 21:25:41 +0000255 # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000256 def get(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000257 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000258 if i < 256:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000259 return BINGET + bytes([i])
Guido van Rossum5c938d02003-01-28 03:03:08 +0000260 else:
261 return LONG_BINGET + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000262
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000263 return GET + bytes(repr(i)) + b'\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000264
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000265 def save(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000266 # Check for persistent id (defined by a subclass)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000267 pid = self.persistent_id(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000268 if pid:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000269 self.save_pers(pid)
270 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000271
Guido van Rossumbc64e222003-01-28 16:34:19 +0000272 # Check the memo
273 x = self.memo.get(id(obj))
274 if x:
275 self.write(self.get(x[0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000276 return
277
Guido van Rossumbc64e222003-01-28 16:34:19 +0000278 # Check the type dispatch table
Guido van Rossum3a41c612003-01-28 15:10:22 +0000279 t = type(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000280 f = self.dispatch.get(t)
281 if f:
282 f(self, obj) # Call unbound method with explicit self
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000283 return
284
Guido van Rossumbc64e222003-01-28 16:34:19 +0000285 # Check for a class with a custom metaclass; treat as regular class
Tim Petersb32a8312003-01-28 00:48:09 +0000286 try:
Guido van Rossum13257902007-06-07 23:15:56 +0000287 issc = issubclass(t, type)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000288 except TypeError: # t is not a class (old Boost; see SF #502085)
Tim Petersb32a8312003-01-28 00:48:09 +0000289 issc = 0
290 if issc:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000291 self.save_global(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000292 return
293
Guido van Rossumbc64e222003-01-28 16:34:19 +0000294 # Check copy_reg.dispatch_table
295 reduce = dispatch_table.get(t)
Guido van Rossumc53f0092003-02-18 22:05:12 +0000296 if reduce:
297 rv = reduce(obj)
298 else:
299 # Check for a __reduce_ex__ method, fall back to __reduce__
300 reduce = getattr(obj, "__reduce_ex__", None)
301 if reduce:
302 rv = reduce(self.proto)
303 else:
304 reduce = getattr(obj, "__reduce__", None)
305 if reduce:
306 rv = reduce()
307 else:
308 raise PicklingError("Can't pickle %r object: %r" %
309 (t.__name__, obj))
Tim Petersb32a8312003-01-28 00:48:09 +0000310
Guido van Rossumbc64e222003-01-28 16:34:19 +0000311 # Check for string returned by reduce(), meaning "save as global"
Guido van Rossum1255ed62007-05-04 20:30:19 +0000312 if isinstance(rv, basestring):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000313 self.save_global(obj, rv)
Tim Petersb32a8312003-01-28 00:48:09 +0000314 return
315
Guido van Rossumbc64e222003-01-28 16:34:19 +0000316 # Assert that reduce() returned a tuple
Guido van Rossum13257902007-06-07 23:15:56 +0000317 if not isinstance(rv, tuple):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000318 raise PicklingError("%s must return string or tuple" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000319
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000320 # Assert that it returned an appropriately sized tuple
Guido van Rossumbc64e222003-01-28 16:34:19 +0000321 l = len(rv)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000322 if not (2 <= l <= 5):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000323 raise PicklingError("Tuple returned by %s must have "
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000324 "two to five elements" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000325
Guido van Rossumbc64e222003-01-28 16:34:19 +0000326 # Save the reduce() output and finally memoize the object
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000327 self.save_reduce(obj=obj, *rv)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000328
Guido van Rossum3a41c612003-01-28 15:10:22 +0000329 def persistent_id(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000330 # This exists so a subclass can override it
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000331 return None
332
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000333 def save_pers(self, pid):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000334 # Save a persistent id reference
Tim Petersbd1cdb92003-01-28 01:03:10 +0000335 if self.bin:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000336 self.save(pid)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000337 self.write(BINPERSID)
Tim Petersbd1cdb92003-01-28 01:03:10 +0000338 else:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000339 self.write(PERSID + bytes(str(pid)) + b'\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000340
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000341 def save_reduce(self, func, args, state=None,
342 listitems=None, dictitems=None, obj=None):
Jeremy Hyltone3a565e2003-06-29 16:59:59 +0000343 # This API is called by some subclasses
Guido van Rossumbc64e222003-01-28 16:34:19 +0000344
345 # Assert that args is a tuple or None
Guido van Rossum13257902007-06-07 23:15:56 +0000346 if not isinstance(args, tuple):
Raymond Hettingera6b45cc2004-12-07 07:05:57 +0000347 raise PicklingError("args from reduce() should be a tuple")
Guido van Rossumbc64e222003-01-28 16:34:19 +0000348
349 # Assert that func is callable
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000350 if not hasattr(func, '__call__'):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000351 raise PicklingError("func from reduce should be callable")
352
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000353 save = self.save
Guido van Rossumbc64e222003-01-28 16:34:19 +0000354 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000355
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000356 # Protocol 2 special case: if func's name is __newobj__, use NEWOBJ
357 if self.proto >= 2 and getattr(func, "__name__", "") == "__newobj__":
358 # A __reduce__ implementation can direct protocol 2 to
359 # use the more efficient NEWOBJ opcode, while still
360 # allowing protocol 0 and 1 to work normally. For this to
361 # work, the function returned by __reduce__ should be
362 # called __newobj__, and its first argument should be a
363 # new-style class. The implementation for __newobj__
364 # should be as follows, although pickle has no way to
365 # verify this:
366 #
367 # def __newobj__(cls, *args):
368 # return cls.__new__(cls, *args)
369 #
370 # Protocols 0 and 1 will pickle a reference to __newobj__,
371 # while protocol 2 (and above) will pickle a reference to
372 # cls, the remaining args tuple, and the NEWOBJ code,
373 # which calls cls.__new__(cls, *args) at unpickling time
374 # (see load_newobj below). If __reduce__ returns a
375 # three-tuple, the state from the third tuple item will be
376 # pickled regardless of the protocol, calling __setstate__
377 # at unpickling time (see load_build below).
378 #
379 # Note that no standard __newobj__ implementation exists;
380 # you have to provide your own. This is to enforce
381 # compatibility with Python 2.2 (pickles written using
382 # protocol 0 or 1 in Python 2.3 should be unpicklable by
383 # Python 2.2).
384 cls = args[0]
385 if not hasattr(cls, "__new__"):
386 raise PicklingError(
387 "args[0] from __newobj__ args has no __new__")
Guido van Rossumf7f45172003-01-31 17:17:49 +0000388 if obj is not None and cls is not obj.__class__:
389 raise PicklingError(
390 "args[0] from __newobj__ args has the wrong class")
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000391 args = args[1:]
392 save(cls)
393 save(args)
394 write(NEWOBJ)
395 else:
396 save(func)
397 save(args)
398 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000399
Guido van Rossumf7f45172003-01-31 17:17:49 +0000400 if obj is not None:
401 self.memoize(obj)
402
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000403 # More new special cases (that work with older protocols as
404 # well): when __reduce__ returns a tuple with 4 or 5 items,
405 # the 4th and 5th item should be iterators that provide list
406 # items and dict items (as (key, value) tuples), or None.
407
408 if listitems is not None:
409 self._batch_appends(listitems)
410
411 if dictitems is not None:
412 self._batch_setitems(dictitems)
413
Tim Petersc32d8242001-04-10 02:48:53 +0000414 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000415 save(state)
416 write(BUILD)
417
Guido van Rossumbc64e222003-01-28 16:34:19 +0000418 # Methods below this point are dispatched through the dispatch table
419
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000420 dispatch = {}
421
Guido van Rossum3a41c612003-01-28 15:10:22 +0000422 def save_none(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000423 self.write(NONE)
Guido van Rossum13257902007-06-07 23:15:56 +0000424 dispatch[type(None)] = save_none
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000425
Guido van Rossum3a41c612003-01-28 15:10:22 +0000426 def save_bool(self, obj):
Guido van Rossum7d97d312003-01-28 04:25:27 +0000427 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000428 self.write(obj and NEWTRUE or NEWFALSE)
Guido van Rossum7d97d312003-01-28 04:25:27 +0000429 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000430 self.write(obj and TRUE or FALSE)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000431 dispatch[bool] = save_bool
432
Guido van Rossum3a41c612003-01-28 15:10:22 +0000433 def save_int(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000434 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000435 # If the int is small enough to fit in a signed 4-byte 2's-comp
436 # format, we can store it more efficiently than the general
437 # case.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000438 # First one- and two-byte unsigned ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000439 if obj >= 0:
440 if obj <= 0xff:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000441 self.write(BININT1 + bytes([obj]))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000442 return
Guido van Rossum3a41c612003-01-28 15:10:22 +0000443 if obj <= 0xffff:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000444 self.write(BININT2 + bytes([obj&0xff, obj>>8]))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000445 return
446 # Next check for 4-byte signed ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000447 high_bits = obj >> 31 # note that Python shift sign-extends
Tim Petersd95c2df2003-01-28 03:41:54 +0000448 if high_bits == 0 or high_bits == -1:
Tim Peters44714002001-04-10 05:02:52 +0000449 # All high bits are copies of bit 2**31, so the value
450 # fits in a 4-byte signed int.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000451 self.write(BININT + pack("<i", obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000452 return
Tim Peters44714002001-04-10 05:02:52 +0000453 # Text pickle, or int too big to fit in signed 4-byte format.
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000454 self.write(INT + bytes(repr(obj)) + b'\n')
Guido van Rossumddefaf32007-01-14 03:31:43 +0000455 # XXX save_int is merged into save_long
Guido van Rossum13257902007-06-07 23:15:56 +0000456 # dispatch[int] = save_int
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000457
Guido van Rossum3a41c612003-01-28 15:10:22 +0000458 def save_long(self, obj, pack=struct.pack):
Guido van Rossumddefaf32007-01-14 03:31:43 +0000459 if self.bin:
460 # If the int is small enough to fit in a signed 4-byte 2's-comp
461 # format, we can store it more efficiently than the general
462 # case.
463 # First one- and two-byte unsigned ints:
464 if obj >= 0:
465 if obj <= 0xff:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000466 self.write(BININT1 + bytes([obj]))
Guido van Rossumddefaf32007-01-14 03:31:43 +0000467 return
468 if obj <= 0xffff:
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000469 self.write(BININT2 + bytes([obj&0xff, obj>>8]))
Guido van Rossumddefaf32007-01-14 03:31:43 +0000470 return
471 # Next check for 4-byte signed ints:
472 high_bits = obj >> 31 # note that Python shift sign-extends
473 if high_bits == 0 or high_bits == -1:
474 # All high bits are copies of bit 2**31, so the value
475 # fits in a 4-byte signed int.
476 self.write(BININT + pack("<i", obj))
477 return
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000478 if self.proto >= 2:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000479 encoded = encode_long(obj)
480 n = len(encoded)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000481 if n < 256:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000482 self.write(LONG1 + bytes([n]) + encoded)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000483 else:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000484 self.write(LONG4 + pack("<i", n) + encoded)
Tim Petersee1a53c2003-02-02 02:57:53 +0000485 return
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000486 self.write(LONG + bytes(repr(obj)) + b'\n')
Guido van Rossum13257902007-06-07 23:15:56 +0000487 dispatch[int] = save_long
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000488
Guido van Rossum3a41c612003-01-28 15:10:22 +0000489 def save_float(self, obj, pack=struct.pack):
Guido van Rossumd3703791998-10-22 20:15:36 +0000490 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000491 self.write(BINFLOAT + pack('>d', obj))
Guido van Rossumd3703791998-10-22 20:15:36 +0000492 else:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000493 self.write(FLOAT + bytes(repr(obj)) + b'\n')
Guido van Rossum13257902007-06-07 23:15:56 +0000494 dispatch[float] = save_float
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000495
Guido van Rossum3a41c612003-01-28 15:10:22 +0000496 def save_string(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000497 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000498 n = len(obj)
Tim Petersbbf63cd2003-01-27 21:15:36 +0000499 if n < 256:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000500 self.write(SHORT_BINSTRING + bytes([n]) + bytes(obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000501 else:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000502 self.write(BINSTRING + pack("<i", n) + bytes(obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000503 else:
Guido van Rossumaa588c42007-06-15 03:35:38 +0000504 # Strip leading 's' due to repr() of str8() returning s'...'
505 self.write(STRING + bytes(repr(obj).lstrip("s")) + b'\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000506 self.memoize(obj)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000507 dispatch[str8] = save_string
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000508
Martin v. Löwis10a60b32007-07-18 02:28:27 +0000509 def save_bytes(self, obj):
510 # Like save_string
511 if self.bin:
512 n = len(obj)
513 if n < 256:
514 self.write(SHORT_BINSTRING + bytes([n]) + bytes(obj))
515 else:
516 self.write(BINSTRING + pack("<i", n) + bytes(obj))
517 else:
518 # Strip leading 'b'
519 self.write(STRING + bytes(repr(obj).lstrip("b")) + b'\n')
520 self.memoize(obj)
521 dispatch[bytes] = save_bytes
522
Guido van Rossum3a41c612003-01-28 15:10:22 +0000523 def save_unicode(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000524 if self.bin:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000525 encoded = obj.encode('utf-8')
526 n = len(encoded)
527 self.write(BINUNICODE + pack("<i", n) + encoded)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000528 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000529 obj = obj.replace("\\", "\\u005c")
530 obj = obj.replace("\n", "\\u000a")
Guido van Rossum1255ed62007-05-04 20:30:19 +0000531 self.write(UNICODE + bytes(obj.encode('raw-unicode-escape')) +
532 b'\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000533 self.memoize(obj)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000534 dispatch[str] = save_unicode
Tim Peters658cba62001-02-09 20:06:00 +0000535
Guido van Rossum3a41c612003-01-28 15:10:22 +0000536 def save_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000537 write = self.write
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000538 proto = self.proto
539
Guido van Rossum3a41c612003-01-28 15:10:22 +0000540 n = len(obj)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000541 if n == 0:
542 if proto:
543 write(EMPTY_TUPLE)
544 else:
545 write(MARK + TUPLE)
Tim Petersd97da802003-01-28 05:48:29 +0000546 return
547
548 save = self.save
549 memo = self.memo
550 if n <= 3 and proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000551 for element in obj:
Tim Petersd97da802003-01-28 05:48:29 +0000552 save(element)
553 # Subtle. Same as in the big comment below.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000554 if id(obj) in memo:
555 get = self.get(memo[id(obj)][0])
Tim Petersd97da802003-01-28 05:48:29 +0000556 write(POP * n + get)
557 else:
558 write(_tuplesize2code[n])
Guido van Rossum3a41c612003-01-28 15:10:22 +0000559 self.memoize(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000560 return
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000561
Tim Peters1d63c9f2003-02-02 20:29:39 +0000562 # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple
Tim Petersff57bff2003-01-28 05:34:53 +0000563 # has more than 3 elements.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000564 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000565 for element in obj:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000566 save(element)
567
Tim Peters1d63c9f2003-02-02 20:29:39 +0000568 if id(obj) in memo:
Tim Petersf558da02003-01-28 02:09:55 +0000569 # Subtle. d was not in memo when we entered save_tuple(), so
570 # the process of saving the tuple's elements must have saved
571 # the tuple itself: the tuple is recursive. The proper action
572 # now is to throw away everything we put on the stack, and
573 # simply GET the tuple (it's already constructed). This check
574 # could have been done in the "for element" loop instead, but
575 # recursive tuples are a rare thing.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000576 get = self.get(memo[id(obj)][0])
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000577 if proto:
Tim Petersf558da02003-01-28 02:09:55 +0000578 write(POP_MARK + get)
579 else: # proto 0 -- POP_MARK not available
Tim Petersd97da802003-01-28 05:48:29 +0000580 write(POP * (n+1) + get)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000581 return
582
Tim Peters1d63c9f2003-02-02 20:29:39 +0000583 # No recursion.
Tim Peters518df0d2003-01-28 01:00:38 +0000584 self.write(TUPLE)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000585 self.memoize(obj)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000586
Guido van Rossum13257902007-06-07 23:15:56 +0000587 dispatch[tuple] = save_tuple
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000588
Tim Petersa6ae9a22003-01-28 16:58:41 +0000589 # save_empty_tuple() isn't used by anything in Python 2.3. However, I
590 # found a Pickler subclass in Zope3 that calls it, so it's not harmless
591 # to remove it.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000592 def save_empty_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000593 self.write(EMPTY_TUPLE)
594
Guido van Rossum3a41c612003-01-28 15:10:22 +0000595 def save_list(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000596 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000597
Tim Petersc32d8242001-04-10 02:48:53 +0000598 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000599 write(EMPTY_LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000600 else: # proto 0 -- can't use EMPTY_LIST
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000601 write(MARK + LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000602
603 self.memoize(obj)
604 self._batch_appends(iter(obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000605
Guido van Rossum13257902007-06-07 23:15:56 +0000606 dispatch[list] = save_list
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000607
Tim Peters42f08ac2003-02-11 22:43:24 +0000608 # Keep in synch with cPickle's BATCHSIZE. Nothing will break if it gets
609 # out of synch, though.
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000610 _BATCHSIZE = 1000
611
612 def _batch_appends(self, items):
613 # Helper to batch up APPENDS sequences
614 save = self.save
615 write = self.write
616
617 if not self.bin:
618 for x in items:
619 save(x)
620 write(APPEND)
621 return
622
Guido van Rossum805365e2007-05-07 22:24:25 +0000623 r = range(self._BATCHSIZE)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000624 while items is not None:
625 tmp = []
626 for i in r:
627 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000628 x = next(items)
Guido van Rossum5aac4e62003-02-06 22:57:00 +0000629 tmp.append(x)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000630 except StopIteration:
631 items = None
632 break
633 n = len(tmp)
634 if n > 1:
635 write(MARK)
636 for x in tmp:
637 save(x)
638 write(APPENDS)
639 elif n:
640 save(tmp[0])
641 write(APPEND)
642 # else tmp is empty, and we're done
643
Guido van Rossum3a41c612003-01-28 15:10:22 +0000644 def save_dict(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000645 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000646
Tim Petersc32d8242001-04-10 02:48:53 +0000647 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000648 write(EMPTY_DICT)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000649 else: # proto 0 -- can't use EMPTY_DICT
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000650 write(MARK + DICT)
651
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000652 self.memoize(obj)
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000653 self._batch_setitems(iter(obj.items()))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000654
Guido van Rossum13257902007-06-07 23:15:56 +0000655 dispatch[dict] = save_dict
656 if PyStringMap is not None:
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000657 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000658
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000659 def _batch_setitems(self, items):
660 # Helper to batch up SETITEMS sequences; proto >= 1 only
661 save = self.save
662 write = self.write
663
664 if not self.bin:
665 for k, v in items:
666 save(k)
667 save(v)
668 write(SETITEM)
669 return
670
Guido van Rossum805365e2007-05-07 22:24:25 +0000671 r = range(self._BATCHSIZE)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000672 while items is not None:
673 tmp = []
674 for i in r:
675 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000676 tmp.append(next(items))
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000677 except StopIteration:
678 items = None
679 break
680 n = len(tmp)
681 if n > 1:
682 write(MARK)
683 for k, v in tmp:
684 save(k)
685 save(v)
686 write(SETITEMS)
687 elif n:
688 k, v = tmp[0]
689 save(k)
690 save(v)
691 write(SETITEM)
692 # else tmp is empty, and we're done
693
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000694 def save_global(self, obj, name=None, pack=struct.pack):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000695 write = self.write
696 memo = self.memo
697
Tim Petersc32d8242001-04-10 02:48:53 +0000698 if name is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000699 name = obj.__name__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000700
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000701 module = getattr(obj, "__module__", None)
702 if module is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000703 module = whichmodule(obj, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000704
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000705 try:
706 __import__(module)
707 mod = sys.modules[module]
708 klass = getattr(mod, name)
709 except (ImportError, KeyError, AttributeError):
710 raise PicklingError(
711 "Can't pickle %r: it's not found as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000712 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000713 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000714 if klass is not obj:
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000715 raise PicklingError(
716 "Can't pickle %r: it's not the same object as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000717 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000718
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000719 if self.proto >= 2:
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000720 code = _extension_registry.get((module, name))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000721 if code:
722 assert code > 0
723 if code <= 0xff:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000724 write(EXT1 + bytes([code]))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000725 elif code <= 0xffff:
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000726 write(EXT2 + bytes([code&0xff, code>>8]))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000727 else:
728 write(EXT4 + pack("<i", code))
729 return
730
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000731 write(GLOBAL + bytes(module) + b'\n' + bytes(name) + b'\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000732 self.memoize(obj)
Tim Peters3b769832003-01-28 03:51:36 +0000733
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000734 dispatch[FunctionType] = save_global
735 dispatch[BuiltinFunctionType] = save_global
Guido van Rossum13257902007-06-07 23:15:56 +0000736 dispatch[type] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000737
Guido van Rossum1be31752003-01-28 15:19:53 +0000738# Pickling helpers
Guido van Rossuma48061a1995-01-10 00:31:14 +0000739
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000740def _keep_alive(x, memo):
741 """Keeps a reference to the object x in the memo.
742
743 Because we remember objects by their id, we have
744 to assure that possibly temporary objects are kept
745 alive by referencing them.
746 We store a reference at the id of the memo, which should
747 normally not be used unless someone tries to deepcopy
748 the memo itself...
749 """
750 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000751 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000752 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000753 # aha, this is the first one :-)
754 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000755
756
Tim Petersc0c12b52003-01-29 00:56:17 +0000757# A cache for whichmodule(), mapping a function object to the name of
758# the module in which the function was found.
759
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000760classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000761
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000762def whichmodule(func, funcname):
763 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000764
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000765 Search sys.modules for the module.
766 Cache in classmap.
767 Return a module name.
Tim Petersc0c12b52003-01-29 00:56:17 +0000768 If the function cannot be found, return "__main__".
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000769 """
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000770 # Python functions should always get an __module__ from their globals.
771 mod = getattr(func, "__module__", None)
772 if mod is not None:
773 return mod
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000774 if func in classmap:
775 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000776
Guido van Rossum634e53f2007-02-26 07:07:02 +0000777 for name, module in list(sys.modules.items()):
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000778 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000779 continue # skip dummy package entries
Jeremy Hyltoncc1fccb2003-02-06 16:23:01 +0000780 if name != '__main__' and getattr(module, funcname, None) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000781 break
782 else:
783 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000784 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000785 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000786
787
Guido van Rossum1be31752003-01-28 15:19:53 +0000788# Unpickling machinery
789
Guido van Rossuma48061a1995-01-10 00:31:14 +0000790class Unpickler:
791
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000792 def __init__(self, file):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000793 """This takes a binary file for reading a pickle data stream.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000794
Tim Peters5bd2a792003-02-01 16:45:06 +0000795 The protocol version of the pickle is detected automatically, so no
796 proto argument is needed.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000797
798 The file-like object must have two methods, a read() method that
799 takes an integer argument, and a readline() method that requires no
800 arguments. Both methods should return a string. Thus file-like
801 object can be a file object opened for reading, a StringIO object,
802 or any other custom object that meets this interface.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000803 """
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000804 try:
805 self.readline = file.readline
806 except AttributeError:
807 self.file = file
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000808 self.read = file.read
809 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000810
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000811 def readline(self):
812 # XXX Slow but at least correct
813 b = bytes()
814 while True:
815 c = self.file.read(1)
816 if not c:
817 break
818 b += c
819 if c == b'\n':
820 break
821 return b
822
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000823 def load(self):
Guido van Rossum3a41c612003-01-28 15:10:22 +0000824 """Read a pickled object representation from the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000825
Guido van Rossum3a41c612003-01-28 15:10:22 +0000826 Return the reconstituted object hierarchy specified in the file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000827 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000828 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000829 self.stack = []
830 self.append = self.stack.append
831 read = self.read
832 dispatch = self.dispatch
833 try:
834 while 1:
835 key = read(1)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000836 if not key:
837 raise EOFError
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000838 assert isinstance(key, bytes)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000839 dispatch[key[0]](self)
Guido van Rossumb940e112007-01-10 16:19:56 +0000840 except _Stop as stopinst:
Guido van Rossumff871742000-12-13 18:11:56 +0000841 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000842
Tim Petersc23d18a2003-01-28 01:41:51 +0000843 # Return largest index k such that self.stack[k] is self.mark.
844 # If the stack doesn't contain a mark, eventually raises IndexError.
845 # This could be sped by maintaining another stack, of indices at which
846 # the mark appears. For that matter, the latter stack would suffice,
847 # and we wouldn't need to push mark objects on self.stack at all.
848 # Doing so is probably a good thing, though, since if the pickle is
849 # corrupt (or hostile) we may get a clue from finding self.mark embedded
850 # in unpickled objects.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000851 def marker(self):
852 stack = self.stack
853 mark = self.mark
854 k = len(stack)-1
855 while stack[k] is not mark: k = k-1
856 return k
857
858 dispatch = {}
859
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000860 def load_proto(self):
861 proto = ord(self.read(1))
862 if not 0 <= proto <= 2:
863 raise ValueError, "unsupported pickle protocol: %d" % proto
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000864 dispatch[PROTO[0]] = load_proto
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000865
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000866 def load_persid(self):
867 pid = self.readline()[:-1]
868 self.append(self.persistent_load(pid))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000869 dispatch[PERSID[0]] = load_persid
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000870
871 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000872 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000873 self.append(self.persistent_load(pid))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000874 dispatch[BINPERSID[0]] = load_binpersid
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000875
876 def load_none(self):
877 self.append(None)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000878 dispatch[NONE[0]] = load_none
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000879
Guido van Rossum7d97d312003-01-28 04:25:27 +0000880 def load_false(self):
881 self.append(False)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000882 dispatch[NEWFALSE[0]] = load_false
Guido van Rossum7d97d312003-01-28 04:25:27 +0000883
884 def load_true(self):
885 self.append(True)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000886 dispatch[NEWTRUE[0]] = load_true
Guido van Rossum7d97d312003-01-28 04:25:27 +0000887
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000888 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000889 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000890 if data == FALSE[1:]:
891 val = False
892 elif data == TRUE[1:]:
893 val = True
894 else:
895 try:
896 val = int(data)
897 except ValueError:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000898 val = int(data)
Guido van Rossume2763392002-04-05 19:30:08 +0000899 self.append(val)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000900 dispatch[INT[0]] = load_int
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000901
902 def load_binint(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000903 self.append(mloads(b'i' + self.read(4)))
904 dispatch[BININT[0]] = load_binint
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000905
906 def load_binint1(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000907 self.append(ord(self.read(1)))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000908 dispatch[BININT1[0]] = load_binint1
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000909
910 def load_binint2(self):
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000911 self.append(mloads(b'i' + self.read(2) + b'\000\000'))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000912 dispatch[BININT2[0]] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000913
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000914 def load_long(self):
Guido van Rossum1255ed62007-05-04 20:30:19 +0000915 self.append(int(str(self.readline()[:-1]), 0))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000916 dispatch[LONG[0]] = load_long
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000917
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000918 def load_long1(self):
919 n = ord(self.read(1))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000920 data = self.read(n)
921 self.append(decode_long(data))
922 dispatch[LONG1[0]] = load_long1
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000923
924 def load_long4(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000925 n = mloads(b'i' + self.read(4))
926 data = self.read(n)
927 self.append(decode_long(data))
928 dispatch[LONG4[0]] = load_long4
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000929
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000930 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000931 self.append(float(self.readline()[:-1]))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000932 dispatch[FLOAT[0]] = load_float
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000933
Guido van Rossumd3703791998-10-22 20:15:36 +0000934 def load_binfloat(self, unpack=struct.unpack):
935 self.append(unpack('>d', self.read(8))[0])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000936 dispatch[BINFLOAT[0]] = load_binfloat
Guido van Rossumd3703791998-10-22 20:15:36 +0000937
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000938 def load_string(self):
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000939 rep = self.readline()[:-1]
Tim Petersad5a7712003-01-28 16:23:33 +0000940 for q in "\"'": # double or single quote
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000941 if rep.startswith(q):
942 if not rep.endswith(q):
943 raise ValueError, "insecure string pickle"
944 rep = rep[len(q):-len(q)]
945 break
946 else:
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000947 raise ValueError, "insecure string pickle"
Martin v. Löwis10a60b32007-07-18 02:28:27 +0000948 self.append(bytes(codecs.escape_decode(rep)[0]))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000949 dispatch[STRING[0]] = load_string
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000950
951 def load_binstring(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000952 len = mloads(b'i' + self.read(4))
Martin v. Löwis10a60b32007-07-18 02:28:27 +0000953 self.append(self.read(len))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000954 dispatch[BINSTRING[0]] = load_binstring
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000955
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000956 def load_unicode(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000957 self.append(str(self.readline()[:-1], 'raw-unicode-escape'))
958 dispatch[UNICODE[0]] = load_unicode
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000959
960 def load_binunicode(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000961 len = mloads(b'i' + self.read(4))
962 self.append(str(self.read(len), 'utf-8'))
963 dispatch[BINUNICODE[0]] = load_binunicode
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000964
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000965 def load_short_binstring(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000966 len = ord(self.read(1))
Martin v. Löwis10a60b32007-07-18 02:28:27 +0000967 self.append(self.read(len))
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000968 dispatch[SHORT_BINSTRING[0]] = load_short_binstring
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000969
970 def load_tuple(self):
971 k = self.marker()
972 self.stack[k:] = [tuple(self.stack[k+1:])]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000973 dispatch[TUPLE[0]] = load_tuple
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000974
975 def load_empty_tuple(self):
976 self.stack.append(())
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000977 dispatch[EMPTY_TUPLE[0]] = load_empty_tuple
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000978
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000979 def load_tuple1(self):
980 self.stack[-1] = (self.stack[-1],)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000981 dispatch[TUPLE1[0]] = load_tuple1
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000982
983 def load_tuple2(self):
984 self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000985 dispatch[TUPLE2[0]] = load_tuple2
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000986
987 def load_tuple3(self):
988 self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000989 dispatch[TUPLE3[0]] = load_tuple3
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000990
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000991 def load_empty_list(self):
992 self.stack.append([])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000993 dispatch[EMPTY_LIST[0]] = load_empty_list
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000994
995 def load_empty_dictionary(self):
996 self.stack.append({})
Guido van Rossum2e6a4b32007-05-04 19:56:22 +0000997 dispatch[EMPTY_DICT[0]] = load_empty_dictionary
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000998
999 def load_list(self):
1000 k = self.marker()
1001 self.stack[k:] = [self.stack[k+1:]]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001002 dispatch[LIST[0]] = load_list
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001003
1004 def load_dict(self):
1005 k = self.marker()
1006 d = {}
1007 items = self.stack[k+1:]
1008 for i in range(0, len(items), 2):
1009 key = items[i]
1010 value = items[i+1]
1011 d[key] = value
1012 self.stack[k:] = [d]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001013 dispatch[DICT[0]] = load_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001014
Tim Petersd01c1e92003-01-30 15:41:46 +00001015 # INST and OBJ differ only in how they get a class object. It's not
1016 # only sensible to do the rest in a common routine, the two routines
1017 # previously diverged and grew different bugs.
1018 # klass is the class to instantiate, and k points to the topmost mark
1019 # object, following which are the arguments for klass.__init__.
1020 def _instantiate(self, klass, k):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001021 args = tuple(self.stack[k+1:])
1022 del self.stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001023 instantiated = 0
Tim Petersd01c1e92003-01-30 15:41:46 +00001024 if (not args and
Guido van Rossum13257902007-06-07 23:15:56 +00001025 isinstance(klass, type) and
Tim Petersd01c1e92003-01-30 15:41:46 +00001026 not hasattr(klass, "__getinitargs__")):
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001027 value = _EmptyClass()
1028 value.__class__ = klass
1029 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001030 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +00001031 try:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001032 value = klass(*args)
Guido van Rossumb940e112007-01-10 16:19:56 +00001033 except TypeError as err:
Guido van Rossum743d17e1998-09-15 20:25:57 +00001034 raise TypeError, "in constructor for %s: %s" % (
1035 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001036 self.append(value)
Tim Petersd01c1e92003-01-30 15:41:46 +00001037
1038 def load_inst(self):
1039 module = self.readline()[:-1]
1040 name = self.readline()[:-1]
1041 klass = self.find_class(module, name)
1042 self._instantiate(klass, self.marker())
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001043 dispatch[INST[0]] = load_inst
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001044
1045 def load_obj(self):
Tim Petersd01c1e92003-01-30 15:41:46 +00001046 # Stack is ... markobject classobject arg1 arg2 ...
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001047 k = self.marker()
Tim Petersd01c1e92003-01-30 15:41:46 +00001048 klass = self.stack.pop(k+1)
1049 self._instantiate(klass, k)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001050 dispatch[OBJ[0]] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001051
Guido van Rossum3a41c612003-01-28 15:10:22 +00001052 def load_newobj(self):
1053 args = self.stack.pop()
1054 cls = self.stack[-1]
1055 obj = cls.__new__(cls, *args)
Guido van Rossum533dbcf2003-01-28 17:55:05 +00001056 self.stack[-1] = obj
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001057 dispatch[NEWOBJ[0]] = load_newobj
Guido van Rossum3a41c612003-01-28 15:10:22 +00001058
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001059 def load_global(self):
1060 module = self.readline()[:-1]
1061 name = self.readline()[:-1]
1062 klass = self.find_class(module, name)
1063 self.append(klass)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001064 dispatch[GLOBAL[0]] = load_global
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001065
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001066 def load_ext1(self):
1067 code = ord(self.read(1))
1068 self.get_extension(code)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001069 dispatch[EXT1[0]] = load_ext1
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001070
1071 def load_ext2(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001072 code = mloads(b'i' + self.read(2) + b'\000\000')
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001073 self.get_extension(code)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001074 dispatch[EXT2[0]] = load_ext2
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001075
1076 def load_ext4(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001077 code = mloads(b'i' + self.read(4))
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001078 self.get_extension(code)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001079 dispatch[EXT4[0]] = load_ext4
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001080
1081 def get_extension(self, code):
1082 nil = []
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001083 obj = _extension_cache.get(code, nil)
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001084 if obj is not nil:
1085 self.append(obj)
1086 return
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001087 key = _inverted_registry.get(code)
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001088 if not key:
1089 raise ValueError("unregistered extension code %d" % code)
1090 obj = self.find_class(*key)
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001091 _extension_cache[code] = obj
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001092 self.append(obj)
1093
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001094 def find_class(self, module, name):
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001095 # Subclasses may override this
Guido van Rossum1255ed62007-05-04 20:30:19 +00001096 module = str(module)
1097 name = str(name)
Barry Warsawbf4d9592001-11-15 23:42:58 +00001098 __import__(module)
1099 mod = sys.modules[module]
1100 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001101 return klass
1102
1103 def load_reduce(self):
1104 stack = self.stack
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001105 args = stack.pop()
1106 func = stack[-1]
Raymond Hettingera6b45cc2004-12-07 07:05:57 +00001107 value = func(*args)
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):
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001125 self.append(self.memo[str8(self.readline())[:-1]])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001126 dispatch[GET[0]] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +00001127
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001128 def load_binget(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001129 i = ord(self.read(1))
Walter Dörwald70a6b492004-02-12 17:35:32 +00001130 self.append(self.memo[repr(i)])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001131 dispatch[BINGET[0]] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001132
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001133 def load_long_binget(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001134 i = mloads(b'i' + self.read(4))
Walter Dörwald70a6b492004-02-12 17:35:32 +00001135 self.append(self.memo[repr(i)])
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001136 dispatch[LONG_BINGET[0]] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001137
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001138 def load_put(self):
Guido van Rossum1255ed62007-05-04 20:30:19 +00001139 self.memo[str(self.readline()[:-1])] = self.stack[-1]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001140 dispatch[PUT[0]] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +00001141
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001142 def load_binput(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001143 i = ord(self.read(1))
Walter Dörwald70a6b492004-02-12 17:35:32 +00001144 self.memo[repr(i)] = self.stack[-1]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001145 dispatch[BINPUT[0]] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001146
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001147 def load_long_binput(self):
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001148 i = mloads(b'i' + self.read(4))
Walter Dörwald70a6b492004-02-12 17:35:32 +00001149 self.memo[repr(i)] = self.stack[-1]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001150 dispatch[LONG_BINPUT[0]] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001151
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001152 def load_append(self):
1153 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001154 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001155 list = stack[-1]
1156 list.append(value)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001157 dispatch[APPEND[0]] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +00001158
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001159 def load_appends(self):
1160 stack = self.stack
1161 mark = self.marker()
1162 list = stack[mark - 1]
Tim Peters209ad952003-01-28 01:44:45 +00001163 list.extend(stack[mark + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001164 del stack[mark:]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001165 dispatch[APPENDS[0]] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +00001166
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001167 def load_setitem(self):
1168 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001169 value = stack.pop()
1170 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001171 dict = stack[-1]
1172 dict[key] = value
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001173 dispatch[SETITEM[0]] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001174
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001175 def load_setitems(self):
1176 stack = self.stack
1177 mark = self.marker()
1178 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001179 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001180 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001181
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001182 del stack[mark:]
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001183 dispatch[SETITEMS[0]] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001184
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001185 def load_build(self):
1186 stack = self.stack
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001187 state = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001188 inst = stack[-1]
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001189 setstate = getattr(inst, "__setstate__", None)
1190 if setstate:
1191 setstate(state)
1192 return
1193 slotstate = None
1194 if isinstance(state, tuple) and len(state) == 2:
1195 state, slotstate = state
1196 if state:
Guido van Rossuma8add0e2007-05-14 22:03:55 +00001197 inst.__dict__.update(state)
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001198 if slotstate:
1199 for k, v in slotstate.items():
1200 setattr(inst, k, v)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001201 dispatch[BUILD[0]] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001202
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001203 def load_mark(self):
1204 self.append(self.mark)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001205 dispatch[MARK[0]] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001206
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001207 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001208 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001209 raise _Stop(value)
Guido van Rossum2e6a4b32007-05-04 19:56:22 +00001210 dispatch[STOP[0]] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001211
Guido van Rossume467be61997-12-05 19:42:42 +00001212# Helper class for load_inst/load_obj
1213
1214class _EmptyClass:
1215 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001216
Tim Peters91149822003-01-31 03:43:58 +00001217# Encode/decode longs in linear time.
1218
1219import binascii as _binascii
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001220
1221def encode_long(x):
Tim Peters91149822003-01-31 03:43:58 +00001222 r"""Encode a long to a two's complement little-endian binary string.
Guido van Rossume2a383d2007-01-15 16:59:06 +00001223 Note that 0 is a special case, returning an empty string, to save a
Tim Peters4b23f2b2003-01-31 16:43:39 +00001224 byte in the LONG1 pickling context.
1225
Guido van Rossume2a383d2007-01-15 16:59:06 +00001226 >>> encode_long(0)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001227 b''
Guido van Rossume2a383d2007-01-15 16:59:06 +00001228 >>> encode_long(255)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001229 b'\xff\x00'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001230 >>> encode_long(32767)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001231 b'\xff\x7f'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001232 >>> encode_long(-256)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001233 b'\x00\xff'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001234 >>> encode_long(-32768)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001235 b'\x00\x80'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001236 >>> encode_long(-128)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001237 b'\x80'
Guido van Rossume2a383d2007-01-15 16:59:06 +00001238 >>> encode_long(127)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001239 b'\x7f'
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001240 >>>
1241 """
Tim Peters91149822003-01-31 03:43:58 +00001242
1243 if x == 0:
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001244 return b''
Tim Peters91149822003-01-31 03:43:58 +00001245 if x > 0:
1246 ashex = hex(x)
1247 assert ashex.startswith("0x")
1248 njunkchars = 2 + ashex.endswith('L')
1249 nibbles = len(ashex) - njunkchars
1250 if nibbles & 1:
1251 # need an even # of nibbles for unhexlify
1252 ashex = "0x0" + ashex[2:]
Tim Peters4b23f2b2003-01-31 16:43:39 +00001253 elif int(ashex[2], 16) >= 8:
Tim Peters91149822003-01-31 03:43:58 +00001254 # "looks negative", so need a byte of sign bits
1255 ashex = "0x00" + ashex[2:]
1256 else:
1257 # Build the 256's-complement: (1L << nbytes) + x. The trick is
1258 # to find the number of bytes in linear time (although that should
1259 # really be a constant-time task).
1260 ashex = hex(-x)
1261 assert ashex.startswith("0x")
1262 njunkchars = 2 + ashex.endswith('L')
1263 nibbles = len(ashex) - njunkchars
1264 if nibbles & 1:
Tim Petersee1a53c2003-02-02 02:57:53 +00001265 # Extend to a full byte.
Tim Peters91149822003-01-31 03:43:58 +00001266 nibbles += 1
Tim Peters4b23f2b2003-01-31 16:43:39 +00001267 nbits = nibbles * 4
Guido van Rossume2a383d2007-01-15 16:59:06 +00001268 x += 1 << nbits
Tim Peters91149822003-01-31 03:43:58 +00001269 assert x > 0
1270 ashex = hex(x)
Tim Petersee1a53c2003-02-02 02:57:53 +00001271 njunkchars = 2 + ashex.endswith('L')
1272 newnibbles = len(ashex) - njunkchars
1273 if newnibbles < nibbles:
1274 ashex = "0x" + "0" * (nibbles - newnibbles) + ashex[2:]
1275 if int(ashex[2], 16) < 8:
Tim Peters91149822003-01-31 03:43:58 +00001276 # "looks positive", so need a byte of sign bits
Tim Petersee1a53c2003-02-02 02:57:53 +00001277 ashex = "0xff" + ashex[2:]
Tim Peters91149822003-01-31 03:43:58 +00001278
1279 if ashex.endswith('L'):
1280 ashex = ashex[2:-1]
1281 else:
1282 ashex = ashex[2:]
Tim Petersee1a53c2003-02-02 02:57:53 +00001283 assert len(ashex) & 1 == 0, (x, ashex)
Tim Peters91149822003-01-31 03:43:58 +00001284 binary = _binascii.unhexlify(ashex)
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001285 return bytes(binary[::-1])
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001286
1287def decode_long(data):
1288 r"""Decode a long from a two's complement little-endian binary string.
Tim Peters4b23f2b2003-01-31 16:43:39 +00001289
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001290 >>> decode_long(b'')
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001291 0
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001292 >>> decode_long(b"\xff\x00")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001293 255
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001294 >>> decode_long(b"\xff\x7f")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001295 32767
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001296 >>> decode_long(b"\x00\xff")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001297 -256
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001298 >>> decode_long(b"\x00\x80")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001299 -32768
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001300 >>> decode_long(b"\x80")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001301 -128
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001302 >>> decode_long(b"\x7f")
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001303 127
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001304 """
Tim Peters91149822003-01-31 03:43:58 +00001305
Tim Peters4b23f2b2003-01-31 16:43:39 +00001306 nbytes = len(data)
1307 if nbytes == 0:
Guido van Rossume2a383d2007-01-15 16:59:06 +00001308 return 0
Tim Peters91149822003-01-31 03:43:58 +00001309 ashex = _binascii.hexlify(data[::-1])
Guido van Rossume2a383d2007-01-15 16:59:06 +00001310 n = int(ashex, 16) # quadratic time before Python 2.3; linear now
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001311 if data[-1] >= 0x80:
Guido van Rossume2a383d2007-01-15 16:59:06 +00001312 n -= 1 << (nbytes * 8)
Tim Peters91149822003-01-31 03:43:58 +00001313 return n
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001314
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001315# Shorthands
1316
Raymond Hettinger3489cad2004-12-05 05:20:42 +00001317def dump(obj, file, protocol=None):
1318 Pickler(file, protocol).dump(obj)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001319
Raymond Hettinger3489cad2004-12-05 05:20:42 +00001320def dumps(obj, protocol=None):
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001321 f = io.BytesIO()
1322 Pickler(f, protocol).dump(obj)
1323 res = f.getvalue()
1324 assert isinstance(res, bytes)
1325 return res
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001326
1327def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001328 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001329
Guido van Rossumcfe5f202007-05-08 21:26:54 +00001330def loads(s):
1331 if isinstance(s, str):
1332 raise TypeError("Can't load pickle from unicode string")
1333 file = io.BytesIO(s)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001334 return Unpickler(file).load()
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001335
1336# Doctest
1337
1338def _test():
1339 import doctest
1340 return doctest.testmod()
1341
1342if __name__ == "__main__":
1343 _test()