blob: 4c9188830af746c013bf7f9e2d23cf16a17e91d1 [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
29from types import *
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 Rossumbc64e222003-01-28 16:34:19 +000036import warnings
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
Tim Petersc0c12b52003-01-29 00:56:17 +000041# These are purely informational; no code uses these.
Guido van Rossumf29d3d62003-01-27 22:47:53 +000042format_version = "2.0" # File format version we write
43compatible_formats = ["1.0", # Original protocol 0
Guido van Rossumbc64e222003-01-28 16:34:19 +000044 "1.1", # Protocol 0 with INST added
Guido van Rossumf29d3d62003-01-27 22:47:53 +000045 "1.2", # Original protocol 1
46 "1.3", # Protocol 1 with BINFLOAT added
47 "2.0", # Protocol 2
48 ] # Old format versions we can read
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000049
Tim Peters8587b3c2003-02-13 15:44:41 +000050# Keep in synch with cPickle. This is the highest protocol number we
51# know how to read.
52HIGHEST_PROTOCOL = 2
53
Guido van Rossume0b90422003-01-28 03:17:21 +000054# Why use struct.pack() for pickling but marshal.loads() for
Tim Petersc0c12b52003-01-29 00:56:17 +000055# unpickling? struct.pack() is 40% faster than marshal.dumps(), but
Guido van Rossume0b90422003-01-28 03:17:21 +000056# marshal.loads() is twice as fast as struct.unpack()!
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000057mloads = marshal.loads
Guido van Rossum0c891ce1995-03-14 15:09:05 +000058
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000059class PickleError(Exception):
Neal Norwitzefbb67b2002-05-30 12:12:04 +000060 """A common base class for the other pickling exceptions."""
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000061 pass
62
63class PicklingError(PickleError):
64 """This exception is raised when an unpicklable object is passed to the
65 dump() method.
66
67 """
68 pass
69
70class UnpicklingError(PickleError):
71 """This exception is raised when there is a problem unpickling an object,
72 such as a security violation.
73
74 Note that other exceptions may also be raised during unpickling, including
75 (but not necessarily limited to) AttributeError, EOFError, ImportError,
76 and IndexError.
77
78 """
79 pass
Guido van Rossum7849da81995-03-09 14:08:35 +000080
Tim Petersc0c12b52003-01-29 00:56:17 +000081# An instance of _Stop is raised by Unpickler.load_stop() in response to
82# the STOP opcode, passing the object that is the result of unpickling.
Guido van Rossumff871742000-12-13 18:11:56 +000083class _Stop(Exception):
84 def __init__(self, value):
85 self.value = value
86
Guido van Rossum533dbcf2003-01-28 17:55:05 +000087# Jython has PyStringMap; it's a dict subclass with string keys
Jeremy Hylton2b9d0291998-05-27 22:38:22 +000088try:
89 from org.python.core import PyStringMap
90except ImportError:
91 PyStringMap = None
92
Guido van Rossum533dbcf2003-01-28 17:55:05 +000093# UnicodeType may or may not be exported (normally imported from types)
Guido van Rossumdbb718f2001-09-21 19:22:34 +000094try:
95 UnicodeType
96except NameError:
97 UnicodeType = None
98
Tim Peters22a449a2003-01-27 20:16:36 +000099# Pickle opcodes. See pickletools.py for extensive docs. The listing
100# here is in kind-of alphabetical order of 1-character pickle code.
101# pickletools groups them by purpose.
Guido van Rossumdbb718f2001-09-21 19:22:34 +0000102
Tim Peters22a449a2003-01-27 20:16:36 +0000103MARK = '(' # push special markobject on stack
104STOP = '.' # every pickle ends with STOP
105POP = '0' # discard topmost stack item
106POP_MARK = '1' # discard stack top through topmost markobject
107DUP = '2' # duplicate top stack item
108FLOAT = 'F' # push float object; decimal string argument
109INT = 'I' # push integer or bool; decimal string argument
110BININT = 'J' # push four-byte signed int
111BININT1 = 'K' # push 1-byte unsigned int
112LONG = 'L' # push long; decimal string argument
113BININT2 = 'M' # push 2-byte unsigned int
114NONE = 'N' # push None
115PERSID = 'P' # push persistent object; id is taken from string arg
116BINPERSID = 'Q' # " " " ; " " " " stack
117REDUCE = 'R' # apply callable to argtuple, both on stack
118STRING = 'S' # push string; NL-terminated string argument
119BINSTRING = 'T' # push string; counted binary string argument
120SHORT_BINSTRING = 'U' # " " ; " " " " < 256 bytes
121UNICODE = 'V' # push Unicode string; raw-unicode-escaped'd argument
122BINUNICODE = 'X' # " " " ; counted UTF-8 string argument
123APPEND = 'a' # append stack top to list below it
124BUILD = 'b' # call __setstate__ or __dict__.update()
125GLOBAL = 'c' # push self.find_class(modname, name); 2 string args
126DICT = 'd' # build a dict from stack items
127EMPTY_DICT = '}' # push empty dict
128APPENDS = 'e' # extend list on stack by topmost stack slice
129GET = 'g' # push item from memo on stack; index is string arg
130BINGET = 'h' # " " " " " " ; " " 1-byte arg
131INST = 'i' # build & push class instance
132LONG_BINGET = 'j' # push item from memo on stack; index is 4-byte arg
133LIST = 'l' # build list from topmost stack items
134EMPTY_LIST = ']' # push empty list
135OBJ = 'o' # build & push class instance
136PUT = 'p' # store stack top in memo; index is string arg
137BINPUT = 'q' # " " " " " ; " " 1-byte arg
138LONG_BINPUT = 'r' # " " " " " ; " " 4-byte arg
139SETITEM = 's' # add key+value pair to dict
140TUPLE = 't' # build tuple from topmost stack items
141EMPTY_TUPLE = ')' # push empty tuple
142SETITEMS = 'u' # modify dict by adding topmost key+value pairs
143BINFLOAT = 'G' # push float; arg is 8-byte float encoding
144
145TRUE = 'I01\n' # not an opcode; see INT docs in pickletools.py
146FALSE = 'I00\n' # not an opcode; see INT docs in pickletools.py
Guido van Rossum77f6a652002-04-03 22:41:51 +0000147
Guido van Rossum586c9e82003-01-29 06:16:12 +0000148# Protocol 2
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000149
Tim Peterse1054782003-01-28 00:22:12 +0000150PROTO = '\x80' # identify pickle protocol
151NEWOBJ = '\x81' # build object by applying cls.__new__ to argtuple
152EXT1 = '\x82' # push object from extension registry; 1-byte index
153EXT2 = '\x83' # ditto, but 2-byte index
154EXT4 = '\x84' # ditto, but 4-byte index
155TUPLE1 = '\x85' # build 1-tuple from stack top
156TUPLE2 = '\x86' # build 2-tuple from two topmost stack items
157TUPLE3 = '\x87' # build 3-tuple from three topmost stack items
158NEWTRUE = '\x88' # push True
159NEWFALSE = '\x89' # push False
160LONG1 = '\x8a' # push long from < 256 bytes
161LONG4 = '\x8b' # push really big long
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000162
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000163_tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3]
164
Guido van Rossuma48061a1995-01-10 00:31:14 +0000165
Skip Montanaro23bafc62001-02-18 03:10:09 +0000166__all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
Neal Norwitzd5ba4ae2002-02-11 18:12:06 +0000167del x
Skip Montanaro23bafc62001-02-18 03:10:09 +0000168
Guido van Rossum1be31752003-01-28 15:19:53 +0000169
170# Pickling machinery
171
Guido van Rossuma48061a1995-01-10 00:31:14 +0000172class Pickler:
173
Raymond Hettinger3489cad2004-12-05 05:20:42 +0000174 def __init__(self, file, protocol=None):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000175 """This takes a file-like object for writing a pickle data stream.
176
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 Rossum7eff63a2003-01-31 19:42:31 +0000179 protocol is 0, to be backwards compatible. (Protocol 0 is the
180 only protocol that can be written to a file opened in text
Tim Peters5bd2a792003-02-01 16:45:06 +0000181 mode and read back successfully. When using a protocol higher
182 than 0, make sure the file is opened in binary mode, both when
183 pickling and unpickling.)
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000184
185 Protocol 1 is more efficient than protocol 0; protocol 2 is
Guido van Rossum7eff63a2003-01-31 19:42:31 +0000186 more efficient than protocol 1.
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000187
Guido van Rossum7eff63a2003-01-31 19:42:31 +0000188 Specifying a negative protocol version selects the highest
Tim Peters5bd2a792003-02-01 16:45:06 +0000189 protocol version supported. The higher the protocol used, the
190 more recent the version of Python needed to read the pickle
191 produced.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000192
193 The file parameter must have a write() method that accepts a single
194 string argument. It can thus be an open file object, a StringIO
195 object, or any other custom object that meets this interface.
196
197 """
Guido van Rossumcf117b02003-02-09 17:19:41 +0000198 if protocol is None:
199 protocol = 0
200 if protocol < 0:
Tim Peters8587b3c2003-02-13 15:44:41 +0000201 protocol = HIGHEST_PROTOCOL
202 elif not 0 <= protocol <= HIGHEST_PROTOCOL:
203 raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000204 self.write = file.write
205 self.memo = {}
Guido van Rossumcf117b02003-02-09 17:19:41 +0000206 self.proto = int(protocol)
207 self.bin = protocol >= 1
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000208 self.fast = 0
Guido van Rossuma48061a1995-01-10 00:31:14 +0000209
Fred Drake7f781c92002-05-01 20:33:53 +0000210 def clear_memo(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000211 """Clears the pickler's "memo".
212
213 The memo is the data structure that remembers which objects the
Tim Petersb377f8a2003-01-28 00:23:36 +0000214 pickler has already seen, so that shared or recursive objects are
215 pickled by reference and not by value. This method is useful when
216 re-using picklers.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000217
218 """
Fred Drake7f781c92002-05-01 20:33:53 +0000219 self.memo.clear()
220
Guido van Rossum3a41c612003-01-28 15:10:22 +0000221 def dump(self, obj):
Tim Peters5bd2a792003-02-01 16:45:06 +0000222 """Write a pickled representation of obj to the open file."""
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000223 if self.proto >= 2:
224 self.write(PROTO + chr(self.proto))
Guido van Rossum3a41c612003-01-28 15:10:22 +0000225 self.save(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000226 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000227
Jeremy Hylton3422c992003-01-24 19:29:52 +0000228 def memoize(self, obj):
229 """Store an object in the memo."""
230
Tim Peterse46b73f2003-01-27 21:22:10 +0000231 # The Pickler memo is a dictionary mapping object ids to 2-tuples
232 # that contain the Unpickler memo key and the object being memoized.
233 # The memo key is written to the pickle and will become
Jeremy Hylton3422c992003-01-24 19:29:52 +0000234 # the key in the Unpickler's memo. The object is stored in the
Tim Peterse46b73f2003-01-27 21:22:10 +0000235 # Pickler memo so that transient objects are kept alive during
236 # pickling.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000237
Tim Peterse46b73f2003-01-27 21:22:10 +0000238 # The use of the Unpickler memo length as the memo key is just a
239 # convention. The only requirement is that the memo values be unique.
240 # But there appears no advantage to any other scheme, and this
Tim Peterscbd0a322003-01-28 00:24:43 +0000241 # scheme allows the Unpickler memo to be implemented as a plain (but
Tim Peterse46b73f2003-01-27 21:22:10 +0000242 # growable) array, indexed by memo key.
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000243 if self.fast:
244 return
Guido van Rossum9b40e802003-01-30 06:37:41 +0000245 assert id(obj) not in self.memo
Jeremy Hylton3422c992003-01-24 19:29:52 +0000246 memo_len = len(self.memo)
247 self.write(self.put(memo_len))
Tim Peters518df0d2003-01-28 01:00:38 +0000248 self.memo[id(obj)] = memo_len, obj
Jeremy Hylton3422c992003-01-24 19:29:52 +0000249
Tim Petersbb38e302003-01-27 21:25:41 +0000250 # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000251 def put(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000252 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000253 if i < 256:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000254 return BINPUT + chr(i)
255 else:
256 return LONG_BINPUT + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000257
Walter Dörwald70a6b492004-02-12 17:35:32 +0000258 return PUT + repr(i) + '\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000259
Tim Petersbb38e302003-01-27 21:25:41 +0000260 # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000261 def get(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000262 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000263 if i < 256:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000264 return BINGET + chr(i)
265 else:
266 return LONG_BINGET + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000267
Walter Dörwald70a6b492004-02-12 17:35:32 +0000268 return GET + repr(i) + '\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000269
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000270 def save(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000271 # Check for persistent id (defined by a subclass)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000272 pid = self.persistent_id(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000273 if pid:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000274 self.save_pers(pid)
275 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000276
Guido van Rossumbc64e222003-01-28 16:34:19 +0000277 # Check the memo
278 x = self.memo.get(id(obj))
279 if x:
280 self.write(self.get(x[0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000281 return
282
Guido van Rossumbc64e222003-01-28 16:34:19 +0000283 # Check the type dispatch table
Guido van Rossum3a41c612003-01-28 15:10:22 +0000284 t = type(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000285 f = self.dispatch.get(t)
286 if f:
287 f(self, obj) # Call unbound method with explicit self
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000288 return
289
Guido van Rossumbc64e222003-01-28 16:34:19 +0000290 # Check for a class with a custom metaclass; treat as regular class
Tim Petersb32a8312003-01-28 00:48:09 +0000291 try:
292 issc = issubclass(t, TypeType)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000293 except TypeError: # t is not a class (old Boost; see SF #502085)
Tim Petersb32a8312003-01-28 00:48:09 +0000294 issc = 0
295 if issc:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000296 self.save_global(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000297 return
298
Guido van Rossumbc64e222003-01-28 16:34:19 +0000299 # Check copy_reg.dispatch_table
300 reduce = dispatch_table.get(t)
Guido van Rossumc53f0092003-02-18 22:05:12 +0000301 if reduce:
302 rv = reduce(obj)
303 else:
304 # Check for a __reduce_ex__ method, fall back to __reduce__
305 reduce = getattr(obj, "__reduce_ex__", None)
306 if reduce:
307 rv = reduce(self.proto)
308 else:
309 reduce = getattr(obj, "__reduce__", None)
310 if reduce:
311 rv = reduce()
312 else:
313 raise PicklingError("Can't pickle %r object: %r" %
314 (t.__name__, obj))
Tim Petersb32a8312003-01-28 00:48:09 +0000315
Guido van Rossumbc64e222003-01-28 16:34:19 +0000316 # Check for string returned by reduce(), meaning "save as global"
317 if type(rv) is StringType:
318 self.save_global(obj, rv)
Tim Petersb32a8312003-01-28 00:48:09 +0000319 return
320
Guido van Rossumbc64e222003-01-28 16:34:19 +0000321 # Assert that reduce() returned a tuple
322 if type(rv) is not TupleType:
323 raise PicklingError("%s must return string or tuple" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000324
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000325 # Assert that it returned an appropriately sized tuple
Guido van Rossumbc64e222003-01-28 16:34:19 +0000326 l = len(rv)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000327 if not (2 <= l <= 5):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000328 raise PicklingError("Tuple returned by %s must have "
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000329 "two to five elements" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000330
Guido van Rossumbc64e222003-01-28 16:34:19 +0000331 # Save the reduce() output and finally memoize the object
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000332 self.save_reduce(obj=obj, *rv)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000333
Guido van Rossum3a41c612003-01-28 15:10:22 +0000334 def persistent_id(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000335 # This exists so a subclass can override it
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000336 return None
337
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000338 def save_pers(self, pid):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000339 # Save a persistent id reference
Tim Petersbd1cdb92003-01-28 01:03:10 +0000340 if self.bin:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000341 self.save(pid)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000342 self.write(BINPERSID)
Tim Petersbd1cdb92003-01-28 01:03:10 +0000343 else:
344 self.write(PERSID + str(pid) + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000345
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000346 def save_reduce(self, func, args, state=None,
347 listitems=None, dictitems=None, obj=None):
Jeremy Hyltone3a565e2003-06-29 16:59:59 +0000348 # This API is called by some subclasses
Guido van Rossumbc64e222003-01-28 16:34:19 +0000349
350 # Assert that args is a tuple or None
351 if not isinstance(args, TupleType):
352 if args is None:
353 # A hack for Jim Fulton's ExtensionClass, now deprecated.
354 # See load_reduce()
355 warnings.warn("__basicnew__ special case is deprecated",
356 DeprecationWarning)
357 else:
358 raise PicklingError(
359 "args from reduce() should be a tuple")
360
361 # Assert that func is callable
362 if not callable(func):
363 raise PicklingError("func from reduce should be callable")
364
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000365 save = self.save
Guido van Rossumbc64e222003-01-28 16:34:19 +0000366 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000367
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000368 # Protocol 2 special case: if func's name is __newobj__, use NEWOBJ
369 if self.proto >= 2 and getattr(func, "__name__", "") == "__newobj__":
370 # A __reduce__ implementation can direct protocol 2 to
371 # use the more efficient NEWOBJ opcode, while still
372 # allowing protocol 0 and 1 to work normally. For this to
373 # work, the function returned by __reduce__ should be
374 # called __newobj__, and its first argument should be a
375 # new-style class. The implementation for __newobj__
376 # should be as follows, although pickle has no way to
377 # verify this:
378 #
379 # def __newobj__(cls, *args):
380 # return cls.__new__(cls, *args)
381 #
382 # Protocols 0 and 1 will pickle a reference to __newobj__,
383 # while protocol 2 (and above) will pickle a reference to
384 # cls, the remaining args tuple, and the NEWOBJ code,
385 # which calls cls.__new__(cls, *args) at unpickling time
386 # (see load_newobj below). If __reduce__ returns a
387 # three-tuple, the state from the third tuple item will be
388 # pickled regardless of the protocol, calling __setstate__
389 # at unpickling time (see load_build below).
390 #
391 # Note that no standard __newobj__ implementation exists;
392 # you have to provide your own. This is to enforce
393 # compatibility with Python 2.2 (pickles written using
394 # protocol 0 or 1 in Python 2.3 should be unpicklable by
395 # Python 2.2).
396 cls = args[0]
397 if not hasattr(cls, "__new__"):
398 raise PicklingError(
399 "args[0] from __newobj__ args has no __new__")
Guido van Rossumf7f45172003-01-31 17:17:49 +0000400 if obj is not None and cls is not obj.__class__:
401 raise PicklingError(
402 "args[0] from __newobj__ args has the wrong class")
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000403 args = args[1:]
404 save(cls)
405 save(args)
406 write(NEWOBJ)
407 else:
408 save(func)
409 save(args)
410 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000411
Guido van Rossumf7f45172003-01-31 17:17:49 +0000412 if obj is not None:
413 self.memoize(obj)
414
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000415 # More new special cases (that work with older protocols as
416 # well): when __reduce__ returns a tuple with 4 or 5 items,
417 # the 4th and 5th item should be iterators that provide list
418 # items and dict items (as (key, value) tuples), or None.
419
420 if listitems is not None:
421 self._batch_appends(listitems)
422
423 if dictitems is not None:
424 self._batch_setitems(dictitems)
425
Tim Petersc32d8242001-04-10 02:48:53 +0000426 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000427 save(state)
428 write(BUILD)
429
Guido van Rossumbc64e222003-01-28 16:34:19 +0000430 # Methods below this point are dispatched through the dispatch table
431
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000432 dispatch = {}
433
Guido van Rossum3a41c612003-01-28 15:10:22 +0000434 def save_none(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000435 self.write(NONE)
436 dispatch[NoneType] = save_none
437
Guido van Rossum3a41c612003-01-28 15:10:22 +0000438 def save_bool(self, obj):
Guido van Rossum7d97d312003-01-28 04:25:27 +0000439 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000440 self.write(obj and NEWTRUE or NEWFALSE)
Guido van Rossum7d97d312003-01-28 04:25:27 +0000441 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000442 self.write(obj and TRUE or FALSE)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000443 dispatch[bool] = save_bool
444
Guido van Rossum3a41c612003-01-28 15:10:22 +0000445 def save_int(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000446 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000447 # If the int is small enough to fit in a signed 4-byte 2's-comp
448 # format, we can store it more efficiently than the general
449 # case.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000450 # First one- and two-byte unsigned ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000451 if obj >= 0:
452 if obj <= 0xff:
453 self.write(BININT1 + chr(obj))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000454 return
Guido van Rossum3a41c612003-01-28 15:10:22 +0000455 if obj <= 0xffff:
Guido van Rossumba884f32003-01-29 20:14:23 +0000456 self.write("%c%c%c" % (BININT2, obj&0xff, obj>>8))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000457 return
458 # Next check for 4-byte signed ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000459 high_bits = obj >> 31 # note that Python shift sign-extends
Tim Petersd95c2df2003-01-28 03:41:54 +0000460 if high_bits == 0 or high_bits == -1:
Tim Peters44714002001-04-10 05:02:52 +0000461 # All high bits are copies of bit 2**31, so the value
462 # fits in a 4-byte signed int.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000463 self.write(BININT + pack("<i", obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000464 return
Tim Peters44714002001-04-10 05:02:52 +0000465 # Text pickle, or int too big to fit in signed 4-byte format.
Walter Dörwald70a6b492004-02-12 17:35:32 +0000466 self.write(INT + repr(obj) + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000467 dispatch[IntType] = save_int
468
Guido van Rossum3a41c612003-01-28 15:10:22 +0000469 def save_long(self, obj, pack=struct.pack):
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000470 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000471 bytes = encode_long(obj)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000472 n = len(bytes)
473 if n < 256:
474 self.write(LONG1 + chr(n) + bytes)
475 else:
476 self.write(LONG4 + pack("<i", n) + bytes)
Tim Petersee1a53c2003-02-02 02:57:53 +0000477 return
Walter Dörwald70a6b492004-02-12 17:35:32 +0000478 self.write(LONG + repr(obj) + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000479 dispatch[LongType] = save_long
480
Guido van Rossum3a41c612003-01-28 15:10:22 +0000481 def save_float(self, obj, pack=struct.pack):
Guido van Rossumd3703791998-10-22 20:15:36 +0000482 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000483 self.write(BINFLOAT + pack('>d', obj))
Guido van Rossumd3703791998-10-22 20:15:36 +0000484 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000485 self.write(FLOAT + repr(obj) + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000486 dispatch[FloatType] = save_float
487
Guido van Rossum3a41c612003-01-28 15:10:22 +0000488 def save_string(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000489 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000490 n = len(obj)
Tim Petersbbf63cd2003-01-27 21:15:36 +0000491 if n < 256:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000492 self.write(SHORT_BINSTRING + chr(n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000493 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000494 self.write(BINSTRING + pack("<i", n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000495 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000496 self.write(STRING + repr(obj) + '\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000497 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000498 dispatch[StringType] = save_string
499
Guido van Rossum3a41c612003-01-28 15:10:22 +0000500 def save_unicode(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000501 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000502 encoding = obj.encode('utf-8')
Tim Petersbbf63cd2003-01-27 21:15:36 +0000503 n = len(encoding)
Guido van Rossum5c938d02003-01-28 03:03:08 +0000504 self.write(BINUNICODE + pack("<i", n) + encoding)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000505 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000506 obj = obj.replace("\\", "\\u005c")
507 obj = obj.replace("\n", "\\u000a")
508 self.write(UNICODE + obj.encode('raw-unicode-escape') + '\n')
509 self.memoize(obj)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000510 dispatch[UnicodeType] = save_unicode
511
Guido van Rossum31584cb2001-01-22 14:53:29 +0000512 if StringType == UnicodeType:
513 # This is true for Jython
Guido van Rossum3a41c612003-01-28 15:10:22 +0000514 def save_string(self, obj, pack=struct.pack):
515 unicode = obj.isunicode()
Guido van Rossum31584cb2001-01-22 14:53:29 +0000516
Tim Petersc32d8242001-04-10 02:48:53 +0000517 if self.bin:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000518 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000519 obj = obj.encode("utf-8")
520 l = len(obj)
Tim Petersc32d8242001-04-10 02:48:53 +0000521 if l < 256 and not unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000522 self.write(SHORT_BINSTRING + chr(l) + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000523 else:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000524 s = pack("<i", l)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000525 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000526 self.write(BINUNICODE + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000527 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000528 self.write(BINSTRING + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000529 else:
Tim Peters658cba62001-02-09 20:06:00 +0000530 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000531 obj = obj.replace("\\", "\\u005c")
532 obj = obj.replace("\n", "\\u000a")
533 obj = obj.encode('raw-unicode-escape')
534 self.write(UNICODE + obj + '\n')
Guido van Rossum31584cb2001-01-22 14:53:29 +0000535 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000536 self.write(STRING + repr(obj) + '\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000537 self.memoize(obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000538 dispatch[StringType] = save_string
Tim Peters658cba62001-02-09 20:06:00 +0000539
Guido van Rossum3a41c612003-01-28 15:10:22 +0000540 def save_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000541 write = self.write
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000542 proto = self.proto
543
Guido van Rossum3a41c612003-01-28 15:10:22 +0000544 n = len(obj)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000545 if n == 0:
546 if proto:
547 write(EMPTY_TUPLE)
548 else:
549 write(MARK + TUPLE)
Tim Petersd97da802003-01-28 05:48:29 +0000550 return
551
552 save = self.save
553 memo = self.memo
554 if n <= 3 and proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000555 for element in obj:
Tim Petersd97da802003-01-28 05:48:29 +0000556 save(element)
557 # Subtle. Same as in the big comment below.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000558 if id(obj) in memo:
559 get = self.get(memo[id(obj)][0])
Tim Petersd97da802003-01-28 05:48:29 +0000560 write(POP * n + get)
561 else:
562 write(_tuplesize2code[n])
Guido van Rossum3a41c612003-01-28 15:10:22 +0000563 self.memoize(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000564 return
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000565
Tim Peters1d63c9f2003-02-02 20:29:39 +0000566 # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple
Tim Petersff57bff2003-01-28 05:34:53 +0000567 # has more than 3 elements.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000568 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000569 for element in obj:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000570 save(element)
571
Tim Peters1d63c9f2003-02-02 20:29:39 +0000572 if id(obj) in memo:
Tim Petersf558da02003-01-28 02:09:55 +0000573 # Subtle. d was not in memo when we entered save_tuple(), so
574 # the process of saving the tuple's elements must have saved
575 # the tuple itself: the tuple is recursive. The proper action
576 # now is to throw away everything we put on the stack, and
577 # simply GET the tuple (it's already constructed). This check
578 # could have been done in the "for element" loop instead, but
579 # recursive tuples are a rare thing.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000580 get = self.get(memo[id(obj)][0])
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000581 if proto:
Tim Petersf558da02003-01-28 02:09:55 +0000582 write(POP_MARK + get)
583 else: # proto 0 -- POP_MARK not available
Tim Petersd97da802003-01-28 05:48:29 +0000584 write(POP * (n+1) + get)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000585 return
586
Tim Peters1d63c9f2003-02-02 20:29:39 +0000587 # No recursion.
Tim Peters518df0d2003-01-28 01:00:38 +0000588 self.write(TUPLE)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000589 self.memoize(obj)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000590
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000591 dispatch[TupleType] = save_tuple
592
Tim Petersa6ae9a22003-01-28 16:58:41 +0000593 # save_empty_tuple() isn't used by anything in Python 2.3. However, I
594 # found a Pickler subclass in Zope3 that calls it, so it's not harmless
595 # to remove it.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000596 def save_empty_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000597 self.write(EMPTY_TUPLE)
598
Guido van Rossum3a41c612003-01-28 15:10:22 +0000599 def save_list(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000600 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000601
Tim Petersc32d8242001-04-10 02:48:53 +0000602 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000603 write(EMPTY_LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000604 else: # proto 0 -- can't use EMPTY_LIST
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000605 write(MARK + LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000606
607 self.memoize(obj)
608 self._batch_appends(iter(obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000609
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000610 dispatch[ListType] = save_list
611
Tim Peters42f08ac2003-02-11 22:43:24 +0000612 # Keep in synch with cPickle's BATCHSIZE. Nothing will break if it gets
613 # out of synch, though.
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000614 _BATCHSIZE = 1000
615
616 def _batch_appends(self, items):
617 # Helper to batch up APPENDS sequences
618 save = self.save
619 write = self.write
620
621 if not self.bin:
622 for x in items:
623 save(x)
624 write(APPEND)
625 return
626
627 r = xrange(self._BATCHSIZE)
628 while items is not None:
629 tmp = []
630 for i in r:
631 try:
Guido van Rossum5aac4e62003-02-06 22:57:00 +0000632 x = items.next()
633 tmp.append(x)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000634 except StopIteration:
635 items = None
636 break
637 n = len(tmp)
638 if n > 1:
639 write(MARK)
640 for x in tmp:
641 save(x)
642 write(APPENDS)
643 elif n:
644 save(tmp[0])
645 write(APPEND)
646 # else tmp is empty, and we're done
647
Guido van Rossum3a41c612003-01-28 15:10:22 +0000648 def save_dict(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000649 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000650
Tim Petersc32d8242001-04-10 02:48:53 +0000651 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000652 write(EMPTY_DICT)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000653 else: # proto 0 -- can't use EMPTY_DICT
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000654 write(MARK + DICT)
655
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000656 self.memoize(obj)
657 self._batch_setitems(obj.iteritems())
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000658
659 dispatch[DictionaryType] = save_dict
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000660 if not PyStringMap is None:
661 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000662
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000663 def _batch_setitems(self, items):
664 # Helper to batch up SETITEMS sequences; proto >= 1 only
665 save = self.save
666 write = self.write
667
668 if not self.bin:
669 for k, v in items:
670 save(k)
671 save(v)
672 write(SETITEM)
673 return
674
675 r = xrange(self._BATCHSIZE)
676 while items is not None:
677 tmp = []
678 for i in r:
679 try:
680 tmp.append(items.next())
681 except StopIteration:
682 items = None
683 break
684 n = len(tmp)
685 if n > 1:
686 write(MARK)
687 for k, v in tmp:
688 save(k)
689 save(v)
690 write(SETITEMS)
691 elif n:
692 k, v = tmp[0]
693 save(k)
694 save(v)
695 write(SETITEM)
696 # else tmp is empty, and we're done
697
Guido van Rossum3a41c612003-01-28 15:10:22 +0000698 def save_inst(self, obj):
699 cls = obj.__class__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000700
701 memo = self.memo
702 write = self.write
703 save = self.save
704
Guido van Rossum3a41c612003-01-28 15:10:22 +0000705 if hasattr(obj, '__getinitargs__'):
706 args = obj.__getinitargs__()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000707 len(args) # XXX Assert it's a sequence
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000708 _keep_alive(args, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000709 else:
710 args = ()
711
712 write(MARK)
713
Tim Petersc32d8242001-04-10 02:48:53 +0000714 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000715 save(cls)
Tim Peters3b769832003-01-28 03:51:36 +0000716 for arg in args:
717 save(arg)
718 write(OBJ)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000719 else:
Tim Peters3b769832003-01-28 03:51:36 +0000720 for arg in args:
721 save(arg)
722 write(INST + cls.__module__ + '\n' + cls.__name__ + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000723
Guido van Rossum3a41c612003-01-28 15:10:22 +0000724 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000725
726 try:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000727 getstate = obj.__getstate__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000728 except AttributeError:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000729 stuff = obj.__dict__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000730 else:
731 stuff = getstate()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000732 _keep_alive(stuff, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000733 save(stuff)
734 write(BUILD)
Tim Peters3b769832003-01-28 03:51:36 +0000735
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000736 dispatch[InstanceType] = save_inst
737
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000738 def save_global(self, obj, name=None, pack=struct.pack):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000739 write = self.write
740 memo = self.memo
741
Tim Petersc32d8242001-04-10 02:48:53 +0000742 if name is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000743 name = obj.__name__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000744
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000745 module = getattr(obj, "__module__", None)
746 if module is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000747 module = whichmodule(obj, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000748
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000749 try:
750 __import__(module)
751 mod = sys.modules[module]
752 klass = getattr(mod, name)
753 except (ImportError, KeyError, AttributeError):
754 raise PicklingError(
755 "Can't pickle %r: it's not found as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000756 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000757 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000758 if klass is not obj:
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000759 raise PicklingError(
760 "Can't pickle %r: it's not the same object as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000761 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000762
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000763 if self.proto >= 2:
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000764 code = _extension_registry.get((module, name))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000765 if code:
766 assert code > 0
767 if code <= 0xff:
768 write(EXT1 + chr(code))
769 elif code <= 0xffff:
Guido van Rossumba884f32003-01-29 20:14:23 +0000770 write("%c%c%c" % (EXT2, code&0xff, code>>8))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000771 else:
772 write(EXT4 + pack("<i", code))
773 return
774
Tim Peters518df0d2003-01-28 01:00:38 +0000775 write(GLOBAL + module + '\n' + name + '\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000776 self.memoize(obj)
Tim Peters3b769832003-01-28 03:51:36 +0000777
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000778 dispatch[ClassType] = save_global
779 dispatch[FunctionType] = save_global
780 dispatch[BuiltinFunctionType] = save_global
Tim Peters6d6c1a32001-08-02 04:15:00 +0000781 dispatch[TypeType] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000782
Guido van Rossum1be31752003-01-28 15:19:53 +0000783# Pickling helpers
Guido van Rossuma48061a1995-01-10 00:31:14 +0000784
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000785def _keep_alive(x, memo):
786 """Keeps a reference to the object x in the memo.
787
788 Because we remember objects by their id, we have
789 to assure that possibly temporary objects are kept
790 alive by referencing them.
791 We store a reference at the id of the memo, which should
792 normally not be used unless someone tries to deepcopy
793 the memo itself...
794 """
795 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000796 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000797 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000798 # aha, this is the first one :-)
799 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000800
801
Tim Petersc0c12b52003-01-29 00:56:17 +0000802# A cache for whichmodule(), mapping a function object to the name of
803# the module in which the function was found.
804
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000805classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000806
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000807def whichmodule(func, funcname):
808 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000809
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000810 Search sys.modules for the module.
811 Cache in classmap.
812 Return a module name.
Tim Petersc0c12b52003-01-29 00:56:17 +0000813 If the function cannot be found, return "__main__".
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000814 """
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000815 # Python functions should always get an __module__ from their globals.
816 mod = getattr(func, "__module__", None)
817 if mod is not None:
818 return mod
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000819 if func in classmap:
820 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000821
822 for name, module in sys.modules.items():
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000823 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000824 continue # skip dummy package entries
Jeremy Hyltoncc1fccb2003-02-06 16:23:01 +0000825 if name != '__main__' and getattr(module, funcname, None) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000826 break
827 else:
828 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000829 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000830 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000831
832
Guido van Rossum1be31752003-01-28 15:19:53 +0000833# Unpickling machinery
834
Guido van Rossuma48061a1995-01-10 00:31:14 +0000835class Unpickler:
836
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000837 def __init__(self, file):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000838 """This takes a file-like object for reading a pickle data stream.
839
Tim Peters5bd2a792003-02-01 16:45:06 +0000840 The protocol version of the pickle is detected automatically, so no
841 proto argument is needed.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000842
843 The file-like object must have two methods, a read() method that
844 takes an integer argument, and a readline() method that requires no
845 arguments. Both methods should return a string. Thus file-like
846 object can be a file object opened for reading, a StringIO object,
847 or any other custom object that meets this interface.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000848 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000849 self.readline = file.readline
850 self.read = file.read
851 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000852
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000853 def load(self):
Guido van Rossum3a41c612003-01-28 15:10:22 +0000854 """Read a pickled object representation from the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000855
Guido van Rossum3a41c612003-01-28 15:10:22 +0000856 Return the reconstituted object hierarchy specified in the file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000857 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000858 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000859 self.stack = []
860 self.append = self.stack.append
861 read = self.read
862 dispatch = self.dispatch
863 try:
864 while 1:
865 key = read(1)
866 dispatch[key](self)
Guido van Rossumff871742000-12-13 18:11:56 +0000867 except _Stop, stopinst:
868 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000869
Tim Petersc23d18a2003-01-28 01:41:51 +0000870 # Return largest index k such that self.stack[k] is self.mark.
871 # If the stack doesn't contain a mark, eventually raises IndexError.
872 # This could be sped by maintaining another stack, of indices at which
873 # the mark appears. For that matter, the latter stack would suffice,
874 # and we wouldn't need to push mark objects on self.stack at all.
875 # Doing so is probably a good thing, though, since if the pickle is
876 # corrupt (or hostile) we may get a clue from finding self.mark embedded
877 # in unpickled objects.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000878 def marker(self):
879 stack = self.stack
880 mark = self.mark
881 k = len(stack)-1
882 while stack[k] is not mark: k = k-1
883 return k
884
885 dispatch = {}
886
887 def load_eof(self):
888 raise EOFError
889 dispatch[''] = load_eof
890
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000891 def load_proto(self):
892 proto = ord(self.read(1))
893 if not 0 <= proto <= 2:
894 raise ValueError, "unsupported pickle protocol: %d" % proto
895 dispatch[PROTO] = load_proto
896
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000897 def load_persid(self):
898 pid = self.readline()[:-1]
899 self.append(self.persistent_load(pid))
900 dispatch[PERSID] = load_persid
901
902 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000903 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000904 self.append(self.persistent_load(pid))
905 dispatch[BINPERSID] = load_binpersid
906
907 def load_none(self):
908 self.append(None)
909 dispatch[NONE] = load_none
910
Guido van Rossum7d97d312003-01-28 04:25:27 +0000911 def load_false(self):
912 self.append(False)
913 dispatch[NEWFALSE] = load_false
914
915 def load_true(self):
916 self.append(True)
917 dispatch[NEWTRUE] = load_true
918
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000919 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000920 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000921 if data == FALSE[1:]:
922 val = False
923 elif data == TRUE[1:]:
924 val = True
925 else:
926 try:
927 val = int(data)
928 except ValueError:
929 val = long(data)
930 self.append(val)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000931 dispatch[INT] = load_int
932
933 def load_binint(self):
934 self.append(mloads('i' + self.read(4)))
935 dispatch[BININT] = load_binint
936
937 def load_binint1(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000938 self.append(ord(self.read(1)))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000939 dispatch[BININT1] = load_binint1
940
941 def load_binint2(self):
942 self.append(mloads('i' + self.read(2) + '\000\000'))
943 dispatch[BININT2] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000944
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000945 def load_long(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000946 self.append(long(self.readline()[:-1], 0))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000947 dispatch[LONG] = load_long
948
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000949 def load_long1(self):
950 n = ord(self.read(1))
951 bytes = self.read(n)
Tim Petersee1a53c2003-02-02 02:57:53 +0000952 self.append(decode_long(bytes))
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000953 dispatch[LONG1] = load_long1
954
955 def load_long4(self):
956 n = mloads('i' + self.read(4))
957 bytes = self.read(n)
Tim Petersee1a53c2003-02-02 02:57:53 +0000958 self.append(decode_long(bytes))
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000959 dispatch[LONG4] = load_long4
960
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000961 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000962 self.append(float(self.readline()[:-1]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000963 dispatch[FLOAT] = load_float
964
Guido van Rossumd3703791998-10-22 20:15:36 +0000965 def load_binfloat(self, unpack=struct.unpack):
966 self.append(unpack('>d', self.read(8))[0])
967 dispatch[BINFLOAT] = load_binfloat
968
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000969 def load_string(self):
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000970 rep = self.readline()[:-1]
Tim Petersad5a7712003-01-28 16:23:33 +0000971 for q in "\"'": # double or single quote
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000972 if rep.startswith(q):
973 if not rep.endswith(q):
974 raise ValueError, "insecure string pickle"
975 rep = rep[len(q):-len(q)]
976 break
977 else:
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000978 raise ValueError, "insecure string pickle"
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000979 self.append(rep.decode("string-escape"))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000980 dispatch[STRING] = load_string
981
982 def load_binstring(self):
983 len = mloads('i' + self.read(4))
984 self.append(self.read(len))
985 dispatch[BINSTRING] = load_binstring
986
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000987 def load_unicode(self):
988 self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
989 dispatch[UNICODE] = load_unicode
990
991 def load_binunicode(self):
992 len = mloads('i' + self.read(4))
993 self.append(unicode(self.read(len),'utf-8'))
994 dispatch[BINUNICODE] = load_binunicode
995
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000996 def load_short_binstring(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000997 len = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000998 self.append(self.read(len))
999 dispatch[SHORT_BINSTRING] = load_short_binstring
1000
1001 def load_tuple(self):
1002 k = self.marker()
1003 self.stack[k:] = [tuple(self.stack[k+1:])]
1004 dispatch[TUPLE] = load_tuple
1005
1006 def load_empty_tuple(self):
1007 self.stack.append(())
1008 dispatch[EMPTY_TUPLE] = load_empty_tuple
1009
Guido van Rossum44f0ea52003-01-28 04:14:51 +00001010 def load_tuple1(self):
1011 self.stack[-1] = (self.stack[-1],)
1012 dispatch[TUPLE1] = load_tuple1
1013
1014 def load_tuple2(self):
1015 self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
1016 dispatch[TUPLE2] = load_tuple2
1017
1018 def load_tuple3(self):
1019 self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
1020 dispatch[TUPLE3] = load_tuple3
1021
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001022 def load_empty_list(self):
1023 self.stack.append([])
1024 dispatch[EMPTY_LIST] = load_empty_list
1025
1026 def load_empty_dictionary(self):
1027 self.stack.append({})
1028 dispatch[EMPTY_DICT] = load_empty_dictionary
1029
1030 def load_list(self):
1031 k = self.marker()
1032 self.stack[k:] = [self.stack[k+1:]]
1033 dispatch[LIST] = load_list
1034
1035 def load_dict(self):
1036 k = self.marker()
1037 d = {}
1038 items = self.stack[k+1:]
1039 for i in range(0, len(items), 2):
1040 key = items[i]
1041 value = items[i+1]
1042 d[key] = value
1043 self.stack[k:] = [d]
1044 dispatch[DICT] = load_dict
1045
Tim Petersd01c1e92003-01-30 15:41:46 +00001046 # INST and OBJ differ only in how they get a class object. It's not
1047 # only sensible to do the rest in a common routine, the two routines
1048 # previously diverged and grew different bugs.
1049 # klass is the class to instantiate, and k points to the topmost mark
1050 # object, following which are the arguments for klass.__init__.
1051 def _instantiate(self, klass, k):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001052 args = tuple(self.stack[k+1:])
1053 del self.stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001054 instantiated = 0
Tim Petersd01c1e92003-01-30 15:41:46 +00001055 if (not args and
1056 type(klass) is ClassType and
1057 not hasattr(klass, "__getinitargs__")):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001058 try:
1059 value = _EmptyClass()
1060 value.__class__ = klass
Guido van Rossumb19e2a31998-04-13 18:08:45 +00001061 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001062 except RuntimeError:
1063 # In restricted execution, assignment to inst.__class__ is
1064 # prohibited
1065 pass
1066 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +00001067 try:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001068 value = klass(*args)
Guido van Rossum743d17e1998-09-15 20:25:57 +00001069 except TypeError, err:
1070 raise TypeError, "in constructor for %s: %s" % (
1071 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001072 self.append(value)
Tim Petersd01c1e92003-01-30 15:41:46 +00001073
1074 def load_inst(self):
1075 module = self.readline()[:-1]
1076 name = self.readline()[:-1]
1077 klass = self.find_class(module, name)
1078 self._instantiate(klass, self.marker())
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001079 dispatch[INST] = load_inst
1080
1081 def load_obj(self):
Tim Petersd01c1e92003-01-30 15:41:46 +00001082 # Stack is ... markobject classobject arg1 arg2 ...
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001083 k = self.marker()
Tim Petersd01c1e92003-01-30 15:41:46 +00001084 klass = self.stack.pop(k+1)
1085 self._instantiate(klass, k)
Tim Peters2344fae2001-01-15 00:50:52 +00001086 dispatch[OBJ] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001087
Guido van Rossum3a41c612003-01-28 15:10:22 +00001088 def load_newobj(self):
1089 args = self.stack.pop()
1090 cls = self.stack[-1]
1091 obj = cls.__new__(cls, *args)
Guido van Rossum533dbcf2003-01-28 17:55:05 +00001092 self.stack[-1] = obj
Guido van Rossum3a41c612003-01-28 15:10:22 +00001093 dispatch[NEWOBJ] = load_newobj
1094
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001095 def load_global(self):
1096 module = self.readline()[:-1]
1097 name = self.readline()[:-1]
1098 klass = self.find_class(module, name)
1099 self.append(klass)
1100 dispatch[GLOBAL] = load_global
1101
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001102 def load_ext1(self):
1103 code = ord(self.read(1))
1104 self.get_extension(code)
1105 dispatch[EXT1] = load_ext1
1106
1107 def load_ext2(self):
1108 code = mloads('i' + self.read(2) + '\000\000')
1109 self.get_extension(code)
1110 dispatch[EXT2] = load_ext2
1111
1112 def load_ext4(self):
1113 code = mloads('i' + self.read(4))
1114 self.get_extension(code)
1115 dispatch[EXT4] = load_ext4
1116
1117 def get_extension(self, code):
1118 nil = []
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001119 obj = _extension_cache.get(code, nil)
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001120 if obj is not nil:
1121 self.append(obj)
1122 return
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001123 key = _inverted_registry.get(code)
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001124 if not key:
1125 raise ValueError("unregistered extension code %d" % code)
1126 obj = self.find_class(*key)
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001127 _extension_cache[code] = obj
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001128 self.append(obj)
1129
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001130 def find_class(self, module, name):
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001131 # Subclasses may override this
Barry Warsawbf4d9592001-11-15 23:42:58 +00001132 __import__(module)
1133 mod = sys.modules[module]
1134 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001135 return klass
1136
1137 def load_reduce(self):
1138 stack = self.stack
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001139 args = stack.pop()
1140 func = stack[-1]
1141 if args is None:
Guido van Rossumbc64e222003-01-28 16:34:19 +00001142 # A hack for Jim Fulton's ExtensionClass, now deprecated
1143 warnings.warn("__basicnew__ special case is deprecated",
Tim Peters8ac14952002-05-23 15:15:30 +00001144 DeprecationWarning)
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001145 value = func.__basicnew__()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001146 else:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001147 value = func(*args)
1148 stack[-1] = value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001149 dispatch[REDUCE] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +00001150
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001151 def load_pop(self):
1152 del self.stack[-1]
1153 dispatch[POP] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +00001154
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001155 def load_pop_mark(self):
1156 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001157 del self.stack[k:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001158 dispatch[POP_MARK] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001159
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001160 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +00001161 self.append(self.stack[-1])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001162 dispatch[DUP] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +00001163
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001164 def load_get(self):
1165 self.append(self.memo[self.readline()[:-1]])
1166 dispatch[GET] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +00001167
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001168 def load_binget(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001169 i = ord(self.read(1))
Walter Dörwald70a6b492004-02-12 17:35:32 +00001170 self.append(self.memo[repr(i)])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001171 dispatch[BINGET] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001172
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001173 def load_long_binget(self):
1174 i = mloads('i' + self.read(4))
Walter Dörwald70a6b492004-02-12 17:35:32 +00001175 self.append(self.memo[repr(i)])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001176 dispatch[LONG_BINGET] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001177
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001178 def load_put(self):
1179 self.memo[self.readline()[:-1]] = self.stack[-1]
1180 dispatch[PUT] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +00001181
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001182 def load_binput(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001183 i = ord(self.read(1))
Walter Dörwald70a6b492004-02-12 17:35:32 +00001184 self.memo[repr(i)] = self.stack[-1]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001185 dispatch[BINPUT] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001186
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001187 def load_long_binput(self):
1188 i = mloads('i' + self.read(4))
Walter Dörwald70a6b492004-02-12 17:35:32 +00001189 self.memo[repr(i)] = self.stack[-1]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001190 dispatch[LONG_BINPUT] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001191
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001192 def load_append(self):
1193 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001194 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001195 list = stack[-1]
1196 list.append(value)
1197 dispatch[APPEND] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +00001198
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001199 def load_appends(self):
1200 stack = self.stack
1201 mark = self.marker()
1202 list = stack[mark - 1]
Tim Peters209ad952003-01-28 01:44:45 +00001203 list.extend(stack[mark + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001204 del stack[mark:]
1205 dispatch[APPENDS] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +00001206
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001207 def load_setitem(self):
1208 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001209 value = stack.pop()
1210 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001211 dict = stack[-1]
1212 dict[key] = value
1213 dispatch[SETITEM] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001214
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001215 def load_setitems(self):
1216 stack = self.stack
1217 mark = self.marker()
1218 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001219 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001220 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001221
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001222 del stack[mark:]
1223 dispatch[SETITEMS] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001224
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001225 def load_build(self):
1226 stack = self.stack
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001227 state = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001228 inst = stack[-1]
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001229 setstate = getattr(inst, "__setstate__", None)
1230 if setstate:
1231 setstate(state)
1232 return
1233 slotstate = None
1234 if isinstance(state, tuple) and len(state) == 2:
1235 state, slotstate = state
1236 if state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001237 try:
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001238 inst.__dict__.update(state)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001239 except RuntimeError:
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001240 # XXX In restricted execution, the instance's __dict__
1241 # is not accessible. Use the old way of unpickling
1242 # the instance variables. This is a semantic
1243 # difference when unpickling in restricted
1244 # vs. unrestricted modes.
Tim Peters080c88b2003-02-15 03:01:11 +00001245 # Note, however, that cPickle has never tried to do the
1246 # .update() business, and always uses
1247 # PyObject_SetItem(inst.__dict__, key, value) in a
1248 # loop over state.items().
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001249 for k, v in state.items():
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001250 setattr(inst, k, v)
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001251 if slotstate:
1252 for k, v in slotstate.items():
1253 setattr(inst, k, v)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001254 dispatch[BUILD] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001255
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001256 def load_mark(self):
1257 self.append(self.mark)
1258 dispatch[MARK] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001259
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001260 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001261 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001262 raise _Stop(value)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001263 dispatch[STOP] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001264
Guido van Rossume467be61997-12-05 19:42:42 +00001265# Helper class for load_inst/load_obj
1266
1267class _EmptyClass:
1268 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001269
Tim Peters91149822003-01-31 03:43:58 +00001270# Encode/decode longs in linear time.
1271
1272import binascii as _binascii
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001273
1274def encode_long(x):
Tim Peters91149822003-01-31 03:43:58 +00001275 r"""Encode a long to a two's complement little-endian binary string.
Tim Peters4b23f2b2003-01-31 16:43:39 +00001276 Note that 0L is a special case, returning an empty string, to save a
1277 byte in the LONG1 pickling context.
1278
1279 >>> encode_long(0L)
1280 ''
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001281 >>> encode_long(255L)
1282 '\xff\x00'
1283 >>> encode_long(32767L)
1284 '\xff\x7f'
1285 >>> encode_long(-256L)
1286 '\x00\xff'
1287 >>> encode_long(-32768L)
1288 '\x00\x80'
1289 >>> encode_long(-128L)
1290 '\x80'
1291 >>> encode_long(127L)
1292 '\x7f'
1293 >>>
1294 """
Tim Peters91149822003-01-31 03:43:58 +00001295
1296 if x == 0:
Tim Peters4b23f2b2003-01-31 16:43:39 +00001297 return ''
Tim Peters91149822003-01-31 03:43:58 +00001298 if x > 0:
1299 ashex = hex(x)
1300 assert ashex.startswith("0x")
1301 njunkchars = 2 + ashex.endswith('L')
1302 nibbles = len(ashex) - njunkchars
1303 if nibbles & 1:
1304 # need an even # of nibbles for unhexlify
1305 ashex = "0x0" + ashex[2:]
Tim Peters4b23f2b2003-01-31 16:43:39 +00001306 elif int(ashex[2], 16) >= 8:
Tim Peters91149822003-01-31 03:43:58 +00001307 # "looks negative", so need a byte of sign bits
1308 ashex = "0x00" + ashex[2:]
1309 else:
1310 # Build the 256's-complement: (1L << nbytes) + x. The trick is
1311 # to find the number of bytes in linear time (although that should
1312 # really be a constant-time task).
1313 ashex = hex(-x)
1314 assert ashex.startswith("0x")
1315 njunkchars = 2 + ashex.endswith('L')
1316 nibbles = len(ashex) - njunkchars
1317 if nibbles & 1:
Tim Petersee1a53c2003-02-02 02:57:53 +00001318 # Extend to a full byte.
Tim Peters91149822003-01-31 03:43:58 +00001319 nibbles += 1
Tim Peters4b23f2b2003-01-31 16:43:39 +00001320 nbits = nibbles * 4
1321 x += 1L << nbits
Tim Peters91149822003-01-31 03:43:58 +00001322 assert x > 0
1323 ashex = hex(x)
Tim Petersee1a53c2003-02-02 02:57:53 +00001324 njunkchars = 2 + ashex.endswith('L')
1325 newnibbles = len(ashex) - njunkchars
1326 if newnibbles < nibbles:
1327 ashex = "0x" + "0" * (nibbles - newnibbles) + ashex[2:]
1328 if int(ashex[2], 16) < 8:
Tim Peters91149822003-01-31 03:43:58 +00001329 # "looks positive", so need a byte of sign bits
Tim Petersee1a53c2003-02-02 02:57:53 +00001330 ashex = "0xff" + ashex[2:]
Tim Peters91149822003-01-31 03:43:58 +00001331
1332 if ashex.endswith('L'):
1333 ashex = ashex[2:-1]
1334 else:
1335 ashex = ashex[2:]
Tim Petersee1a53c2003-02-02 02:57:53 +00001336 assert len(ashex) & 1 == 0, (x, ashex)
Tim Peters91149822003-01-31 03:43:58 +00001337 binary = _binascii.unhexlify(ashex)
1338 return binary[::-1]
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001339
1340def decode_long(data):
1341 r"""Decode a long from a two's complement little-endian binary string.
Tim Peters4b23f2b2003-01-31 16:43:39 +00001342
1343 >>> decode_long('')
1344 0L
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001345 >>> decode_long("\xff\x00")
1346 255L
1347 >>> decode_long("\xff\x7f")
1348 32767L
1349 >>> decode_long("\x00\xff")
1350 -256L
1351 >>> decode_long("\x00\x80")
1352 -32768L
1353 >>> decode_long("\x80")
1354 -128L
1355 >>> decode_long("\x7f")
1356 127L
1357 """
Tim Peters91149822003-01-31 03:43:58 +00001358
Tim Peters4b23f2b2003-01-31 16:43:39 +00001359 nbytes = len(data)
1360 if nbytes == 0:
1361 return 0L
Tim Peters91149822003-01-31 03:43:58 +00001362 ashex = _binascii.hexlify(data[::-1])
Tim Petersbf2674b2003-02-02 07:51:32 +00001363 n = long(ashex, 16) # quadratic time before Python 2.3; linear now
Tim Peters91149822003-01-31 03:43:58 +00001364 if data[-1] >= '\x80':
Tim Peters4b23f2b2003-01-31 16:43:39 +00001365 n -= 1L << (nbytes * 8)
Tim Peters91149822003-01-31 03:43:58 +00001366 return n
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001367
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001368# Shorthands
1369
Jeremy Hyltonabe2c622001-10-15 21:29:28 +00001370try:
1371 from cStringIO import StringIO
1372except ImportError:
1373 from StringIO import StringIO
Guido van Rossumc7c5e691996-07-22 22:26:07 +00001374
Raymond Hettinger3489cad2004-12-05 05:20:42 +00001375def dump(obj, file, protocol=None):
1376 Pickler(file, protocol).dump(obj)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001377
Raymond Hettinger3489cad2004-12-05 05:20:42 +00001378def dumps(obj, protocol=None):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001379 file = StringIO()
Raymond Hettinger3489cad2004-12-05 05:20:42 +00001380 Pickler(file, protocol).dump(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001381 return file.getvalue()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001382
1383def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001384 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001385
1386def loads(str):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001387 file = StringIO(str)
1388 return Unpickler(file).load()
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001389
1390# Doctest
1391
1392def _test():
1393 import doctest
1394 return doctest.testmod()
1395
1396if __name__ == "__main__":
1397 _test()