blob: 00f5834beaccf4d1d793ceb51bc97bf1bb16e220 [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 Rossum5aac4e62003-02-06 22:57:00 +000030from copy_reg import dispatch_table, _reconstructor, _better_reduce
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
Guido van Rossume0b90422003-01-28 03:17:21 +000050# Why use struct.pack() for pickling but marshal.loads() for
Tim Petersc0c12b52003-01-29 00:56:17 +000051# unpickling? struct.pack() is 40% faster than marshal.dumps(), but
Guido van Rossume0b90422003-01-28 03:17:21 +000052# marshal.loads() is twice as fast as struct.unpack()!
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000053mloads = marshal.loads
Guido van Rossum0c891ce1995-03-14 15:09:05 +000054
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000055class PickleError(Exception):
Neal Norwitzefbb67b2002-05-30 12:12:04 +000056 """A common base class for the other pickling exceptions."""
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000057 pass
58
59class PicklingError(PickleError):
60 """This exception is raised when an unpicklable object is passed to the
61 dump() method.
62
63 """
64 pass
65
66class UnpicklingError(PickleError):
67 """This exception is raised when there is a problem unpickling an object,
68 such as a security violation.
69
70 Note that other exceptions may also be raised during unpickling, including
71 (but not necessarily limited to) AttributeError, EOFError, ImportError,
72 and IndexError.
73
74 """
75 pass
Guido van Rossum7849da81995-03-09 14:08:35 +000076
Tim Petersc0c12b52003-01-29 00:56:17 +000077# An instance of _Stop is raised by Unpickler.load_stop() in response to
78# the STOP opcode, passing the object that is the result of unpickling.
Guido van Rossumff871742000-12-13 18:11:56 +000079class _Stop(Exception):
80 def __init__(self, value):
81 self.value = value
82
Guido van Rossum533dbcf2003-01-28 17:55:05 +000083# Jython has PyStringMap; it's a dict subclass with string keys
Jeremy Hylton2b9d0291998-05-27 22:38:22 +000084try:
85 from org.python.core import PyStringMap
86except ImportError:
87 PyStringMap = None
88
Guido van Rossum533dbcf2003-01-28 17:55:05 +000089# UnicodeType may or may not be exported (normally imported from types)
Guido van Rossumdbb718f2001-09-21 19:22:34 +000090try:
91 UnicodeType
92except NameError:
93 UnicodeType = None
94
Tim Peters22a449a2003-01-27 20:16:36 +000095# Pickle opcodes. See pickletools.py for extensive docs. The listing
96# here is in kind-of alphabetical order of 1-character pickle code.
97# pickletools groups them by purpose.
Guido van Rossumdbb718f2001-09-21 19:22:34 +000098
Tim Peters22a449a2003-01-27 20:16:36 +000099MARK = '(' # push special markobject on stack
100STOP = '.' # every pickle ends with STOP
101POP = '0' # discard topmost stack item
102POP_MARK = '1' # discard stack top through topmost markobject
103DUP = '2' # duplicate top stack item
104FLOAT = 'F' # push float object; decimal string argument
105INT = 'I' # push integer or bool; decimal string argument
106BININT = 'J' # push four-byte signed int
107BININT1 = 'K' # push 1-byte unsigned int
108LONG = 'L' # push long; decimal string argument
109BININT2 = 'M' # push 2-byte unsigned int
110NONE = 'N' # push None
111PERSID = 'P' # push persistent object; id is taken from string arg
112BINPERSID = 'Q' # " " " ; " " " " stack
113REDUCE = 'R' # apply callable to argtuple, both on stack
114STRING = 'S' # push string; NL-terminated string argument
115BINSTRING = 'T' # push string; counted binary string argument
116SHORT_BINSTRING = 'U' # " " ; " " " " < 256 bytes
117UNICODE = 'V' # push Unicode string; raw-unicode-escaped'd argument
118BINUNICODE = 'X' # " " " ; counted UTF-8 string argument
119APPEND = 'a' # append stack top to list below it
120BUILD = 'b' # call __setstate__ or __dict__.update()
121GLOBAL = 'c' # push self.find_class(modname, name); 2 string args
122DICT = 'd' # build a dict from stack items
123EMPTY_DICT = '}' # push empty dict
124APPENDS = 'e' # extend list on stack by topmost stack slice
125GET = 'g' # push item from memo on stack; index is string arg
126BINGET = 'h' # " " " " " " ; " " 1-byte arg
127INST = 'i' # build & push class instance
128LONG_BINGET = 'j' # push item from memo on stack; index is 4-byte arg
129LIST = 'l' # build list from topmost stack items
130EMPTY_LIST = ']' # push empty list
131OBJ = 'o' # build & push class instance
132PUT = 'p' # store stack top in memo; index is string arg
133BINPUT = 'q' # " " " " " ; " " 1-byte arg
134LONG_BINPUT = 'r' # " " " " " ; " " 4-byte arg
135SETITEM = 's' # add key+value pair to dict
136TUPLE = 't' # build tuple from topmost stack items
137EMPTY_TUPLE = ')' # push empty tuple
138SETITEMS = 'u' # modify dict by adding topmost key+value pairs
139BINFLOAT = 'G' # push float; arg is 8-byte float encoding
140
141TRUE = 'I01\n' # not an opcode; see INT docs in pickletools.py
142FALSE = 'I00\n' # not an opcode; see INT docs in pickletools.py
Guido van Rossum77f6a652002-04-03 22:41:51 +0000143
Guido van Rossum586c9e82003-01-29 06:16:12 +0000144# Protocol 2
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000145
Tim Peterse1054782003-01-28 00:22:12 +0000146PROTO = '\x80' # identify pickle protocol
147NEWOBJ = '\x81' # build object by applying cls.__new__ to argtuple
148EXT1 = '\x82' # push object from extension registry; 1-byte index
149EXT2 = '\x83' # ditto, but 2-byte index
150EXT4 = '\x84' # ditto, but 4-byte index
151TUPLE1 = '\x85' # build 1-tuple from stack top
152TUPLE2 = '\x86' # build 2-tuple from two topmost stack items
153TUPLE3 = '\x87' # build 3-tuple from three topmost stack items
154NEWTRUE = '\x88' # push True
155NEWFALSE = '\x89' # push False
156LONG1 = '\x8a' # push long from < 256 bytes
157LONG4 = '\x8b' # push really big long
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000158
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000159_tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3]
160
Guido van Rossuma48061a1995-01-10 00:31:14 +0000161
Skip Montanaro23bafc62001-02-18 03:10:09 +0000162__all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
Neal Norwitzd5ba4ae2002-02-11 18:12:06 +0000163del x
Skip Montanaro23bafc62001-02-18 03:10:09 +0000164
Guido van Rossum1be31752003-01-28 15:19:53 +0000165
166# Pickling machinery
167
Guido van Rossuma48061a1995-01-10 00:31:14 +0000168class Pickler:
169
Guido van Rossumcf117b02003-02-09 17:19:41 +0000170 def __init__(self, file, protocol=None, bin=None):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000171 """This takes a file-like object for writing a pickle data stream.
172
Guido van Rossumcf117b02003-02-09 17:19:41 +0000173 The optional protocol argument tells the pickler to use the
174 given protocol; supported protocols are 0, 1, 2. The default
Guido van Rossum7eff63a2003-01-31 19:42:31 +0000175 protocol is 0, to be backwards compatible. (Protocol 0 is the
176 only protocol that can be written to a file opened in text
Tim Peters5bd2a792003-02-01 16:45:06 +0000177 mode and read back successfully. When using a protocol higher
178 than 0, make sure the file is opened in binary mode, both when
179 pickling and unpickling.)
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000180
181 Protocol 1 is more efficient than protocol 0; protocol 2 is
Guido van Rossum7eff63a2003-01-31 19:42:31 +0000182 more efficient than protocol 1.
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000183
Guido van Rossum7eff63a2003-01-31 19:42:31 +0000184 Specifying a negative protocol version selects the highest
Tim Peters5bd2a792003-02-01 16:45:06 +0000185 protocol version supported. The higher the protocol used, the
186 more recent the version of Python needed to read the pickle
187 produced.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000188
189 The file parameter must have a write() method that accepts a single
190 string argument. It can thus be an open file object, a StringIO
191 object, or any other custom object that meets this interface.
192
193 """
Guido van Rossumcf117b02003-02-09 17:19:41 +0000194 if protocol is not None and bin is not None:
195 raise ValueError, "can't specify both 'protocol' and 'bin'"
Guido van Rossum795ea892003-02-03 16:59:48 +0000196 if bin is not None:
197 warnings.warn("The 'bin' argument to Pickler() is deprecated",
198 PendingDeprecationWarning)
Guido van Rossumcf117b02003-02-09 17:19:41 +0000199 protocol = bin
200 if protocol is None:
201 protocol = 0
202 if protocol < 0:
203 protocol = 2
204 elif protocol not in (0, 1, 2):
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000205 raise ValueError, "pickle protocol must be 0, 1 or 2"
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000206 self.write = file.write
207 self.memo = {}
Guido van Rossumcf117b02003-02-09 17:19:41 +0000208 self.proto = int(protocol)
209 self.bin = protocol >= 1
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000210 self.fast = 0
Guido van Rossuma48061a1995-01-10 00:31:14 +0000211
Fred Drake7f781c92002-05-01 20:33:53 +0000212 def clear_memo(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000213 """Clears the pickler's "memo".
214
215 The memo is the data structure that remembers which objects the
Tim Petersb377f8a2003-01-28 00:23:36 +0000216 pickler has already seen, so that shared or recursive objects are
217 pickled by reference and not by value. This method is useful when
218 re-using picklers.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000219
220 """
Fred Drake7f781c92002-05-01 20:33:53 +0000221 self.memo.clear()
222
Guido van Rossum3a41c612003-01-28 15:10:22 +0000223 def dump(self, obj):
Tim Peters5bd2a792003-02-01 16:45:06 +0000224 """Write a pickled representation of obj to the open file."""
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000225 if self.proto >= 2:
226 self.write(PROTO + chr(self.proto))
Guido van Rossum3a41c612003-01-28 15:10:22 +0000227 self.save(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000228 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000229
Jeremy Hylton3422c992003-01-24 19:29:52 +0000230 def memoize(self, obj):
231 """Store an object in the memo."""
232
Tim Peterse46b73f2003-01-27 21:22:10 +0000233 # The Pickler memo is a dictionary mapping object ids to 2-tuples
234 # that contain the Unpickler memo key and the object being memoized.
235 # The memo key is written to the pickle and will become
Jeremy Hylton3422c992003-01-24 19:29:52 +0000236 # the key in the Unpickler's memo. The object is stored in the
Tim Peterse46b73f2003-01-27 21:22:10 +0000237 # Pickler memo so that transient objects are kept alive during
238 # pickling.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000239
Tim Peterse46b73f2003-01-27 21:22:10 +0000240 # The use of the Unpickler memo length as the memo key is just a
241 # convention. The only requirement is that the memo values be unique.
242 # But there appears no advantage to any other scheme, and this
Tim Peterscbd0a322003-01-28 00:24:43 +0000243 # scheme allows the Unpickler memo to be implemented as a plain (but
Tim Peterse46b73f2003-01-27 21:22:10 +0000244 # growable) array, indexed by memo key.
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000245 if self.fast:
246 return
Guido van Rossum9b40e802003-01-30 06:37:41 +0000247 assert id(obj) not in self.memo
Jeremy Hylton3422c992003-01-24 19:29:52 +0000248 memo_len = len(self.memo)
249 self.write(self.put(memo_len))
Tim Peters518df0d2003-01-28 01:00:38 +0000250 self.memo[id(obj)] = memo_len, obj
Jeremy Hylton3422c992003-01-24 19:29:52 +0000251
Tim Petersbb38e302003-01-27 21:25:41 +0000252 # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000253 def put(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000254 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000255 if i < 256:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000256 return BINPUT + chr(i)
257 else:
258 return LONG_BINPUT + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000259
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000260 return PUT + `i` + '\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000261
Tim Petersbb38e302003-01-27 21:25:41 +0000262 # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000263 def get(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000264 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000265 if i < 256:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000266 return BINGET + chr(i)
267 else:
268 return LONG_BINGET + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000269
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000270 return GET + `i` + '\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000271
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000272 def save(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000273 # Check for persistent id (defined by a subclass)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000274 pid = self.persistent_id(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000275 if pid:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000276 self.save_pers(pid)
277 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000278
Guido van Rossumbc64e222003-01-28 16:34:19 +0000279 # Check the memo
280 x = self.memo.get(id(obj))
281 if x:
282 self.write(self.get(x[0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000283 return
284
Guido van Rossumbc64e222003-01-28 16:34:19 +0000285 # Check the type dispatch table
Guido van Rossum3a41c612003-01-28 15:10:22 +0000286 t = type(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000287 f = self.dispatch.get(t)
288 if f:
289 f(self, obj) # Call unbound method with explicit self
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000290 return
291
Guido van Rossumbc64e222003-01-28 16:34:19 +0000292 # Check for a class with a custom metaclass; treat as regular class
Tim Petersb32a8312003-01-28 00:48:09 +0000293 try:
294 issc = issubclass(t, TypeType)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000295 except TypeError: # t is not a class (old Boost; see SF #502085)
Tim Petersb32a8312003-01-28 00:48:09 +0000296 issc = 0
297 if issc:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000298 self.save_global(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000299 return
300
Guido van Rossumbc64e222003-01-28 16:34:19 +0000301 # Check copy_reg.dispatch_table
302 reduce = dispatch_table.get(t)
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000303 if not reduce:
304 # Check for a __reduce__ method.
305 # Subtle: get the unbound method from the class, so that
306 # protocol 2 can override the default __reduce__ that all
307 # classes inherit from object. This has the added
308 # advantage that the call always has the form reduce(obj)
309 reduce = getattr(t, "__reduce__", None)
310 if self.proto >= 2:
311 # Protocol 2 can do better than the default __reduce__
312 if reduce is object.__reduce__:
Guido van Rossum5aac4e62003-02-06 22:57:00 +0000313 reduce = _better_reduce
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000314 if not reduce:
Guido van Rossumbc64e222003-01-28 16:34:19 +0000315 raise PicklingError("Can't pickle %r object: %r" %
316 (t.__name__, obj))
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000317 rv = reduce(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000318
Guido van Rossumbc64e222003-01-28 16:34:19 +0000319 # Check for string returned by reduce(), meaning "save as global"
320 if type(rv) is StringType:
321 self.save_global(obj, rv)
Tim Petersb32a8312003-01-28 00:48:09 +0000322 return
323
Guido van Rossumbc64e222003-01-28 16:34:19 +0000324 # Assert that reduce() returned a tuple
325 if type(rv) is not TupleType:
326 raise PicklingError("%s must return string or tuple" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000327
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000328 # Assert that it returned an appropriately sized tuple
Guido van Rossumbc64e222003-01-28 16:34:19 +0000329 l = len(rv)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000330 if not (2 <= l <= 5):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000331 raise PicklingError("Tuple returned by %s must have "
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000332 "two to five elements" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000333
Guido van Rossumbc64e222003-01-28 16:34:19 +0000334 # Save the reduce() output and finally memoize the object
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000335 self.save_reduce(obj=obj, *rv)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000336
Guido van Rossum3a41c612003-01-28 15:10:22 +0000337 def persistent_id(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000338 # This exists so a subclass can override it
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000339 return None
340
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000341 def save_pers(self, pid):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000342 # Save a persistent id reference
Tim Petersbd1cdb92003-01-28 01:03:10 +0000343 if self.bin:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000344 self.save(pid)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000345 self.write(BINPERSID)
Tim Petersbd1cdb92003-01-28 01:03:10 +0000346 else:
347 self.write(PERSID + str(pid) + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000348
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000349 def save_reduce(self, func, args, state=None,
350 listitems=None, dictitems=None, obj=None):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000351 # This API is be called by some subclasses
352
353 # Assert that args is a tuple or None
354 if not isinstance(args, TupleType):
355 if args is None:
356 # A hack for Jim Fulton's ExtensionClass, now deprecated.
357 # See load_reduce()
358 warnings.warn("__basicnew__ special case is deprecated",
359 DeprecationWarning)
360 else:
361 raise PicklingError(
362 "args from reduce() should be a tuple")
363
364 # Assert that func is callable
365 if not callable(func):
366 raise PicklingError("func from reduce should be callable")
367
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000368 save = self.save
Guido van Rossumbc64e222003-01-28 16:34:19 +0000369 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000370
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000371 # Protocol 2 special case: if func's name is __newobj__, use NEWOBJ
372 if self.proto >= 2 and getattr(func, "__name__", "") == "__newobj__":
373 # A __reduce__ implementation can direct protocol 2 to
374 # use the more efficient NEWOBJ opcode, while still
375 # allowing protocol 0 and 1 to work normally. For this to
376 # work, the function returned by __reduce__ should be
377 # called __newobj__, and its first argument should be a
378 # new-style class. The implementation for __newobj__
379 # should be as follows, although pickle has no way to
380 # verify this:
381 #
382 # def __newobj__(cls, *args):
383 # return cls.__new__(cls, *args)
384 #
385 # Protocols 0 and 1 will pickle a reference to __newobj__,
386 # while protocol 2 (and above) will pickle a reference to
387 # cls, the remaining args tuple, and the NEWOBJ code,
388 # which calls cls.__new__(cls, *args) at unpickling time
389 # (see load_newobj below). If __reduce__ returns a
390 # three-tuple, the state from the third tuple item will be
391 # pickled regardless of the protocol, calling __setstate__
392 # at unpickling time (see load_build below).
393 #
394 # Note that no standard __newobj__ implementation exists;
395 # you have to provide your own. This is to enforce
396 # compatibility with Python 2.2 (pickles written using
397 # protocol 0 or 1 in Python 2.3 should be unpicklable by
398 # Python 2.2).
399 cls = args[0]
400 if not hasattr(cls, "__new__"):
401 raise PicklingError(
402 "args[0] from __newobj__ args has no __new__")
Guido van Rossumf7f45172003-01-31 17:17:49 +0000403 if obj is not None and cls is not obj.__class__:
404 raise PicklingError(
405 "args[0] from __newobj__ args has the wrong class")
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000406 args = args[1:]
407 save(cls)
408 save(args)
409 write(NEWOBJ)
410 else:
411 save(func)
412 save(args)
413 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000414
Guido van Rossumf7f45172003-01-31 17:17:49 +0000415 if obj is not None:
416 self.memoize(obj)
417
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000418 # More new special cases (that work with older protocols as
419 # well): when __reduce__ returns a tuple with 4 or 5 items,
420 # the 4th and 5th item should be iterators that provide list
421 # items and dict items (as (key, value) tuples), or None.
422
423 if listitems is not None:
424 self._batch_appends(listitems)
425
426 if dictitems is not None:
427 self._batch_setitems(dictitems)
428
Tim Petersc32d8242001-04-10 02:48:53 +0000429 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000430 save(state)
431 write(BUILD)
432
Guido van Rossumbc64e222003-01-28 16:34:19 +0000433 # Methods below this point are dispatched through the dispatch table
434
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000435 dispatch = {}
436
Guido van Rossum3a41c612003-01-28 15:10:22 +0000437 def save_none(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000438 self.write(NONE)
439 dispatch[NoneType] = save_none
440
Guido van Rossum3a41c612003-01-28 15:10:22 +0000441 def save_bool(self, obj):
Guido van Rossum7d97d312003-01-28 04:25:27 +0000442 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000443 self.write(obj and NEWTRUE or NEWFALSE)
Guido van Rossum7d97d312003-01-28 04:25:27 +0000444 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000445 self.write(obj and TRUE or FALSE)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000446 dispatch[bool] = save_bool
447
Guido van Rossum3a41c612003-01-28 15:10:22 +0000448 def save_int(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000449 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000450 # If the int is small enough to fit in a signed 4-byte 2's-comp
451 # format, we can store it more efficiently than the general
452 # case.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000453 # First one- and two-byte unsigned ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000454 if obj >= 0:
455 if obj <= 0xff:
456 self.write(BININT1 + chr(obj))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000457 return
Guido van Rossum3a41c612003-01-28 15:10:22 +0000458 if obj <= 0xffff:
Guido van Rossumba884f32003-01-29 20:14:23 +0000459 self.write("%c%c%c" % (BININT2, obj&0xff, obj>>8))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000460 return
461 # Next check for 4-byte signed ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000462 high_bits = obj >> 31 # note that Python shift sign-extends
Tim Petersd95c2df2003-01-28 03:41:54 +0000463 if high_bits == 0 or high_bits == -1:
Tim Peters44714002001-04-10 05:02:52 +0000464 # All high bits are copies of bit 2**31, so the value
465 # fits in a 4-byte signed int.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000466 self.write(BININT + pack("<i", obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000467 return
Tim Peters44714002001-04-10 05:02:52 +0000468 # Text pickle, or int too big to fit in signed 4-byte format.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000469 self.write(INT + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000470 dispatch[IntType] = save_int
471
Guido van Rossum3a41c612003-01-28 15:10:22 +0000472 def save_long(self, obj, pack=struct.pack):
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000473 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000474 bytes = encode_long(obj)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000475 n = len(bytes)
476 if n < 256:
477 self.write(LONG1 + chr(n) + bytes)
478 else:
479 self.write(LONG4 + pack("<i", n) + bytes)
Tim Petersee1a53c2003-02-02 02:57:53 +0000480 return
Guido van Rossum3a41c612003-01-28 15:10:22 +0000481 self.write(LONG + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000482 dispatch[LongType] = save_long
483
Guido van Rossum3a41c612003-01-28 15:10:22 +0000484 def save_float(self, obj, pack=struct.pack):
Guido van Rossumd3703791998-10-22 20:15:36 +0000485 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000486 self.write(BINFLOAT + pack('>d', obj))
Guido van Rossumd3703791998-10-22 20:15:36 +0000487 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000488 self.write(FLOAT + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000489 dispatch[FloatType] = save_float
490
Guido van Rossum3a41c612003-01-28 15:10:22 +0000491 def save_string(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000492 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000493 n = len(obj)
Tim Petersbbf63cd2003-01-27 21:15:36 +0000494 if n < 256:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000495 self.write(SHORT_BINSTRING + chr(n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000496 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000497 self.write(BINSTRING + pack("<i", n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000498 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000499 self.write(STRING + `obj` + '\n')
500 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000501 dispatch[StringType] = save_string
502
Guido van Rossum3a41c612003-01-28 15:10:22 +0000503 def save_unicode(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000504 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000505 encoding = obj.encode('utf-8')
Tim Petersbbf63cd2003-01-27 21:15:36 +0000506 n = len(encoding)
Guido van Rossum5c938d02003-01-28 03:03:08 +0000507 self.write(BINUNICODE + pack("<i", n) + encoding)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000508 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000509 obj = obj.replace("\\", "\\u005c")
510 obj = obj.replace("\n", "\\u000a")
511 self.write(UNICODE + obj.encode('raw-unicode-escape') + '\n')
512 self.memoize(obj)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000513 dispatch[UnicodeType] = save_unicode
514
Guido van Rossum31584cb2001-01-22 14:53:29 +0000515 if StringType == UnicodeType:
516 # This is true for Jython
Guido van Rossum3a41c612003-01-28 15:10:22 +0000517 def save_string(self, obj, pack=struct.pack):
518 unicode = obj.isunicode()
Guido van Rossum31584cb2001-01-22 14:53:29 +0000519
Tim Petersc32d8242001-04-10 02:48:53 +0000520 if self.bin:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000521 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000522 obj = obj.encode("utf-8")
523 l = len(obj)
Tim Petersc32d8242001-04-10 02:48:53 +0000524 if l < 256 and not unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000525 self.write(SHORT_BINSTRING + chr(l) + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000526 else:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000527 s = pack("<i", l)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000528 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000529 self.write(BINUNICODE + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000530 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000531 self.write(BINSTRING + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000532 else:
Tim Peters658cba62001-02-09 20:06:00 +0000533 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000534 obj = obj.replace("\\", "\\u005c")
535 obj = obj.replace("\n", "\\u000a")
536 obj = obj.encode('raw-unicode-escape')
537 self.write(UNICODE + obj + '\n')
Guido van Rossum31584cb2001-01-22 14:53:29 +0000538 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000539 self.write(STRING + `obj` + '\n')
540 self.memoize(obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000541 dispatch[StringType] = save_string
Tim Peters658cba62001-02-09 20:06:00 +0000542
Guido van Rossum3a41c612003-01-28 15:10:22 +0000543 def save_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000544 write = self.write
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000545 proto = self.proto
546
Guido van Rossum3a41c612003-01-28 15:10:22 +0000547 n = len(obj)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000548 if n == 0:
549 if proto:
550 write(EMPTY_TUPLE)
551 else:
552 write(MARK + TUPLE)
Tim Petersd97da802003-01-28 05:48:29 +0000553 return
554
555 save = self.save
556 memo = self.memo
557 if n <= 3 and proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000558 for element in obj:
Tim Petersd97da802003-01-28 05:48:29 +0000559 save(element)
560 # Subtle. Same as in the big comment below.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000561 if id(obj) in memo:
562 get = self.get(memo[id(obj)][0])
Tim Petersd97da802003-01-28 05:48:29 +0000563 write(POP * n + get)
564 else:
565 write(_tuplesize2code[n])
Guido van Rossum3a41c612003-01-28 15:10:22 +0000566 self.memoize(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000567 return
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000568
Tim Peters1d63c9f2003-02-02 20:29:39 +0000569 # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple
Tim Petersff57bff2003-01-28 05:34:53 +0000570 # has more than 3 elements.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000571 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000572 for element in obj:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000573 save(element)
574
Tim Peters1d63c9f2003-02-02 20:29:39 +0000575 if id(obj) in memo:
Tim Petersf558da02003-01-28 02:09:55 +0000576 # Subtle. d was not in memo when we entered save_tuple(), so
577 # the process of saving the tuple's elements must have saved
578 # the tuple itself: the tuple is recursive. The proper action
579 # now is to throw away everything we put on the stack, and
580 # simply GET the tuple (it's already constructed). This check
581 # could have been done in the "for element" loop instead, but
582 # recursive tuples are a rare thing.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000583 get = self.get(memo[id(obj)][0])
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000584 if proto:
Tim Petersf558da02003-01-28 02:09:55 +0000585 write(POP_MARK + get)
586 else: # proto 0 -- POP_MARK not available
Tim Petersd97da802003-01-28 05:48:29 +0000587 write(POP * (n+1) + get)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000588 return
589
Tim Peters1d63c9f2003-02-02 20:29:39 +0000590 # No recursion.
Tim Peters518df0d2003-01-28 01:00:38 +0000591 self.write(TUPLE)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000592 self.memoize(obj)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000593
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000594 dispatch[TupleType] = save_tuple
595
Tim Petersa6ae9a22003-01-28 16:58:41 +0000596 # save_empty_tuple() isn't used by anything in Python 2.3. However, I
597 # found a Pickler subclass in Zope3 that calls it, so it's not harmless
598 # to remove it.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000599 def save_empty_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000600 self.write(EMPTY_TUPLE)
601
Guido van Rossum3a41c612003-01-28 15:10:22 +0000602 def save_list(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000603 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000604
Tim Petersc32d8242001-04-10 02:48:53 +0000605 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000606 write(EMPTY_LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000607 else: # proto 0 -- can't use EMPTY_LIST
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000608 write(MARK + LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000609
610 self.memoize(obj)
611 self._batch_appends(iter(obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000612
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000613 dispatch[ListType] = save_list
614
Tim Peters42f08ac2003-02-11 22:43:24 +0000615 # Keep in synch with cPickle's BATCHSIZE. Nothing will break if it gets
616 # out of synch, though.
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000617 _BATCHSIZE = 1000
618
619 def _batch_appends(self, items):
620 # Helper to batch up APPENDS sequences
621 save = self.save
622 write = self.write
623
624 if not self.bin:
625 for x in items:
626 save(x)
627 write(APPEND)
628 return
629
630 r = xrange(self._BATCHSIZE)
631 while items is not None:
632 tmp = []
633 for i in r:
634 try:
Guido van Rossum5aac4e62003-02-06 22:57:00 +0000635 x = items.next()
636 tmp.append(x)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000637 except StopIteration:
638 items = None
639 break
640 n = len(tmp)
641 if n > 1:
642 write(MARK)
643 for x in tmp:
644 save(x)
645 write(APPENDS)
646 elif n:
647 save(tmp[0])
648 write(APPEND)
649 # else tmp is empty, and we're done
650
Guido van Rossum3a41c612003-01-28 15:10:22 +0000651 def save_dict(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000652 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000653
Tim Petersc32d8242001-04-10 02:48:53 +0000654 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000655 write(EMPTY_DICT)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000656 else: # proto 0 -- can't use EMPTY_DICT
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000657 write(MARK + DICT)
658
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000659 self.memoize(obj)
660 self._batch_setitems(obj.iteritems())
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000661
662 dispatch[DictionaryType] = save_dict
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000663 if not PyStringMap is None:
664 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000665
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000666 def _batch_setitems(self, items):
667 # Helper to batch up SETITEMS sequences; proto >= 1 only
668 save = self.save
669 write = self.write
670
671 if not self.bin:
672 for k, v in items:
673 save(k)
674 save(v)
675 write(SETITEM)
676 return
677
678 r = xrange(self._BATCHSIZE)
679 while items is not None:
680 tmp = []
681 for i in r:
682 try:
683 tmp.append(items.next())
684 except StopIteration:
685 items = None
686 break
687 n = len(tmp)
688 if n > 1:
689 write(MARK)
690 for k, v in tmp:
691 save(k)
692 save(v)
693 write(SETITEMS)
694 elif n:
695 k, v = tmp[0]
696 save(k)
697 save(v)
698 write(SETITEM)
699 # else tmp is empty, and we're done
700
Guido van Rossum3a41c612003-01-28 15:10:22 +0000701 def save_inst(self, obj):
702 cls = obj.__class__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000703
704 memo = self.memo
705 write = self.write
706 save = self.save
707
Guido van Rossum3a41c612003-01-28 15:10:22 +0000708 if hasattr(obj, '__getinitargs__'):
709 args = obj.__getinitargs__()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000710 len(args) # XXX Assert it's a sequence
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000711 _keep_alive(args, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000712 else:
713 args = ()
714
715 write(MARK)
716
Tim Petersc32d8242001-04-10 02:48:53 +0000717 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000718 save(cls)
Tim Peters3b769832003-01-28 03:51:36 +0000719 for arg in args:
720 save(arg)
721 write(OBJ)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000722 else:
Tim Peters3b769832003-01-28 03:51:36 +0000723 for arg in args:
724 save(arg)
725 write(INST + cls.__module__ + '\n' + cls.__name__ + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000726
Guido van Rossum3a41c612003-01-28 15:10:22 +0000727 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000728
729 try:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000730 getstate = obj.__getstate__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000731 except AttributeError:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000732 stuff = obj.__dict__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000733 else:
734 stuff = getstate()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000735 _keep_alive(stuff, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000736 save(stuff)
737 write(BUILD)
Tim Peters3b769832003-01-28 03:51:36 +0000738
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000739 dispatch[InstanceType] = save_inst
740
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000741 def save_global(self, obj, name=None, pack=struct.pack):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000742 write = self.write
743 memo = self.memo
744
Tim Petersc32d8242001-04-10 02:48:53 +0000745 if name is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000746 name = obj.__name__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000747
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000748 module = getattr(obj, "__module__", None)
749 if module is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000750 module = whichmodule(obj, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000751
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000752 try:
753 __import__(module)
754 mod = sys.modules[module]
755 klass = getattr(mod, name)
756 except (ImportError, KeyError, AttributeError):
757 raise PicklingError(
758 "Can't pickle %r: it's not found as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000759 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000760 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000761 if klass is not obj:
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000762 raise PicklingError(
763 "Can't pickle %r: it's not the same object as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000764 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000765
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000766 if self.proto >= 2:
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000767 code = _extension_registry.get((module, name))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000768 if code:
769 assert code > 0
770 if code <= 0xff:
771 write(EXT1 + chr(code))
772 elif code <= 0xffff:
Guido van Rossumba884f32003-01-29 20:14:23 +0000773 write("%c%c%c" % (EXT2, code&0xff, code>>8))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000774 else:
775 write(EXT4 + pack("<i", code))
776 return
777
Tim Peters518df0d2003-01-28 01:00:38 +0000778 write(GLOBAL + module + '\n' + name + '\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000779 self.memoize(obj)
Tim Peters3b769832003-01-28 03:51:36 +0000780
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000781 dispatch[ClassType] = save_global
782 dispatch[FunctionType] = save_global
783 dispatch[BuiltinFunctionType] = save_global
Tim Peters6d6c1a32001-08-02 04:15:00 +0000784 dispatch[TypeType] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000785
Guido van Rossum1be31752003-01-28 15:19:53 +0000786# Pickling helpers
Guido van Rossuma48061a1995-01-10 00:31:14 +0000787
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000788def _keep_alive(x, memo):
789 """Keeps a reference to the object x in the memo.
790
791 Because we remember objects by their id, we have
792 to assure that possibly temporary objects are kept
793 alive by referencing them.
794 We store a reference at the id of the memo, which should
795 normally not be used unless someone tries to deepcopy
796 the memo itself...
797 """
798 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000799 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000800 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000801 # aha, this is the first one :-)
802 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000803
804
Tim Petersc0c12b52003-01-29 00:56:17 +0000805# A cache for whichmodule(), mapping a function object to the name of
806# the module in which the function was found.
807
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000808classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000809
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000810def whichmodule(func, funcname):
811 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000812
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000813 Search sys.modules for the module.
814 Cache in classmap.
815 Return a module name.
Tim Petersc0c12b52003-01-29 00:56:17 +0000816 If the function cannot be found, return "__main__".
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000817 """
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000818 # Python functions should always get an __module__ from their globals.
819 mod = getattr(func, "__module__", None)
820 if mod is not None:
821 return mod
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000822 if func in classmap:
823 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000824
825 for name, module in sys.modules.items():
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000826 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000827 continue # skip dummy package entries
Jeremy Hyltoncc1fccb2003-02-06 16:23:01 +0000828 if name != '__main__' and getattr(module, funcname, None) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000829 break
830 else:
831 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000832 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000833 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000834
835
Guido van Rossum1be31752003-01-28 15:19:53 +0000836# Unpickling machinery
837
Guido van Rossuma48061a1995-01-10 00:31:14 +0000838class Unpickler:
839
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000840 def __init__(self, file):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000841 """This takes a file-like object for reading a pickle data stream.
842
Tim Peters5bd2a792003-02-01 16:45:06 +0000843 The protocol version of the pickle is detected automatically, so no
844 proto argument is needed.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000845
846 The file-like object must have two methods, a read() method that
847 takes an integer argument, and a readline() method that requires no
848 arguments. Both methods should return a string. Thus file-like
849 object can be a file object opened for reading, a StringIO object,
850 or any other custom object that meets this interface.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000851 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000852 self.readline = file.readline
853 self.read = file.read
854 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000855
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000856 def load(self):
Guido van Rossum3a41c612003-01-28 15:10:22 +0000857 """Read a pickled object representation from the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000858
Guido van Rossum3a41c612003-01-28 15:10:22 +0000859 Return the reconstituted object hierarchy specified in the file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000860 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000861 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000862 self.stack = []
863 self.append = self.stack.append
864 read = self.read
865 dispatch = self.dispatch
866 try:
867 while 1:
868 key = read(1)
869 dispatch[key](self)
Guido van Rossumff871742000-12-13 18:11:56 +0000870 except _Stop, stopinst:
871 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000872
Tim Petersc23d18a2003-01-28 01:41:51 +0000873 # Return largest index k such that self.stack[k] is self.mark.
874 # If the stack doesn't contain a mark, eventually raises IndexError.
875 # This could be sped by maintaining another stack, of indices at which
876 # the mark appears. For that matter, the latter stack would suffice,
877 # and we wouldn't need to push mark objects on self.stack at all.
878 # Doing so is probably a good thing, though, since if the pickle is
879 # corrupt (or hostile) we may get a clue from finding self.mark embedded
880 # in unpickled objects.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000881 def marker(self):
882 stack = self.stack
883 mark = self.mark
884 k = len(stack)-1
885 while stack[k] is not mark: k = k-1
886 return k
887
888 dispatch = {}
889
890 def load_eof(self):
891 raise EOFError
892 dispatch[''] = load_eof
893
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000894 def load_proto(self):
895 proto = ord(self.read(1))
896 if not 0 <= proto <= 2:
897 raise ValueError, "unsupported pickle protocol: %d" % proto
898 dispatch[PROTO] = load_proto
899
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000900 def load_persid(self):
901 pid = self.readline()[:-1]
902 self.append(self.persistent_load(pid))
903 dispatch[PERSID] = load_persid
904
905 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000906 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000907 self.append(self.persistent_load(pid))
908 dispatch[BINPERSID] = load_binpersid
909
910 def load_none(self):
911 self.append(None)
912 dispatch[NONE] = load_none
913
Guido van Rossum7d97d312003-01-28 04:25:27 +0000914 def load_false(self):
915 self.append(False)
916 dispatch[NEWFALSE] = load_false
917
918 def load_true(self):
919 self.append(True)
920 dispatch[NEWTRUE] = load_true
921
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000922 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000923 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000924 if data == FALSE[1:]:
925 val = False
926 elif data == TRUE[1:]:
927 val = True
928 else:
929 try:
930 val = int(data)
931 except ValueError:
932 val = long(data)
933 self.append(val)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000934 dispatch[INT] = load_int
935
936 def load_binint(self):
937 self.append(mloads('i' + self.read(4)))
938 dispatch[BININT] = load_binint
939
940 def load_binint1(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000941 self.append(ord(self.read(1)))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000942 dispatch[BININT1] = load_binint1
943
944 def load_binint2(self):
945 self.append(mloads('i' + self.read(2) + '\000\000'))
946 dispatch[BININT2] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000947
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000948 def load_long(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000949 self.append(long(self.readline()[:-1], 0))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000950 dispatch[LONG] = load_long
951
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000952 def load_long1(self):
953 n = ord(self.read(1))
954 bytes = self.read(n)
Tim Petersee1a53c2003-02-02 02:57:53 +0000955 self.append(decode_long(bytes))
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000956 dispatch[LONG1] = load_long1
957
958 def load_long4(self):
959 n = mloads('i' + self.read(4))
960 bytes = self.read(n)
Tim Petersee1a53c2003-02-02 02:57:53 +0000961 self.append(decode_long(bytes))
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000962 dispatch[LONG4] = load_long4
963
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000964 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000965 self.append(float(self.readline()[:-1]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000966 dispatch[FLOAT] = load_float
967
Guido van Rossumd3703791998-10-22 20:15:36 +0000968 def load_binfloat(self, unpack=struct.unpack):
969 self.append(unpack('>d', self.read(8))[0])
970 dispatch[BINFLOAT] = load_binfloat
971
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000972 def load_string(self):
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000973 rep = self.readline()[:-1]
Tim Petersad5a7712003-01-28 16:23:33 +0000974 for q in "\"'": # double or single quote
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000975 if rep.startswith(q):
976 if not rep.endswith(q):
977 raise ValueError, "insecure string pickle"
978 rep = rep[len(q):-len(q)]
979 break
980 else:
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000981 raise ValueError, "insecure string pickle"
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000982 self.append(rep.decode("string-escape"))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000983 dispatch[STRING] = load_string
984
985 def load_binstring(self):
986 len = mloads('i' + self.read(4))
987 self.append(self.read(len))
988 dispatch[BINSTRING] = load_binstring
989
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000990 def load_unicode(self):
991 self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
992 dispatch[UNICODE] = load_unicode
993
994 def load_binunicode(self):
995 len = mloads('i' + self.read(4))
996 self.append(unicode(self.read(len),'utf-8'))
997 dispatch[BINUNICODE] = load_binunicode
998
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000999 def load_short_binstring(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001000 len = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001001 self.append(self.read(len))
1002 dispatch[SHORT_BINSTRING] = load_short_binstring
1003
1004 def load_tuple(self):
1005 k = self.marker()
1006 self.stack[k:] = [tuple(self.stack[k+1:])]
1007 dispatch[TUPLE] = load_tuple
1008
1009 def load_empty_tuple(self):
1010 self.stack.append(())
1011 dispatch[EMPTY_TUPLE] = load_empty_tuple
1012
Guido van Rossum44f0ea52003-01-28 04:14:51 +00001013 def load_tuple1(self):
1014 self.stack[-1] = (self.stack[-1],)
1015 dispatch[TUPLE1] = load_tuple1
1016
1017 def load_tuple2(self):
1018 self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
1019 dispatch[TUPLE2] = load_tuple2
1020
1021 def load_tuple3(self):
1022 self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
1023 dispatch[TUPLE3] = load_tuple3
1024
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001025 def load_empty_list(self):
1026 self.stack.append([])
1027 dispatch[EMPTY_LIST] = load_empty_list
1028
1029 def load_empty_dictionary(self):
1030 self.stack.append({})
1031 dispatch[EMPTY_DICT] = load_empty_dictionary
1032
1033 def load_list(self):
1034 k = self.marker()
1035 self.stack[k:] = [self.stack[k+1:]]
1036 dispatch[LIST] = load_list
1037
1038 def load_dict(self):
1039 k = self.marker()
1040 d = {}
1041 items = self.stack[k+1:]
1042 for i in range(0, len(items), 2):
1043 key = items[i]
1044 value = items[i+1]
1045 d[key] = value
1046 self.stack[k:] = [d]
1047 dispatch[DICT] = load_dict
1048
Tim Petersd01c1e92003-01-30 15:41:46 +00001049 # INST and OBJ differ only in how they get a class object. It's not
1050 # only sensible to do the rest in a common routine, the two routines
1051 # previously diverged and grew different bugs.
1052 # klass is the class to instantiate, and k points to the topmost mark
1053 # object, following which are the arguments for klass.__init__.
1054 def _instantiate(self, klass, k):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001055 args = tuple(self.stack[k+1:])
1056 del self.stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001057 instantiated = 0
Tim Petersd01c1e92003-01-30 15:41:46 +00001058 if (not args and
1059 type(klass) is ClassType and
1060 not hasattr(klass, "__getinitargs__")):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001061 try:
1062 value = _EmptyClass()
1063 value.__class__ = klass
Guido van Rossumb19e2a31998-04-13 18:08:45 +00001064 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001065 except RuntimeError:
1066 # In restricted execution, assignment to inst.__class__ is
1067 # prohibited
1068 pass
1069 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +00001070 try:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001071 value = klass(*args)
Guido van Rossum743d17e1998-09-15 20:25:57 +00001072 except TypeError, err:
1073 raise TypeError, "in constructor for %s: %s" % (
1074 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001075 self.append(value)
Tim Petersd01c1e92003-01-30 15:41:46 +00001076
1077 def load_inst(self):
1078 module = self.readline()[:-1]
1079 name = self.readline()[:-1]
1080 klass = self.find_class(module, name)
1081 self._instantiate(klass, self.marker())
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001082 dispatch[INST] = load_inst
1083
1084 def load_obj(self):
Tim Petersd01c1e92003-01-30 15:41:46 +00001085 # Stack is ... markobject classobject arg1 arg2 ...
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001086 k = self.marker()
Tim Petersd01c1e92003-01-30 15:41:46 +00001087 klass = self.stack.pop(k+1)
1088 self._instantiate(klass, k)
Tim Peters2344fae2001-01-15 00:50:52 +00001089 dispatch[OBJ] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001090
Guido van Rossum3a41c612003-01-28 15:10:22 +00001091 def load_newobj(self):
1092 args = self.stack.pop()
1093 cls = self.stack[-1]
1094 obj = cls.__new__(cls, *args)
Guido van Rossum533dbcf2003-01-28 17:55:05 +00001095 self.stack[-1] = obj
Guido van Rossum3a41c612003-01-28 15:10:22 +00001096 dispatch[NEWOBJ] = load_newobj
1097
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001098 def load_global(self):
1099 module = self.readline()[:-1]
1100 name = self.readline()[:-1]
1101 klass = self.find_class(module, name)
1102 self.append(klass)
1103 dispatch[GLOBAL] = load_global
1104
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001105 def load_ext1(self):
1106 code = ord(self.read(1))
1107 self.get_extension(code)
1108 dispatch[EXT1] = load_ext1
1109
1110 def load_ext2(self):
1111 code = mloads('i' + self.read(2) + '\000\000')
1112 self.get_extension(code)
1113 dispatch[EXT2] = load_ext2
1114
1115 def load_ext4(self):
1116 code = mloads('i' + self.read(4))
1117 self.get_extension(code)
1118 dispatch[EXT4] = load_ext4
1119
1120 def get_extension(self, code):
1121 nil = []
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001122 obj = _extension_cache.get(code, nil)
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001123 if obj is not nil:
1124 self.append(obj)
1125 return
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001126 key = _inverted_registry.get(code)
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001127 if not key:
1128 raise ValueError("unregistered extension code %d" % code)
1129 obj = self.find_class(*key)
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001130 _extension_cache[code] = obj
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001131 self.append(obj)
1132
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001133 def find_class(self, module, name):
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001134 # Subclasses may override this
Barry Warsawbf4d9592001-11-15 23:42:58 +00001135 __import__(module)
1136 mod = sys.modules[module]
1137 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001138 return klass
1139
1140 def load_reduce(self):
1141 stack = self.stack
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001142 args = stack.pop()
1143 func = stack[-1]
1144 if args is None:
Guido van Rossumbc64e222003-01-28 16:34:19 +00001145 # A hack for Jim Fulton's ExtensionClass, now deprecated
1146 warnings.warn("__basicnew__ special case is deprecated",
Tim Peters8ac14952002-05-23 15:15:30 +00001147 DeprecationWarning)
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001148 value = func.__basicnew__()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001149 else:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001150 value = func(*args)
1151 stack[-1] = value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001152 dispatch[REDUCE] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +00001153
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001154 def load_pop(self):
1155 del self.stack[-1]
1156 dispatch[POP] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +00001157
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001158 def load_pop_mark(self):
1159 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001160 del self.stack[k:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001161 dispatch[POP_MARK] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001162
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001163 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +00001164 self.append(self.stack[-1])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001165 dispatch[DUP] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +00001166
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001167 def load_get(self):
1168 self.append(self.memo[self.readline()[:-1]])
1169 dispatch[GET] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +00001170
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001171 def load_binget(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001172 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001173 self.append(self.memo[`i`])
1174 dispatch[BINGET] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001175
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001176 def load_long_binget(self):
1177 i = mloads('i' + self.read(4))
1178 self.append(self.memo[`i`])
1179 dispatch[LONG_BINGET] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001180
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001181 def load_put(self):
1182 self.memo[self.readline()[:-1]] = self.stack[-1]
1183 dispatch[PUT] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +00001184
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001185 def load_binput(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001186 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001187 self.memo[`i`] = self.stack[-1]
1188 dispatch[BINPUT] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001189
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001190 def load_long_binput(self):
1191 i = mloads('i' + self.read(4))
1192 self.memo[`i`] = self.stack[-1]
1193 dispatch[LONG_BINPUT] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001194
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001195 def load_append(self):
1196 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001197 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001198 list = stack[-1]
1199 list.append(value)
1200 dispatch[APPEND] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +00001201
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001202 def load_appends(self):
1203 stack = self.stack
1204 mark = self.marker()
1205 list = stack[mark - 1]
Tim Peters209ad952003-01-28 01:44:45 +00001206 list.extend(stack[mark + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001207 del stack[mark:]
1208 dispatch[APPENDS] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +00001209
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001210 def load_setitem(self):
1211 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001212 value = stack.pop()
1213 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001214 dict = stack[-1]
1215 dict[key] = value
1216 dispatch[SETITEM] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001217
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001218 def load_setitems(self):
1219 stack = self.stack
1220 mark = self.marker()
1221 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001222 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001223 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001224
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001225 del stack[mark:]
1226 dispatch[SETITEMS] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001227
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001228 def load_build(self):
1229 stack = self.stack
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001230 state = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001231 inst = stack[-1]
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001232 setstate = getattr(inst, "__setstate__", None)
1233 if setstate:
1234 setstate(state)
1235 return
1236 slotstate = None
1237 if isinstance(state, tuple) and len(state) == 2:
1238 state, slotstate = state
1239 if state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001240 try:
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001241 inst.__dict__.update(state)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001242 except RuntimeError:
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001243 # XXX In restricted execution, the instance's __dict__
1244 # is not accessible. Use the old way of unpickling
1245 # the instance variables. This is a semantic
1246 # difference when unpickling in restricted
1247 # vs. unrestricted modes.
1248 for k, v in state.items():
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001249 setattr(inst, k, v)
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001250 if slotstate:
1251 for k, v in slotstate.items():
1252 setattr(inst, k, v)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001253 dispatch[BUILD] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001254
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001255 def load_mark(self):
1256 self.append(self.mark)
1257 dispatch[MARK] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001258
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001259 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001260 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001261 raise _Stop(value)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001262 dispatch[STOP] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001263
Guido van Rossume467be61997-12-05 19:42:42 +00001264# Helper class for load_inst/load_obj
1265
1266class _EmptyClass:
1267 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001268
Tim Peters91149822003-01-31 03:43:58 +00001269# Encode/decode longs in linear time.
1270
1271import binascii as _binascii
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001272
1273def encode_long(x):
Tim Peters91149822003-01-31 03:43:58 +00001274 r"""Encode a long to a two's complement little-endian binary string.
Tim Peters4b23f2b2003-01-31 16:43:39 +00001275 Note that 0L is a special case, returning an empty string, to save a
1276 byte in the LONG1 pickling context.
1277
1278 >>> encode_long(0L)
1279 ''
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001280 >>> encode_long(255L)
1281 '\xff\x00'
1282 >>> encode_long(32767L)
1283 '\xff\x7f'
1284 >>> encode_long(-256L)
1285 '\x00\xff'
1286 >>> encode_long(-32768L)
1287 '\x00\x80'
1288 >>> encode_long(-128L)
1289 '\x80'
1290 >>> encode_long(127L)
1291 '\x7f'
1292 >>>
1293 """
Tim Peters91149822003-01-31 03:43:58 +00001294
1295 if x == 0:
Tim Peters4b23f2b2003-01-31 16:43:39 +00001296 return ''
Tim Peters91149822003-01-31 03:43:58 +00001297 if x > 0:
1298 ashex = hex(x)
1299 assert ashex.startswith("0x")
1300 njunkchars = 2 + ashex.endswith('L')
1301 nibbles = len(ashex) - njunkchars
1302 if nibbles & 1:
1303 # need an even # of nibbles for unhexlify
1304 ashex = "0x0" + ashex[2:]
Tim Peters4b23f2b2003-01-31 16:43:39 +00001305 elif int(ashex[2], 16) >= 8:
Tim Peters91149822003-01-31 03:43:58 +00001306 # "looks negative", so need a byte of sign bits
1307 ashex = "0x00" + ashex[2:]
1308 else:
1309 # Build the 256's-complement: (1L << nbytes) + x. The trick is
1310 # to find the number of bytes in linear time (although that should
1311 # really be a constant-time task).
1312 ashex = hex(-x)
1313 assert ashex.startswith("0x")
1314 njunkchars = 2 + ashex.endswith('L')
1315 nibbles = len(ashex) - njunkchars
1316 if nibbles & 1:
Tim Petersee1a53c2003-02-02 02:57:53 +00001317 # Extend to a full byte.
Tim Peters91149822003-01-31 03:43:58 +00001318 nibbles += 1
Tim Peters4b23f2b2003-01-31 16:43:39 +00001319 nbits = nibbles * 4
1320 x += 1L << nbits
Tim Peters91149822003-01-31 03:43:58 +00001321 assert x > 0
1322 ashex = hex(x)
Tim Petersee1a53c2003-02-02 02:57:53 +00001323 njunkchars = 2 + ashex.endswith('L')
1324 newnibbles = len(ashex) - njunkchars
1325 if newnibbles < nibbles:
1326 ashex = "0x" + "0" * (nibbles - newnibbles) + ashex[2:]
1327 if int(ashex[2], 16) < 8:
Tim Peters91149822003-01-31 03:43:58 +00001328 # "looks positive", so need a byte of sign bits
Tim Petersee1a53c2003-02-02 02:57:53 +00001329 ashex = "0xff" + ashex[2:]
Tim Peters91149822003-01-31 03:43:58 +00001330
1331 if ashex.endswith('L'):
1332 ashex = ashex[2:-1]
1333 else:
1334 ashex = ashex[2:]
Tim Petersee1a53c2003-02-02 02:57:53 +00001335 assert len(ashex) & 1 == 0, (x, ashex)
Tim Peters91149822003-01-31 03:43:58 +00001336 binary = _binascii.unhexlify(ashex)
1337 return binary[::-1]
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001338
1339def decode_long(data):
1340 r"""Decode a long from a two's complement little-endian binary string.
Tim Peters4b23f2b2003-01-31 16:43:39 +00001341
1342 >>> decode_long('')
1343 0L
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001344 >>> decode_long("\xff\x00")
1345 255L
1346 >>> decode_long("\xff\x7f")
1347 32767L
1348 >>> decode_long("\x00\xff")
1349 -256L
1350 >>> decode_long("\x00\x80")
1351 -32768L
1352 >>> decode_long("\x80")
1353 -128L
1354 >>> decode_long("\x7f")
1355 127L
1356 """
Tim Peters91149822003-01-31 03:43:58 +00001357
Tim Peters4b23f2b2003-01-31 16:43:39 +00001358 nbytes = len(data)
1359 if nbytes == 0:
1360 return 0L
Tim Peters91149822003-01-31 03:43:58 +00001361 ashex = _binascii.hexlify(data[::-1])
Tim Petersbf2674b2003-02-02 07:51:32 +00001362 n = long(ashex, 16) # quadratic time before Python 2.3; linear now
Tim Peters91149822003-01-31 03:43:58 +00001363 if data[-1] >= '\x80':
Tim Peters4b23f2b2003-01-31 16:43:39 +00001364 n -= 1L << (nbytes * 8)
Tim Peters91149822003-01-31 03:43:58 +00001365 return n
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001366
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001367# Shorthands
1368
Jeremy Hyltonabe2c622001-10-15 21:29:28 +00001369try:
1370 from cStringIO import StringIO
1371except ImportError:
1372 from StringIO import StringIO
Guido van Rossumc7c5e691996-07-22 22:26:07 +00001373
Guido van Rossumcf117b02003-02-09 17:19:41 +00001374def dump(obj, file, protocol=None, bin=None):
1375 Pickler(file, protocol, bin).dump(obj)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001376
Guido van Rossumcf117b02003-02-09 17:19:41 +00001377def dumps(obj, protocol=None, bin=None):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001378 file = StringIO()
Guido van Rossumcf117b02003-02-09 17:19:41 +00001379 Pickler(file, protocol, bin).dump(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001380 return file.getvalue()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001381
1382def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001383 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001384
1385def loads(str):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001386 file = StringIO(str)
1387 return Unpickler(file).load()
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001388
1389# Doctest
1390
1391def _test():
1392 import doctest
1393 return doctest.testmod()
1394
1395if __name__ == "__main__":
1396 _test()