blob: 1d14ed35c0761c0991483958fdaf184d89a55936 [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 Rossumb26a97a2003-01-28 22:29:13 +000030from copy_reg import dispatch_table, _reconstructor
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 Rossum795ea892003-02-03 16:59:48 +0000170 def __init__(self, file, proto=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 Rossumf29d3d62003-01-27 22:47:53 +0000173 The optional proto argument tells the pickler to use the given
174 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 Rossum795ea892003-02-03 16:59:48 +0000194 if proto is not None and bin is not None:
195 raise ValueError, "can't specify both 'proto' and 'bin' arguments"
196 if bin is not None:
197 warnings.warn("The 'bin' argument to Pickler() is deprecated",
198 PendingDeprecationWarning)
199 proto = bin
200 if proto is None:
201 proto = 0
Guido van Rossum7eff63a2003-01-31 19:42:31 +0000202 if proto < 0:
203 proto = 2
204 elif proto 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 Rossum1be31752003-01-28 15:19:53 +0000208 self.proto = int(proto)
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000209 self.bin = proto >= 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__:
313 reduce = None
314 if not reduce:
Guido van Rossum54fb1922003-01-28 18:22:35 +0000315 self.save_newobj(obj)
316 return
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000317 if not reduce:
Guido van Rossumbc64e222003-01-28 16:34:19 +0000318 raise PicklingError("Can't pickle %r object: %r" %
319 (t.__name__, obj))
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000320 rv = reduce(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000321
Guido van Rossumbc64e222003-01-28 16:34:19 +0000322 # Check for string returned by reduce(), meaning "save as global"
323 if type(rv) is StringType:
324 self.save_global(obj, rv)
Tim Petersb32a8312003-01-28 00:48:09 +0000325 return
326
Guido van Rossumbc64e222003-01-28 16:34:19 +0000327 # Assert that reduce() returned a tuple
328 if type(rv) is not TupleType:
329 raise PicklingError("%s must return string or tuple" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000330
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000331 # Assert that it returned an appropriately sized tuple
Guido van Rossumbc64e222003-01-28 16:34:19 +0000332 l = len(rv)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000333 if not (2 <= l <= 5):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000334 raise PicklingError("Tuple returned by %s must have "
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000335 "two to five elements" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000336
Guido van Rossumbc64e222003-01-28 16:34:19 +0000337 # Save the reduce() output and finally memoize the object
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000338 self.save_reduce(obj=obj, *rv)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000339
Guido van Rossum3a41c612003-01-28 15:10:22 +0000340 def persistent_id(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000341 # This exists so a subclass can override it
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000342 return None
343
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000344 def save_pers(self, pid):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000345 # Save a persistent id reference
Tim Petersbd1cdb92003-01-28 01:03:10 +0000346 if self.bin:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000347 self.save(pid)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000348 self.write(BINPERSID)
Tim Petersbd1cdb92003-01-28 01:03:10 +0000349 else:
350 self.write(PERSID + str(pid) + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000351
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000352 def save_reduce(self, func, args, state=None,
353 listitems=None, dictitems=None, obj=None):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000354 # This API is be called by some subclasses
355
356 # Assert that args is a tuple or None
357 if not isinstance(args, TupleType):
358 if args is None:
359 # A hack for Jim Fulton's ExtensionClass, now deprecated.
360 # See load_reduce()
361 warnings.warn("__basicnew__ special case is deprecated",
362 DeprecationWarning)
363 else:
364 raise PicklingError(
365 "args from reduce() should be a tuple")
366
367 # Assert that func is callable
368 if not callable(func):
369 raise PicklingError("func from reduce should be callable")
370
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000371 save = self.save
Guido van Rossumbc64e222003-01-28 16:34:19 +0000372 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000373
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000374 # Protocol 2 special case: if func's name is __newobj__, use NEWOBJ
375 if self.proto >= 2 and getattr(func, "__name__", "") == "__newobj__":
376 # A __reduce__ implementation can direct protocol 2 to
377 # use the more efficient NEWOBJ opcode, while still
378 # allowing protocol 0 and 1 to work normally. For this to
379 # work, the function returned by __reduce__ should be
380 # called __newobj__, and its first argument should be a
381 # new-style class. The implementation for __newobj__
382 # should be as follows, although pickle has no way to
383 # verify this:
384 #
385 # def __newobj__(cls, *args):
386 # return cls.__new__(cls, *args)
387 #
388 # Protocols 0 and 1 will pickle a reference to __newobj__,
389 # while protocol 2 (and above) will pickle a reference to
390 # cls, the remaining args tuple, and the NEWOBJ code,
391 # which calls cls.__new__(cls, *args) at unpickling time
392 # (see load_newobj below). If __reduce__ returns a
393 # three-tuple, the state from the third tuple item will be
394 # pickled regardless of the protocol, calling __setstate__
395 # at unpickling time (see load_build below).
396 #
397 # Note that no standard __newobj__ implementation exists;
398 # you have to provide your own. This is to enforce
399 # compatibility with Python 2.2 (pickles written using
400 # protocol 0 or 1 in Python 2.3 should be unpicklable by
401 # Python 2.2).
402 cls = args[0]
403 if not hasattr(cls, "__new__"):
404 raise PicklingError(
405 "args[0] from __newobj__ args has no __new__")
Guido van Rossumf7f45172003-01-31 17:17:49 +0000406 if obj is not None and cls is not obj.__class__:
407 raise PicklingError(
408 "args[0] from __newobj__ args has the wrong class")
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000409 args = args[1:]
410 save(cls)
411 save(args)
412 write(NEWOBJ)
413 else:
414 save(func)
415 save(args)
416 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000417
Guido van Rossumf7f45172003-01-31 17:17:49 +0000418 if obj is not None:
419 self.memoize(obj)
420
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000421 # More new special cases (that work with older protocols as
422 # well): when __reduce__ returns a tuple with 4 or 5 items,
423 # the 4th and 5th item should be iterators that provide list
424 # items and dict items (as (key, value) tuples), or None.
425
426 if listitems is not None:
427 self._batch_appends(listitems)
428
429 if dictitems is not None:
430 self._batch_setitems(dictitems)
431
Tim Petersc32d8242001-04-10 02:48:53 +0000432 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000433 save(state)
434 write(BUILD)
435
Guido van Rossum54fb1922003-01-28 18:22:35 +0000436 def save_newobj(self, obj):
437 # Save a new-style class instance, using protocol 2.
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000438 assert self.proto >= 2 # This only works for protocol 2
Guido van Rossum54fb1922003-01-28 18:22:35 +0000439 t = type(obj)
Guido van Rossum54fb1922003-01-28 18:22:35 +0000440 getnewargs = getattr(obj, "__getnewargs__", None)
441 if getnewargs:
Neal Norwitzd1740682003-01-31 04:04:23 +0000442 args = getnewargs() # This better not reference obj
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000443 else:
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000444 args = ()
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000445
446 save = self.save
447 write = self.write
448
Guido van Rossum9b40e802003-01-30 06:37:41 +0000449 self.save(t)
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000450 save(args)
451 write(NEWOBJ)
Guido van Rossum54fb1922003-01-28 18:22:35 +0000452 self.memoize(obj)
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000453
454 if isinstance(obj, list):
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000455 self._batch_appends(iter(obj))
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000456 elif isinstance(obj, dict):
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000457 self._batch_setitems(obj.iteritems())
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000458
Guido van Rossum54fb1922003-01-28 18:22:35 +0000459 getstate = getattr(obj, "__getstate__", None)
Guido van Rossum45486172003-01-30 05:39:04 +0000460
Guido van Rossum54fb1922003-01-28 18:22:35 +0000461 if getstate:
Guido van Rossum4fba2202003-01-30 05:41:19 +0000462 # A class may define both __getstate__ and __getnewargs__.
463 # If they are the same function, we ignore __getstate__.
464 # This is for the benefit of protocols 0 and 1, which don't
465 # use __getnewargs__. Note that the only way to make them
466 # the same function is something like this:
467 #
468 # class C(object):
469 # def __getstate__(self):
470 # return ...
471 # __getnewargs__ = __getstate__
472 #
473 # No tricks are needed to ignore __setstate__; it simply
474 # won't be called when we don't generate BUILD.
475 # Also note that when __getnewargs__ and __getstate__ are
476 # the same function, we don't do the default thing of
477 # looking for __dict__ and slots either -- it is assumed
478 # that __getnewargs__ returns all the state there is
479 # (which should be a safe assumption since __getstate__
480 # returns the *same* state).
481 if getstate == getnewargs:
482 return
483
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000484 try:
485 state = getstate()
486 except TypeError, err:
487 # XXX Catch generic exception caused by __slots__
488 if str(err) != ("a class that defines __slots__ "
489 "without defining __getstate__ "
490 "cannot be pickled"):
491 print repr(str(err))
492 raise # Not that specific exception
493 getstate = None
Guido van Rossum4fba2202003-01-30 05:41:19 +0000494
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000495 if not getstate:
Guido van Rossum54fb1922003-01-28 18:22:35 +0000496 state = getattr(obj, "__dict__", None)
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000497 if not state:
498 state = None
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000499 # If there are slots, the state becomes a tuple of two
500 # items: the first item the regular __dict__ or None, and
501 # the second a dict mapping slot names to slot values
502 names = _slotnames(t)
503 if names:
504 slots = {}
505 nil = []
506 for name in names:
507 value = getattr(obj, name, nil)
508 if value is not nil:
509 slots[name] = value
510 if slots:
511 state = (state, slots)
512
Guido van Rossum54fb1922003-01-28 18:22:35 +0000513 if state is not None:
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000514 save(state)
515 write(BUILD)
Guido van Rossum54fb1922003-01-28 18:22:35 +0000516
Guido van Rossumbc64e222003-01-28 16:34:19 +0000517 # Methods below this point are dispatched through the dispatch table
518
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000519 dispatch = {}
520
Guido van Rossum3a41c612003-01-28 15:10:22 +0000521 def save_none(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000522 self.write(NONE)
523 dispatch[NoneType] = save_none
524
Guido van Rossum3a41c612003-01-28 15:10:22 +0000525 def save_bool(self, obj):
Guido van Rossum7d97d312003-01-28 04:25:27 +0000526 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000527 self.write(obj and NEWTRUE or NEWFALSE)
Guido van Rossum7d97d312003-01-28 04:25:27 +0000528 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000529 self.write(obj and TRUE or FALSE)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000530 dispatch[bool] = save_bool
531
Guido van Rossum3a41c612003-01-28 15:10:22 +0000532 def save_int(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000533 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000534 # If the int is small enough to fit in a signed 4-byte 2's-comp
535 # format, we can store it more efficiently than the general
536 # case.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000537 # First one- and two-byte unsigned ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000538 if obj >= 0:
539 if obj <= 0xff:
540 self.write(BININT1 + chr(obj))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000541 return
Guido van Rossum3a41c612003-01-28 15:10:22 +0000542 if obj <= 0xffff:
Guido van Rossumba884f32003-01-29 20:14:23 +0000543 self.write("%c%c%c" % (BININT2, obj&0xff, obj>>8))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000544 return
545 # Next check for 4-byte signed ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000546 high_bits = obj >> 31 # note that Python shift sign-extends
Tim Petersd95c2df2003-01-28 03:41:54 +0000547 if high_bits == 0 or high_bits == -1:
Tim Peters44714002001-04-10 05:02:52 +0000548 # All high bits are copies of bit 2**31, so the value
549 # fits in a 4-byte signed int.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000550 self.write(BININT + pack("<i", obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000551 return
Tim Peters44714002001-04-10 05:02:52 +0000552 # Text pickle, or int too big to fit in signed 4-byte format.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000553 self.write(INT + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000554 dispatch[IntType] = save_int
555
Guido van Rossum3a41c612003-01-28 15:10:22 +0000556 def save_long(self, obj, pack=struct.pack):
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000557 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000558 bytes = encode_long(obj)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000559 n = len(bytes)
560 if n < 256:
561 self.write(LONG1 + chr(n) + bytes)
562 else:
563 self.write(LONG4 + pack("<i", n) + bytes)
Tim Petersee1a53c2003-02-02 02:57:53 +0000564 return
Guido van Rossum3a41c612003-01-28 15:10:22 +0000565 self.write(LONG + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000566 dispatch[LongType] = save_long
567
Guido van Rossum3a41c612003-01-28 15:10:22 +0000568 def save_float(self, obj, pack=struct.pack):
Guido van Rossumd3703791998-10-22 20:15:36 +0000569 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000570 self.write(BINFLOAT + pack('>d', obj))
Guido van Rossumd3703791998-10-22 20:15:36 +0000571 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000572 self.write(FLOAT + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000573 dispatch[FloatType] = save_float
574
Guido van Rossum3a41c612003-01-28 15:10:22 +0000575 def save_string(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000576 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000577 n = len(obj)
Tim Petersbbf63cd2003-01-27 21:15:36 +0000578 if n < 256:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000579 self.write(SHORT_BINSTRING + chr(n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000580 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000581 self.write(BINSTRING + pack("<i", n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000582 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000583 self.write(STRING + `obj` + '\n')
584 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000585 dispatch[StringType] = save_string
586
Guido van Rossum3a41c612003-01-28 15:10:22 +0000587 def save_unicode(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000588 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000589 encoding = obj.encode('utf-8')
Tim Petersbbf63cd2003-01-27 21:15:36 +0000590 n = len(encoding)
Guido van Rossum5c938d02003-01-28 03:03:08 +0000591 self.write(BINUNICODE + pack("<i", n) + encoding)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000592 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000593 obj = obj.replace("\\", "\\u005c")
594 obj = obj.replace("\n", "\\u000a")
595 self.write(UNICODE + obj.encode('raw-unicode-escape') + '\n')
596 self.memoize(obj)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000597 dispatch[UnicodeType] = save_unicode
598
Guido van Rossum31584cb2001-01-22 14:53:29 +0000599 if StringType == UnicodeType:
600 # This is true for Jython
Guido van Rossum3a41c612003-01-28 15:10:22 +0000601 def save_string(self, obj, pack=struct.pack):
602 unicode = obj.isunicode()
Guido van Rossum31584cb2001-01-22 14:53:29 +0000603
Tim Petersc32d8242001-04-10 02:48:53 +0000604 if self.bin:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000605 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000606 obj = obj.encode("utf-8")
607 l = len(obj)
Tim Petersc32d8242001-04-10 02:48:53 +0000608 if l < 256 and not unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000609 self.write(SHORT_BINSTRING + chr(l) + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000610 else:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000611 s = pack("<i", l)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000612 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000613 self.write(BINUNICODE + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000614 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000615 self.write(BINSTRING + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000616 else:
Tim Peters658cba62001-02-09 20:06:00 +0000617 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000618 obj = obj.replace("\\", "\\u005c")
619 obj = obj.replace("\n", "\\u000a")
620 obj = obj.encode('raw-unicode-escape')
621 self.write(UNICODE + obj + '\n')
Guido van Rossum31584cb2001-01-22 14:53:29 +0000622 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000623 self.write(STRING + `obj` + '\n')
624 self.memoize(obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000625 dispatch[StringType] = save_string
Tim Peters658cba62001-02-09 20:06:00 +0000626
Guido van Rossum3a41c612003-01-28 15:10:22 +0000627 def save_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000628 write = self.write
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000629 proto = self.proto
630
Guido van Rossum3a41c612003-01-28 15:10:22 +0000631 n = len(obj)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000632 if n == 0:
633 if proto:
634 write(EMPTY_TUPLE)
635 else:
636 write(MARK + TUPLE)
Tim Petersd97da802003-01-28 05:48:29 +0000637 return
638
639 save = self.save
640 memo = self.memo
641 if n <= 3 and proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000642 for element in obj:
Tim Petersd97da802003-01-28 05:48:29 +0000643 save(element)
644 # Subtle. Same as in the big comment below.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000645 if id(obj) in memo:
646 get = self.get(memo[id(obj)][0])
Tim Petersd97da802003-01-28 05:48:29 +0000647 write(POP * n + get)
648 else:
649 write(_tuplesize2code[n])
Guido van Rossum3a41c612003-01-28 15:10:22 +0000650 self.memoize(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000651 return
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000652
Tim Peters1d63c9f2003-02-02 20:29:39 +0000653 # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple
Tim Petersff57bff2003-01-28 05:34:53 +0000654 # has more than 3 elements.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000655 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000656 for element in obj:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000657 save(element)
658
Tim Peters1d63c9f2003-02-02 20:29:39 +0000659 if id(obj) in memo:
Tim Petersf558da02003-01-28 02:09:55 +0000660 # Subtle. d was not in memo when we entered save_tuple(), so
661 # the process of saving the tuple's elements must have saved
662 # the tuple itself: the tuple is recursive. The proper action
663 # now is to throw away everything we put on the stack, and
664 # simply GET the tuple (it's already constructed). This check
665 # could have been done in the "for element" loop instead, but
666 # recursive tuples are a rare thing.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000667 get = self.get(memo[id(obj)][0])
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000668 if proto:
Tim Petersf558da02003-01-28 02:09:55 +0000669 write(POP_MARK + get)
670 else: # proto 0 -- POP_MARK not available
Tim Petersd97da802003-01-28 05:48:29 +0000671 write(POP * (n+1) + get)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000672 return
673
Tim Peters1d63c9f2003-02-02 20:29:39 +0000674 # No recursion.
Tim Peters518df0d2003-01-28 01:00:38 +0000675 self.write(TUPLE)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000676 self.memoize(obj)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000677
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000678 dispatch[TupleType] = save_tuple
679
Tim Petersa6ae9a22003-01-28 16:58:41 +0000680 # save_empty_tuple() isn't used by anything in Python 2.3. However, I
681 # found a Pickler subclass in Zope3 that calls it, so it's not harmless
682 # to remove it.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000683 def save_empty_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000684 self.write(EMPTY_TUPLE)
685
Guido van Rossum3a41c612003-01-28 15:10:22 +0000686 def save_list(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000687 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000688
Tim Petersc32d8242001-04-10 02:48:53 +0000689 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000690 write(EMPTY_LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000691 else: # proto 0 -- can't use EMPTY_LIST
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000692 write(MARK + LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000693
694 self.memoize(obj)
695 self._batch_appends(iter(obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000696
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000697 dispatch[ListType] = save_list
698
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000699 _BATCHSIZE = 1000
700
701 def _batch_appends(self, items):
702 # Helper to batch up APPENDS sequences
703 save = self.save
704 write = self.write
705
706 if not self.bin:
707 for x in items:
708 save(x)
709 write(APPEND)
710 return
711
712 r = xrange(self._BATCHSIZE)
713 while items is not None:
714 tmp = []
715 for i in r:
716 try:
717 tmp.append(items.next())
718 except StopIteration:
719 items = None
720 break
721 n = len(tmp)
722 if n > 1:
723 write(MARK)
724 for x in tmp:
725 save(x)
726 write(APPENDS)
727 elif n:
728 save(tmp[0])
729 write(APPEND)
730 # else tmp is empty, and we're done
731
Guido van Rossum3a41c612003-01-28 15:10:22 +0000732 def save_dict(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000733 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000734
Tim Petersc32d8242001-04-10 02:48:53 +0000735 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000736 write(EMPTY_DICT)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000737 else: # proto 0 -- can't use EMPTY_DICT
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000738 write(MARK + DICT)
739
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000740 self.memoize(obj)
741 self._batch_setitems(obj.iteritems())
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000742
743 dispatch[DictionaryType] = save_dict
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000744 if not PyStringMap is None:
745 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000746
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000747 def _batch_setitems(self, items):
748 # Helper to batch up SETITEMS sequences; proto >= 1 only
749 save = self.save
750 write = self.write
751
752 if not self.bin:
753 for k, v in items:
754 save(k)
755 save(v)
756 write(SETITEM)
757 return
758
759 r = xrange(self._BATCHSIZE)
760 while items is not None:
761 tmp = []
762 for i in r:
763 try:
764 tmp.append(items.next())
765 except StopIteration:
766 items = None
767 break
768 n = len(tmp)
769 if n > 1:
770 write(MARK)
771 for k, v in tmp:
772 save(k)
773 save(v)
774 write(SETITEMS)
775 elif n:
776 k, v = tmp[0]
777 save(k)
778 save(v)
779 write(SETITEM)
780 # else tmp is empty, and we're done
781
Guido van Rossum3a41c612003-01-28 15:10:22 +0000782 def save_inst(self, obj):
783 cls = obj.__class__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000784
785 memo = self.memo
786 write = self.write
787 save = self.save
788
Guido van Rossum3a41c612003-01-28 15:10:22 +0000789 if hasattr(obj, '__getinitargs__'):
790 args = obj.__getinitargs__()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000791 len(args) # XXX Assert it's a sequence
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000792 _keep_alive(args, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000793 else:
794 args = ()
795
796 write(MARK)
797
Tim Petersc32d8242001-04-10 02:48:53 +0000798 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000799 save(cls)
Tim Peters3b769832003-01-28 03:51:36 +0000800 for arg in args:
801 save(arg)
802 write(OBJ)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000803 else:
Tim Peters3b769832003-01-28 03:51:36 +0000804 for arg in args:
805 save(arg)
806 write(INST + cls.__module__ + '\n' + cls.__name__ + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000807
Guido van Rossum3a41c612003-01-28 15:10:22 +0000808 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000809
810 try:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000811 getstate = obj.__getstate__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000812 except AttributeError:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000813 stuff = obj.__dict__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000814 else:
815 stuff = getstate()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000816 _keep_alive(stuff, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000817 save(stuff)
818 write(BUILD)
Tim Peters3b769832003-01-28 03:51:36 +0000819
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000820 dispatch[InstanceType] = save_inst
821
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000822 def save_global(self, obj, name=None, pack=struct.pack):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000823 write = self.write
824 memo = self.memo
825
Tim Petersc32d8242001-04-10 02:48:53 +0000826 if name is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000827 name = obj.__name__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000828
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000829 module = getattr(obj, "__module__", None)
830 if module is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000831 module = whichmodule(obj, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000832
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000833 try:
834 __import__(module)
835 mod = sys.modules[module]
836 klass = getattr(mod, name)
837 except (ImportError, KeyError, AttributeError):
838 raise PicklingError(
839 "Can't pickle %r: it's not found as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000840 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000841 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000842 if klass is not obj:
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000843 raise PicklingError(
844 "Can't pickle %r: it's not the same object as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000845 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000846
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000847 if self.proto >= 2:
Guido van Rossumd4b920c2003-02-04 01:54:49 +0000848 code = _extension_registry.get((module, name))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000849 if code:
850 assert code > 0
851 if code <= 0xff:
852 write(EXT1 + chr(code))
853 elif code <= 0xffff:
Guido van Rossumba884f32003-01-29 20:14:23 +0000854 write("%c%c%c" % (EXT2, code&0xff, code>>8))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000855 else:
856 write(EXT4 + pack("<i", code))
857 return
858
Tim Peters518df0d2003-01-28 01:00:38 +0000859 write(GLOBAL + module + '\n' + name + '\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000860 self.memoize(obj)
Tim Peters3b769832003-01-28 03:51:36 +0000861
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000862 dispatch[ClassType] = save_global
863 dispatch[FunctionType] = save_global
864 dispatch[BuiltinFunctionType] = save_global
Tim Peters6d6c1a32001-08-02 04:15:00 +0000865 dispatch[TypeType] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000866
Guido van Rossum1be31752003-01-28 15:19:53 +0000867# Pickling helpers
Guido van Rossuma48061a1995-01-10 00:31:14 +0000868
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000869def _slotnames(cls):
870 """Return a list of slot names for a given class.
871
872 This needs to find slots defined by the class and its bases, so we
873 can't simply return the __slots__ attribute. We must walk down
874 the Method Resolution Order and concatenate the __slots__ of each
875 class found there. (This assumes classes don't modify their
876 __slots__ attribute to misrepresent their slots after the class is
877 defined.)
878 """
Guido van Rossum93fe5642003-02-03 19:46:54 +0000879
880 # Get the value from a cache in the class if possible
881 names = cls.__dict__.get("__slotnames__")
882 if names is not None:
883 return names
884
885 # Not cached -- calculate the value
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000886 names = []
Guido van Rossum93fe5642003-02-03 19:46:54 +0000887 if not hasattr(cls, "__slots__"):
888 # This class has no slots
889 pass
890 else:
891 # Slots found -- gather slot names from all base classes
892 for c in cls.__mro__:
893 if "__slots__" in c.__dict__:
894 names += [name for name in c.__dict__["__slots__"]
895 if name not in ("__dict__", "__weakref__")]
896
897 # Cache the outcome in the class if at all possible
898 try:
899 cls.__slotnames__ = names
900 except:
901 pass # But don't die if we can't
902
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000903 return names
904
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000905def _keep_alive(x, memo):
906 """Keeps a reference to the object x in the memo.
907
908 Because we remember objects by their id, we have
909 to assure that possibly temporary objects are kept
910 alive by referencing them.
911 We store a reference at the id of the memo, which should
912 normally not be used unless someone tries to deepcopy
913 the memo itself...
914 """
915 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000916 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000917 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000918 # aha, this is the first one :-)
919 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000920
921
Tim Petersc0c12b52003-01-29 00:56:17 +0000922# A cache for whichmodule(), mapping a function object to the name of
923# the module in which the function was found.
924
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000925classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000926
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000927def whichmodule(func, funcname):
928 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000929
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000930 Search sys.modules for the module.
931 Cache in classmap.
932 Return a module name.
Tim Petersc0c12b52003-01-29 00:56:17 +0000933 If the function cannot be found, return "__main__".
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000934 """
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000935 # Python functions should always get an __module__ from their globals.
936 mod = getattr(func, "__module__", None)
937 if mod is not None:
938 return mod
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000939 if func in classmap:
940 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000941
942 for name, module in sys.modules.items():
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000943 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000944 continue # skip dummy package entries
Jeremy Hyltoncc1fccb2003-02-06 16:23:01 +0000945 if name != '__main__' and getattr(module, funcname, None) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000946 break
947 else:
948 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000949 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000950 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000951
952
Guido van Rossum1be31752003-01-28 15:19:53 +0000953# Unpickling machinery
954
Guido van Rossuma48061a1995-01-10 00:31:14 +0000955class Unpickler:
956
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000957 def __init__(self, file):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000958 """This takes a file-like object for reading a pickle data stream.
959
Tim Peters5bd2a792003-02-01 16:45:06 +0000960 The protocol version of the pickle is detected automatically, so no
961 proto argument is needed.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000962
963 The file-like object must have two methods, a read() method that
964 takes an integer argument, and a readline() method that requires no
965 arguments. Both methods should return a string. Thus file-like
966 object can be a file object opened for reading, a StringIO object,
967 or any other custom object that meets this interface.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000968 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000969 self.readline = file.readline
970 self.read = file.read
971 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000972
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000973 def load(self):
Guido van Rossum3a41c612003-01-28 15:10:22 +0000974 """Read a pickled object representation from the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000975
Guido van Rossum3a41c612003-01-28 15:10:22 +0000976 Return the reconstituted object hierarchy specified in the file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000977 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000978 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000979 self.stack = []
980 self.append = self.stack.append
981 read = self.read
982 dispatch = self.dispatch
983 try:
984 while 1:
985 key = read(1)
986 dispatch[key](self)
Guido van Rossumff871742000-12-13 18:11:56 +0000987 except _Stop, stopinst:
988 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000989
Tim Petersc23d18a2003-01-28 01:41:51 +0000990 # Return largest index k such that self.stack[k] is self.mark.
991 # If the stack doesn't contain a mark, eventually raises IndexError.
992 # This could be sped by maintaining another stack, of indices at which
993 # the mark appears. For that matter, the latter stack would suffice,
994 # and we wouldn't need to push mark objects on self.stack at all.
995 # Doing so is probably a good thing, though, since if the pickle is
996 # corrupt (or hostile) we may get a clue from finding self.mark embedded
997 # in unpickled objects.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000998 def marker(self):
999 stack = self.stack
1000 mark = self.mark
1001 k = len(stack)-1
1002 while stack[k] is not mark: k = k-1
1003 return k
1004
1005 dispatch = {}
1006
1007 def load_eof(self):
1008 raise EOFError
1009 dispatch[''] = load_eof
1010
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001011 def load_proto(self):
1012 proto = ord(self.read(1))
1013 if not 0 <= proto <= 2:
1014 raise ValueError, "unsupported pickle protocol: %d" % proto
1015 dispatch[PROTO] = load_proto
1016
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001017 def load_persid(self):
1018 pid = self.readline()[:-1]
1019 self.append(self.persistent_load(pid))
1020 dispatch[PERSID] = load_persid
1021
1022 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001023 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001024 self.append(self.persistent_load(pid))
1025 dispatch[BINPERSID] = load_binpersid
1026
1027 def load_none(self):
1028 self.append(None)
1029 dispatch[NONE] = load_none
1030
Guido van Rossum7d97d312003-01-28 04:25:27 +00001031 def load_false(self):
1032 self.append(False)
1033 dispatch[NEWFALSE] = load_false
1034
1035 def load_true(self):
1036 self.append(True)
1037 dispatch[NEWTRUE] = load_true
1038
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001039 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +00001040 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +00001041 if data == FALSE[1:]:
1042 val = False
1043 elif data == TRUE[1:]:
1044 val = True
1045 else:
1046 try:
1047 val = int(data)
1048 except ValueError:
1049 val = long(data)
1050 self.append(val)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001051 dispatch[INT] = load_int
1052
1053 def load_binint(self):
1054 self.append(mloads('i' + self.read(4)))
1055 dispatch[BININT] = load_binint
1056
1057 def load_binint1(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001058 self.append(ord(self.read(1)))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001059 dispatch[BININT1] = load_binint1
1060
1061 def load_binint2(self):
1062 self.append(mloads('i' + self.read(2) + '\000\000'))
1063 dispatch[BININT2] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +00001064
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001065 def load_long(self):
Guido van Rossumff871742000-12-13 18:11:56 +00001066 self.append(long(self.readline()[:-1], 0))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001067 dispatch[LONG] = load_long
1068
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001069 def load_long1(self):
1070 n = ord(self.read(1))
1071 bytes = self.read(n)
Tim Petersee1a53c2003-02-02 02:57:53 +00001072 self.append(decode_long(bytes))
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001073 dispatch[LONG1] = load_long1
1074
1075 def load_long4(self):
1076 n = mloads('i' + self.read(4))
1077 bytes = self.read(n)
Tim Petersee1a53c2003-02-02 02:57:53 +00001078 self.append(decode_long(bytes))
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001079 dispatch[LONG4] = load_long4
1080
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001081 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +00001082 self.append(float(self.readline()[:-1]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001083 dispatch[FLOAT] = load_float
1084
Guido van Rossumd3703791998-10-22 20:15:36 +00001085 def load_binfloat(self, unpack=struct.unpack):
1086 self.append(unpack('>d', self.read(8))[0])
1087 dispatch[BINFLOAT] = load_binfloat
1088
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001089 def load_string(self):
Jeremy Hyltonbe467e52000-09-15 15:14:51 +00001090 rep = self.readline()[:-1]
Tim Petersad5a7712003-01-28 16:23:33 +00001091 for q in "\"'": # double or single quote
Martin v. Löwis8a8da792002-08-14 07:46:28 +00001092 if rep.startswith(q):
1093 if not rep.endswith(q):
1094 raise ValueError, "insecure string pickle"
1095 rep = rep[len(q):-len(q)]
1096 break
1097 else:
Jeremy Hyltonbe467e52000-09-15 15:14:51 +00001098 raise ValueError, "insecure string pickle"
Martin v. Löwis8a8da792002-08-14 07:46:28 +00001099 self.append(rep.decode("string-escape"))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001100 dispatch[STRING] = load_string
1101
1102 def load_binstring(self):
1103 len = mloads('i' + self.read(4))
1104 self.append(self.read(len))
1105 dispatch[BINSTRING] = load_binstring
1106
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +00001107 def load_unicode(self):
1108 self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
1109 dispatch[UNICODE] = load_unicode
1110
1111 def load_binunicode(self):
1112 len = mloads('i' + self.read(4))
1113 self.append(unicode(self.read(len),'utf-8'))
1114 dispatch[BINUNICODE] = load_binunicode
1115
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001116 def load_short_binstring(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001117 len = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001118 self.append(self.read(len))
1119 dispatch[SHORT_BINSTRING] = load_short_binstring
1120
1121 def load_tuple(self):
1122 k = self.marker()
1123 self.stack[k:] = [tuple(self.stack[k+1:])]
1124 dispatch[TUPLE] = load_tuple
1125
1126 def load_empty_tuple(self):
1127 self.stack.append(())
1128 dispatch[EMPTY_TUPLE] = load_empty_tuple
1129
Guido van Rossum44f0ea52003-01-28 04:14:51 +00001130 def load_tuple1(self):
1131 self.stack[-1] = (self.stack[-1],)
1132 dispatch[TUPLE1] = load_tuple1
1133
1134 def load_tuple2(self):
1135 self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
1136 dispatch[TUPLE2] = load_tuple2
1137
1138 def load_tuple3(self):
1139 self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
1140 dispatch[TUPLE3] = load_tuple3
1141
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001142 def load_empty_list(self):
1143 self.stack.append([])
1144 dispatch[EMPTY_LIST] = load_empty_list
1145
1146 def load_empty_dictionary(self):
1147 self.stack.append({})
1148 dispatch[EMPTY_DICT] = load_empty_dictionary
1149
1150 def load_list(self):
1151 k = self.marker()
1152 self.stack[k:] = [self.stack[k+1:]]
1153 dispatch[LIST] = load_list
1154
1155 def load_dict(self):
1156 k = self.marker()
1157 d = {}
1158 items = self.stack[k+1:]
1159 for i in range(0, len(items), 2):
1160 key = items[i]
1161 value = items[i+1]
1162 d[key] = value
1163 self.stack[k:] = [d]
1164 dispatch[DICT] = load_dict
1165
Tim Petersd01c1e92003-01-30 15:41:46 +00001166 # INST and OBJ differ only in how they get a class object. It's not
1167 # only sensible to do the rest in a common routine, the two routines
1168 # previously diverged and grew different bugs.
1169 # klass is the class to instantiate, and k points to the topmost mark
1170 # object, following which are the arguments for klass.__init__.
1171 def _instantiate(self, klass, k):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001172 args = tuple(self.stack[k+1:])
1173 del self.stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001174 instantiated = 0
Tim Petersd01c1e92003-01-30 15:41:46 +00001175 if (not args and
1176 type(klass) is ClassType and
1177 not hasattr(klass, "__getinitargs__")):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001178 try:
1179 value = _EmptyClass()
1180 value.__class__ = klass
Guido van Rossumb19e2a31998-04-13 18:08:45 +00001181 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001182 except RuntimeError:
1183 # In restricted execution, assignment to inst.__class__ is
1184 # prohibited
1185 pass
1186 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +00001187 try:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001188 value = klass(*args)
Guido van Rossum743d17e1998-09-15 20:25:57 +00001189 except TypeError, err:
1190 raise TypeError, "in constructor for %s: %s" % (
1191 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001192 self.append(value)
Tim Petersd01c1e92003-01-30 15:41:46 +00001193
1194 def load_inst(self):
1195 module = self.readline()[:-1]
1196 name = self.readline()[:-1]
1197 klass = self.find_class(module, name)
1198 self._instantiate(klass, self.marker())
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001199 dispatch[INST] = load_inst
1200
1201 def load_obj(self):
Tim Petersd01c1e92003-01-30 15:41:46 +00001202 # Stack is ... markobject classobject arg1 arg2 ...
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001203 k = self.marker()
Tim Petersd01c1e92003-01-30 15:41:46 +00001204 klass = self.stack.pop(k+1)
1205 self._instantiate(klass, k)
Tim Peters2344fae2001-01-15 00:50:52 +00001206 dispatch[OBJ] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001207
Guido van Rossum3a41c612003-01-28 15:10:22 +00001208 def load_newobj(self):
1209 args = self.stack.pop()
1210 cls = self.stack[-1]
1211 obj = cls.__new__(cls, *args)
Guido van Rossum533dbcf2003-01-28 17:55:05 +00001212 self.stack[-1] = obj
Guido van Rossum3a41c612003-01-28 15:10:22 +00001213 dispatch[NEWOBJ] = load_newobj
1214
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001215 def load_global(self):
1216 module = self.readline()[:-1]
1217 name = self.readline()[:-1]
1218 klass = self.find_class(module, name)
1219 self.append(klass)
1220 dispatch[GLOBAL] = load_global
1221
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001222 def load_ext1(self):
1223 code = ord(self.read(1))
1224 self.get_extension(code)
1225 dispatch[EXT1] = load_ext1
1226
1227 def load_ext2(self):
1228 code = mloads('i' + self.read(2) + '\000\000')
1229 self.get_extension(code)
1230 dispatch[EXT2] = load_ext2
1231
1232 def load_ext4(self):
1233 code = mloads('i' + self.read(4))
1234 self.get_extension(code)
1235 dispatch[EXT4] = load_ext4
1236
1237 def get_extension(self, code):
1238 nil = []
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001239 obj = _extension_cache.get(code, nil)
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001240 if obj is not nil:
1241 self.append(obj)
1242 return
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001243 key = _inverted_registry.get(code)
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001244 if not key:
1245 raise ValueError("unregistered extension code %d" % code)
1246 obj = self.find_class(*key)
Guido van Rossumd4b920c2003-02-04 01:54:49 +00001247 _extension_cache[code] = obj
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001248 self.append(obj)
1249
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001250 def find_class(self, module, name):
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001251 # Subclasses may override this
Barry Warsawbf4d9592001-11-15 23:42:58 +00001252 __import__(module)
1253 mod = sys.modules[module]
1254 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001255 return klass
1256
1257 def load_reduce(self):
1258 stack = self.stack
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001259 args = stack.pop()
1260 func = stack[-1]
1261 if args is None:
Guido van Rossumbc64e222003-01-28 16:34:19 +00001262 # A hack for Jim Fulton's ExtensionClass, now deprecated
1263 warnings.warn("__basicnew__ special case is deprecated",
Tim Peters8ac14952002-05-23 15:15:30 +00001264 DeprecationWarning)
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001265 value = func.__basicnew__()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001266 else:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001267 value = func(*args)
1268 stack[-1] = value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001269 dispatch[REDUCE] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +00001270
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001271 def load_pop(self):
1272 del self.stack[-1]
1273 dispatch[POP] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +00001274
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001275 def load_pop_mark(self):
1276 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001277 del self.stack[k:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001278 dispatch[POP_MARK] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001279
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001280 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +00001281 self.append(self.stack[-1])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001282 dispatch[DUP] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +00001283
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001284 def load_get(self):
1285 self.append(self.memo[self.readline()[:-1]])
1286 dispatch[GET] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +00001287
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001288 def load_binget(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001289 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001290 self.append(self.memo[`i`])
1291 dispatch[BINGET] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001292
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001293 def load_long_binget(self):
1294 i = mloads('i' + self.read(4))
1295 self.append(self.memo[`i`])
1296 dispatch[LONG_BINGET] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001297
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001298 def load_put(self):
1299 self.memo[self.readline()[:-1]] = self.stack[-1]
1300 dispatch[PUT] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +00001301
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001302 def load_binput(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001303 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001304 self.memo[`i`] = self.stack[-1]
1305 dispatch[BINPUT] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001306
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001307 def load_long_binput(self):
1308 i = mloads('i' + self.read(4))
1309 self.memo[`i`] = self.stack[-1]
1310 dispatch[LONG_BINPUT] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001311
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001312 def load_append(self):
1313 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001314 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001315 list = stack[-1]
1316 list.append(value)
1317 dispatch[APPEND] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +00001318
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001319 def load_appends(self):
1320 stack = self.stack
1321 mark = self.marker()
1322 list = stack[mark - 1]
Tim Peters209ad952003-01-28 01:44:45 +00001323 list.extend(stack[mark + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001324 del stack[mark:]
1325 dispatch[APPENDS] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +00001326
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001327 def load_setitem(self):
1328 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001329 value = stack.pop()
1330 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001331 dict = stack[-1]
1332 dict[key] = value
1333 dispatch[SETITEM] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001334
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001335 def load_setitems(self):
1336 stack = self.stack
1337 mark = self.marker()
1338 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001339 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001340 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001341
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001342 del stack[mark:]
1343 dispatch[SETITEMS] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001344
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001345 def load_build(self):
1346 stack = self.stack
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001347 state = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001348 inst = stack[-1]
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001349 setstate = getattr(inst, "__setstate__", None)
1350 if setstate:
1351 setstate(state)
1352 return
1353 slotstate = None
1354 if isinstance(state, tuple) and len(state) == 2:
1355 state, slotstate = state
1356 if state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001357 try:
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001358 inst.__dict__.update(state)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001359 except RuntimeError:
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001360 # XXX In restricted execution, the instance's __dict__
1361 # is not accessible. Use the old way of unpickling
1362 # the instance variables. This is a semantic
1363 # difference when unpickling in restricted
1364 # vs. unrestricted modes.
1365 for k, v in state.items():
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001366 setattr(inst, k, v)
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001367 if slotstate:
1368 for k, v in slotstate.items():
1369 setattr(inst, k, v)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001370 dispatch[BUILD] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001371
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001372 def load_mark(self):
1373 self.append(self.mark)
1374 dispatch[MARK] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001375
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001376 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001377 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001378 raise _Stop(value)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001379 dispatch[STOP] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001380
Guido van Rossume467be61997-12-05 19:42:42 +00001381# Helper class for load_inst/load_obj
1382
1383class _EmptyClass:
1384 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001385
Tim Peters91149822003-01-31 03:43:58 +00001386# Encode/decode longs in linear time.
1387
1388import binascii as _binascii
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001389
1390def encode_long(x):
Tim Peters91149822003-01-31 03:43:58 +00001391 r"""Encode a long to a two's complement little-endian binary string.
Tim Peters4b23f2b2003-01-31 16:43:39 +00001392 Note that 0L is a special case, returning an empty string, to save a
1393 byte in the LONG1 pickling context.
1394
1395 >>> encode_long(0L)
1396 ''
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001397 >>> encode_long(255L)
1398 '\xff\x00'
1399 >>> encode_long(32767L)
1400 '\xff\x7f'
1401 >>> encode_long(-256L)
1402 '\x00\xff'
1403 >>> encode_long(-32768L)
1404 '\x00\x80'
1405 >>> encode_long(-128L)
1406 '\x80'
1407 >>> encode_long(127L)
1408 '\x7f'
1409 >>>
1410 """
Tim Peters91149822003-01-31 03:43:58 +00001411
1412 if x == 0:
Tim Peters4b23f2b2003-01-31 16:43:39 +00001413 return ''
Tim Peters91149822003-01-31 03:43:58 +00001414 if x > 0:
1415 ashex = hex(x)
1416 assert ashex.startswith("0x")
1417 njunkchars = 2 + ashex.endswith('L')
1418 nibbles = len(ashex) - njunkchars
1419 if nibbles & 1:
1420 # need an even # of nibbles for unhexlify
1421 ashex = "0x0" + ashex[2:]
Tim Peters4b23f2b2003-01-31 16:43:39 +00001422 elif int(ashex[2], 16) >= 8:
Tim Peters91149822003-01-31 03:43:58 +00001423 # "looks negative", so need a byte of sign bits
1424 ashex = "0x00" + ashex[2:]
1425 else:
1426 # Build the 256's-complement: (1L << nbytes) + x. The trick is
1427 # to find the number of bytes in linear time (although that should
1428 # really be a constant-time task).
1429 ashex = hex(-x)
1430 assert ashex.startswith("0x")
1431 njunkchars = 2 + ashex.endswith('L')
1432 nibbles = len(ashex) - njunkchars
1433 if nibbles & 1:
Tim Petersee1a53c2003-02-02 02:57:53 +00001434 # Extend to a full byte.
Tim Peters91149822003-01-31 03:43:58 +00001435 nibbles += 1
Tim Peters4b23f2b2003-01-31 16:43:39 +00001436 nbits = nibbles * 4
1437 x += 1L << nbits
Tim Peters91149822003-01-31 03:43:58 +00001438 assert x > 0
1439 ashex = hex(x)
Tim Petersee1a53c2003-02-02 02:57:53 +00001440 njunkchars = 2 + ashex.endswith('L')
1441 newnibbles = len(ashex) - njunkchars
1442 if newnibbles < nibbles:
1443 ashex = "0x" + "0" * (nibbles - newnibbles) + ashex[2:]
1444 if int(ashex[2], 16) < 8:
Tim Peters91149822003-01-31 03:43:58 +00001445 # "looks positive", so need a byte of sign bits
Tim Petersee1a53c2003-02-02 02:57:53 +00001446 ashex = "0xff" + ashex[2:]
Tim Peters91149822003-01-31 03:43:58 +00001447
1448 if ashex.endswith('L'):
1449 ashex = ashex[2:-1]
1450 else:
1451 ashex = ashex[2:]
Tim Petersee1a53c2003-02-02 02:57:53 +00001452 assert len(ashex) & 1 == 0, (x, ashex)
Tim Peters91149822003-01-31 03:43:58 +00001453 binary = _binascii.unhexlify(ashex)
1454 return binary[::-1]
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001455
1456def decode_long(data):
1457 r"""Decode a long from a two's complement little-endian binary string.
Tim Peters4b23f2b2003-01-31 16:43:39 +00001458
1459 >>> decode_long('')
1460 0L
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001461 >>> decode_long("\xff\x00")
1462 255L
1463 >>> decode_long("\xff\x7f")
1464 32767L
1465 >>> decode_long("\x00\xff")
1466 -256L
1467 >>> decode_long("\x00\x80")
1468 -32768L
1469 >>> decode_long("\x80")
1470 -128L
1471 >>> decode_long("\x7f")
1472 127L
1473 """
Tim Peters91149822003-01-31 03:43:58 +00001474
Tim Peters4b23f2b2003-01-31 16:43:39 +00001475 nbytes = len(data)
1476 if nbytes == 0:
1477 return 0L
Tim Peters91149822003-01-31 03:43:58 +00001478 ashex = _binascii.hexlify(data[::-1])
Tim Petersbf2674b2003-02-02 07:51:32 +00001479 n = long(ashex, 16) # quadratic time before Python 2.3; linear now
Tim Peters91149822003-01-31 03:43:58 +00001480 if data[-1] >= '\x80':
Tim Peters4b23f2b2003-01-31 16:43:39 +00001481 n -= 1L << (nbytes * 8)
Tim Peters91149822003-01-31 03:43:58 +00001482 return n
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001483
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001484# Shorthands
1485
Jeremy Hyltonabe2c622001-10-15 21:29:28 +00001486try:
1487 from cStringIO import StringIO
1488except ImportError:
1489 from StringIO import StringIO
Guido van Rossumc7c5e691996-07-22 22:26:07 +00001490
Guido van Rossum795ea892003-02-03 16:59:48 +00001491def dump(obj, file, proto=None, bin=None):
1492 Pickler(file, proto, bin).dump(obj)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001493
Guido van Rossum795ea892003-02-03 16:59:48 +00001494def dumps(obj, proto=None, bin=None):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001495 file = StringIO()
Guido van Rossum795ea892003-02-03 16:59:48 +00001496 Pickler(file, proto, bin).dump(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001497 return file.getvalue()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001498
1499def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001500 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001501
1502def loads(str):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001503 file = StringIO(str)
1504 return Unpickler(file).load()
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001505
1506# Doctest
1507
1508def _test():
1509 import doctest
1510 return doctest.testmod()
1511
1512if __name__ == "__main__":
1513 _test()