blob: 926869ea7e18e8a986b3b6a17958dd8ca2cdaed5 [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 Rossum255f3ee2003-01-29 06:14:11 +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 Rossum7eff63a2003-01-31 19:42:31 +0000170 def __init__(self, file, proto=0):
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 Rossum7eff63a2003-01-31 19:42:31 +0000194 if proto < 0:
195 proto = 2
196 elif proto not in (0, 1, 2):
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000197 raise ValueError, "pickle protocol must be 0, 1 or 2"
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000198 self.write = file.write
199 self.memo = {}
Guido van Rossum1be31752003-01-28 15:19:53 +0000200 self.proto = int(proto)
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000201 self.bin = proto >= 1
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000202 self.fast = 0
Guido van Rossuma48061a1995-01-10 00:31:14 +0000203
Fred Drake7f781c92002-05-01 20:33:53 +0000204 def clear_memo(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000205 """Clears the pickler's "memo".
206
207 The memo is the data structure that remembers which objects the
Tim Petersb377f8a2003-01-28 00:23:36 +0000208 pickler has already seen, so that shared or recursive objects are
209 pickled by reference and not by value. This method is useful when
210 re-using picklers.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000211
212 """
Fred Drake7f781c92002-05-01 20:33:53 +0000213 self.memo.clear()
214
Guido van Rossum3a41c612003-01-28 15:10:22 +0000215 def dump(self, obj):
Tim Peters5bd2a792003-02-01 16:45:06 +0000216 """Write a pickled representation of obj to the open file."""
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000217 if self.proto >= 2:
218 self.write(PROTO + chr(self.proto))
Guido van Rossum3a41c612003-01-28 15:10:22 +0000219 self.save(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000220 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000221
Jeremy Hylton3422c992003-01-24 19:29:52 +0000222 def memoize(self, obj):
223 """Store an object in the memo."""
224
Tim Peterse46b73f2003-01-27 21:22:10 +0000225 # The Pickler memo is a dictionary mapping object ids to 2-tuples
226 # that contain the Unpickler memo key and the object being memoized.
227 # The memo key is written to the pickle and will become
Jeremy Hylton3422c992003-01-24 19:29:52 +0000228 # the key in the Unpickler's memo. The object is stored in the
Tim Peterse46b73f2003-01-27 21:22:10 +0000229 # Pickler memo so that transient objects are kept alive during
230 # pickling.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000231
Tim Peterse46b73f2003-01-27 21:22:10 +0000232 # The use of the Unpickler memo length as the memo key is just a
233 # convention. The only requirement is that the memo values be unique.
234 # But there appears no advantage to any other scheme, and this
Tim Peterscbd0a322003-01-28 00:24:43 +0000235 # scheme allows the Unpickler memo to be implemented as a plain (but
Tim Peterse46b73f2003-01-27 21:22:10 +0000236 # growable) array, indexed by memo key.
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000237 if self.fast:
238 return
Guido van Rossum9b40e802003-01-30 06:37:41 +0000239 assert id(obj) not in self.memo
Jeremy Hylton3422c992003-01-24 19:29:52 +0000240 memo_len = len(self.memo)
241 self.write(self.put(memo_len))
Tim Peters518df0d2003-01-28 01:00:38 +0000242 self.memo[id(obj)] = memo_len, obj
Jeremy Hylton3422c992003-01-24 19:29:52 +0000243
Tim Petersbb38e302003-01-27 21:25:41 +0000244 # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000245 def put(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000246 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000247 if i < 256:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000248 return BINPUT + chr(i)
249 else:
250 return LONG_BINPUT + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000251
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000252 return PUT + `i` + '\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000253
Tim Petersbb38e302003-01-27 21:25:41 +0000254 # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000255 def get(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000256 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000257 if i < 256:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000258 return BINGET + chr(i)
259 else:
260 return LONG_BINGET + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000261
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000262 return GET + `i` + '\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000263
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000264 def save(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000265 # Check for persistent id (defined by a subclass)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000266 pid = self.persistent_id(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000267 if pid:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000268 self.save_pers(pid)
269 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000270
Guido van Rossumbc64e222003-01-28 16:34:19 +0000271 # Check the memo
272 x = self.memo.get(id(obj))
273 if x:
274 self.write(self.get(x[0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000275 return
276
Guido van Rossumbc64e222003-01-28 16:34:19 +0000277 # Check the type dispatch table
Guido van Rossum3a41c612003-01-28 15:10:22 +0000278 t = type(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000279 f = self.dispatch.get(t)
280 if f:
281 f(self, obj) # Call unbound method with explicit self
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000282 return
283
Guido van Rossumbc64e222003-01-28 16:34:19 +0000284 # Check for a class with a custom metaclass; treat as regular class
Tim Petersb32a8312003-01-28 00:48:09 +0000285 try:
286 issc = issubclass(t, TypeType)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000287 except TypeError: # t is not a class (old Boost; see SF #502085)
Tim Petersb32a8312003-01-28 00:48:09 +0000288 issc = 0
289 if issc:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000290 self.save_global(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000291 return
292
Guido van Rossumbc64e222003-01-28 16:34:19 +0000293 # Check copy_reg.dispatch_table
294 reduce = dispatch_table.get(t)
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000295 if not reduce:
296 # Check for a __reduce__ method.
297 # Subtle: get the unbound method from the class, so that
298 # protocol 2 can override the default __reduce__ that all
299 # classes inherit from object. This has the added
300 # advantage that the call always has the form reduce(obj)
301 reduce = getattr(t, "__reduce__", None)
302 if self.proto >= 2:
303 # Protocol 2 can do better than the default __reduce__
304 if reduce is object.__reduce__:
305 reduce = None
306 if not reduce:
Guido van Rossum54fb1922003-01-28 18:22:35 +0000307 self.save_newobj(obj)
308 return
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000309 if not reduce:
Guido van Rossumbc64e222003-01-28 16:34:19 +0000310 raise PicklingError("Can't pickle %r object: %r" %
311 (t.__name__, obj))
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000312 rv = reduce(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000313
Guido van Rossumbc64e222003-01-28 16:34:19 +0000314 # Check for string returned by reduce(), meaning "save as global"
315 if type(rv) is StringType:
316 self.save_global(obj, rv)
Tim Petersb32a8312003-01-28 00:48:09 +0000317 return
318
Guido van Rossumbc64e222003-01-28 16:34:19 +0000319 # Assert that reduce() returned a tuple
320 if type(rv) is not TupleType:
321 raise PicklingError("%s must return string or tuple" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000322
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000323 # Assert that it returned an appropriately sized tuple
Guido van Rossumbc64e222003-01-28 16:34:19 +0000324 l = len(rv)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000325 if not (2 <= l <= 5):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000326 raise PicklingError("Tuple returned by %s must have "
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000327 "two to five elements" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000328
Guido van Rossumbc64e222003-01-28 16:34:19 +0000329 # Save the reduce() output and finally memoize the object
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000330 self.save_reduce(obj=obj, *rv)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000331
Guido van Rossum3a41c612003-01-28 15:10:22 +0000332 def persistent_id(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000333 # This exists so a subclass can override it
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000334 return None
335
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000336 def save_pers(self, pid):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000337 # Save a persistent id reference
Tim Petersbd1cdb92003-01-28 01:03:10 +0000338 if self.bin:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000339 self.save(pid)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000340 self.write(BINPERSID)
Tim Petersbd1cdb92003-01-28 01:03:10 +0000341 else:
342 self.write(PERSID + str(pid) + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000343
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000344 def save_reduce(self, func, args, state=None,
345 listitems=None, dictitems=None, obj=None):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000346 # This API is be called by some subclasses
347
348 # Assert that args is a tuple or None
349 if not isinstance(args, TupleType):
350 if args is None:
351 # A hack for Jim Fulton's ExtensionClass, now deprecated.
352 # See load_reduce()
353 warnings.warn("__basicnew__ special case is deprecated",
354 DeprecationWarning)
355 else:
356 raise PicklingError(
357 "args from reduce() should be a tuple")
358
359 # Assert that func is callable
360 if not callable(func):
361 raise PicklingError("func from reduce should be callable")
362
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000363 save = self.save
Guido van Rossumbc64e222003-01-28 16:34:19 +0000364 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000365
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000366 # Protocol 2 special case: if func's name is __newobj__, use NEWOBJ
367 if self.proto >= 2 and getattr(func, "__name__", "") == "__newobj__":
368 # A __reduce__ implementation can direct protocol 2 to
369 # use the more efficient NEWOBJ opcode, while still
370 # allowing protocol 0 and 1 to work normally. For this to
371 # work, the function returned by __reduce__ should be
372 # called __newobj__, and its first argument should be a
373 # new-style class. The implementation for __newobj__
374 # should be as follows, although pickle has no way to
375 # verify this:
376 #
377 # def __newobj__(cls, *args):
378 # return cls.__new__(cls, *args)
379 #
380 # Protocols 0 and 1 will pickle a reference to __newobj__,
381 # while protocol 2 (and above) will pickle a reference to
382 # cls, the remaining args tuple, and the NEWOBJ code,
383 # which calls cls.__new__(cls, *args) at unpickling time
384 # (see load_newobj below). If __reduce__ returns a
385 # three-tuple, the state from the third tuple item will be
386 # pickled regardless of the protocol, calling __setstate__
387 # at unpickling time (see load_build below).
388 #
389 # Note that no standard __newobj__ implementation exists;
390 # you have to provide your own. This is to enforce
391 # compatibility with Python 2.2 (pickles written using
392 # protocol 0 or 1 in Python 2.3 should be unpicklable by
393 # Python 2.2).
394 cls = args[0]
395 if not hasattr(cls, "__new__"):
396 raise PicklingError(
397 "args[0] from __newobj__ args has no __new__")
Guido van Rossumf7f45172003-01-31 17:17:49 +0000398 if obj is not None and cls is not obj.__class__:
399 raise PicklingError(
400 "args[0] from __newobj__ args has the wrong class")
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000401 args = args[1:]
402 save(cls)
403 save(args)
404 write(NEWOBJ)
405 else:
406 save(func)
407 save(args)
408 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000409
Guido van Rossumf7f45172003-01-31 17:17:49 +0000410 if obj is not None:
411 self.memoize(obj)
412
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000413 # More new special cases (that work with older protocols as
414 # well): when __reduce__ returns a tuple with 4 or 5 items,
415 # the 4th and 5th item should be iterators that provide list
416 # items and dict items (as (key, value) tuples), or None.
417
418 if listitems is not None:
419 self._batch_appends(listitems)
420
421 if dictitems is not None:
422 self._batch_setitems(dictitems)
423
Tim Petersc32d8242001-04-10 02:48:53 +0000424 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000425 save(state)
426 write(BUILD)
427
Guido van Rossum54fb1922003-01-28 18:22:35 +0000428 def save_newobj(self, obj):
429 # Save a new-style class instance, using protocol 2.
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000430 assert self.proto >= 2 # This only works for protocol 2
Guido van Rossum54fb1922003-01-28 18:22:35 +0000431 t = type(obj)
Guido van Rossum54fb1922003-01-28 18:22:35 +0000432 getnewargs = getattr(obj, "__getnewargs__", None)
433 if getnewargs:
Neal Norwitzd1740682003-01-31 04:04:23 +0000434 args = getnewargs() # This better not reference obj
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000435 else:
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000436 args = ()
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000437
438 save = self.save
439 write = self.write
440
Guido van Rossum9b40e802003-01-30 06:37:41 +0000441 self.save(t)
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000442 save(args)
443 write(NEWOBJ)
Guido van Rossum54fb1922003-01-28 18:22:35 +0000444 self.memoize(obj)
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000445
446 if isinstance(obj, list):
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000447 self._batch_appends(iter(obj))
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000448 elif isinstance(obj, dict):
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000449 self._batch_setitems(obj.iteritems())
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000450
Guido van Rossum54fb1922003-01-28 18:22:35 +0000451 getstate = getattr(obj, "__getstate__", None)
Guido van Rossum45486172003-01-30 05:39:04 +0000452
Guido van Rossum54fb1922003-01-28 18:22:35 +0000453 if getstate:
Guido van Rossum4fba2202003-01-30 05:41:19 +0000454 # A class may define both __getstate__ and __getnewargs__.
455 # If they are the same function, we ignore __getstate__.
456 # This is for the benefit of protocols 0 and 1, which don't
457 # use __getnewargs__. Note that the only way to make them
458 # the same function is something like this:
459 #
460 # class C(object):
461 # def __getstate__(self):
462 # return ...
463 # __getnewargs__ = __getstate__
464 #
465 # No tricks are needed to ignore __setstate__; it simply
466 # won't be called when we don't generate BUILD.
467 # Also note that when __getnewargs__ and __getstate__ are
468 # the same function, we don't do the default thing of
469 # looking for __dict__ and slots either -- it is assumed
470 # that __getnewargs__ returns all the state there is
471 # (which should be a safe assumption since __getstate__
472 # returns the *same* state).
473 if getstate == getnewargs:
474 return
475
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000476 try:
477 state = getstate()
478 except TypeError, err:
479 # XXX Catch generic exception caused by __slots__
480 if str(err) != ("a class that defines __slots__ "
481 "without defining __getstate__ "
482 "cannot be pickled"):
483 print repr(str(err))
484 raise # Not that specific exception
485 getstate = None
Guido van Rossum4fba2202003-01-30 05:41:19 +0000486
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000487 if not getstate:
Guido van Rossum54fb1922003-01-28 18:22:35 +0000488 state = getattr(obj, "__dict__", None)
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000489 if not state:
490 state = None
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000491 # If there are slots, the state becomes a tuple of two
492 # items: the first item the regular __dict__ or None, and
493 # the second a dict mapping slot names to slot values
494 names = _slotnames(t)
495 if names:
496 slots = {}
497 nil = []
498 for name in names:
499 value = getattr(obj, name, nil)
500 if value is not nil:
501 slots[name] = value
502 if slots:
503 state = (state, slots)
504
Guido van Rossum54fb1922003-01-28 18:22:35 +0000505 if state is not None:
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000506 save(state)
507 write(BUILD)
Guido van Rossum54fb1922003-01-28 18:22:35 +0000508
Guido van Rossumbc64e222003-01-28 16:34:19 +0000509 # Methods below this point are dispatched through the dispatch table
510
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000511 dispatch = {}
512
Guido van Rossum3a41c612003-01-28 15:10:22 +0000513 def save_none(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000514 self.write(NONE)
515 dispatch[NoneType] = save_none
516
Guido van Rossum3a41c612003-01-28 15:10:22 +0000517 def save_bool(self, obj):
Guido van Rossum7d97d312003-01-28 04:25:27 +0000518 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000519 self.write(obj and NEWTRUE or NEWFALSE)
Guido van Rossum7d97d312003-01-28 04:25:27 +0000520 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000521 self.write(obj and TRUE or FALSE)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000522 dispatch[bool] = save_bool
523
Guido van Rossum3a41c612003-01-28 15:10:22 +0000524 def save_int(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000525 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000526 # If the int is small enough to fit in a signed 4-byte 2's-comp
527 # format, we can store it more efficiently than the general
528 # case.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000529 # First one- and two-byte unsigned ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000530 if obj >= 0:
531 if obj <= 0xff:
532 self.write(BININT1 + chr(obj))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000533 return
Guido van Rossum3a41c612003-01-28 15:10:22 +0000534 if obj <= 0xffff:
Guido van Rossumba884f32003-01-29 20:14:23 +0000535 self.write("%c%c%c" % (BININT2, obj&0xff, obj>>8))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000536 return
537 # Next check for 4-byte signed ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000538 high_bits = obj >> 31 # note that Python shift sign-extends
Tim Petersd95c2df2003-01-28 03:41:54 +0000539 if high_bits == 0 or high_bits == -1:
Tim Peters44714002001-04-10 05:02:52 +0000540 # All high bits are copies of bit 2**31, so the value
541 # fits in a 4-byte signed int.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000542 self.write(BININT + pack("<i", obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000543 return
Tim Peters44714002001-04-10 05:02:52 +0000544 # Text pickle, or int too big to fit in signed 4-byte format.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000545 self.write(INT + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000546 dispatch[IntType] = save_int
547
Guido van Rossum3a41c612003-01-28 15:10:22 +0000548 def save_long(self, obj, pack=struct.pack):
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000549 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000550 bytes = encode_long(obj)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000551 n = len(bytes)
552 if n < 256:
553 self.write(LONG1 + chr(n) + bytes)
554 else:
555 self.write(LONG4 + pack("<i", n) + bytes)
Tim Petersee1a53c2003-02-02 02:57:53 +0000556 return
Guido van Rossum3a41c612003-01-28 15:10:22 +0000557 self.write(LONG + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000558 dispatch[LongType] = save_long
559
Guido van Rossum3a41c612003-01-28 15:10:22 +0000560 def save_float(self, obj, pack=struct.pack):
Guido van Rossumd3703791998-10-22 20:15:36 +0000561 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000562 self.write(BINFLOAT + pack('>d', obj))
Guido van Rossumd3703791998-10-22 20:15:36 +0000563 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000564 self.write(FLOAT + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000565 dispatch[FloatType] = save_float
566
Guido van Rossum3a41c612003-01-28 15:10:22 +0000567 def save_string(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000568 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000569 n = len(obj)
Tim Petersbbf63cd2003-01-27 21:15:36 +0000570 if n < 256:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000571 self.write(SHORT_BINSTRING + chr(n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000572 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000573 self.write(BINSTRING + pack("<i", n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000574 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000575 self.write(STRING + `obj` + '\n')
576 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000577 dispatch[StringType] = save_string
578
Guido van Rossum3a41c612003-01-28 15:10:22 +0000579 def save_unicode(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000580 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000581 encoding = obj.encode('utf-8')
Tim Petersbbf63cd2003-01-27 21:15:36 +0000582 n = len(encoding)
Guido van Rossum5c938d02003-01-28 03:03:08 +0000583 self.write(BINUNICODE + pack("<i", n) + encoding)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000584 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000585 obj = obj.replace("\\", "\\u005c")
586 obj = obj.replace("\n", "\\u000a")
587 self.write(UNICODE + obj.encode('raw-unicode-escape') + '\n')
588 self.memoize(obj)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000589 dispatch[UnicodeType] = save_unicode
590
Guido van Rossum31584cb2001-01-22 14:53:29 +0000591 if StringType == UnicodeType:
592 # This is true for Jython
Guido van Rossum3a41c612003-01-28 15:10:22 +0000593 def save_string(self, obj, pack=struct.pack):
594 unicode = obj.isunicode()
Guido van Rossum31584cb2001-01-22 14:53:29 +0000595
Tim Petersc32d8242001-04-10 02:48:53 +0000596 if self.bin:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000597 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000598 obj = obj.encode("utf-8")
599 l = len(obj)
Tim Petersc32d8242001-04-10 02:48:53 +0000600 if l < 256 and not unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000601 self.write(SHORT_BINSTRING + chr(l) + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000602 else:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000603 s = pack("<i", l)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000604 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000605 self.write(BINUNICODE + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000606 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000607 self.write(BINSTRING + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000608 else:
Tim Peters658cba62001-02-09 20:06:00 +0000609 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000610 obj = obj.replace("\\", "\\u005c")
611 obj = obj.replace("\n", "\\u000a")
612 obj = obj.encode('raw-unicode-escape')
613 self.write(UNICODE + obj + '\n')
Guido van Rossum31584cb2001-01-22 14:53:29 +0000614 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000615 self.write(STRING + `obj` + '\n')
616 self.memoize(obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000617 dispatch[StringType] = save_string
Tim Peters658cba62001-02-09 20:06:00 +0000618
Guido van Rossum3a41c612003-01-28 15:10:22 +0000619 def save_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000620 write = self.write
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000621 proto = self.proto
622
Guido van Rossum3a41c612003-01-28 15:10:22 +0000623 n = len(obj)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000624 if n == 0:
625 if proto:
626 write(EMPTY_TUPLE)
627 else:
628 write(MARK + TUPLE)
Tim Petersd97da802003-01-28 05:48:29 +0000629 return
630
631 save = self.save
632 memo = self.memo
633 if n <= 3 and proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000634 for element in obj:
Tim Petersd97da802003-01-28 05:48:29 +0000635 save(element)
636 # Subtle. Same as in the big comment below.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000637 if id(obj) in memo:
638 get = self.get(memo[id(obj)][0])
Tim Petersd97da802003-01-28 05:48:29 +0000639 write(POP * n + get)
640 else:
641 write(_tuplesize2code[n])
Guido van Rossum3a41c612003-01-28 15:10:22 +0000642 self.memoize(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000643 return
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000644
Tim Peters1d63c9f2003-02-02 20:29:39 +0000645 # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple
Tim Petersff57bff2003-01-28 05:34:53 +0000646 # has more than 3 elements.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000647 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000648 for element in obj:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000649 save(element)
650
Tim Peters1d63c9f2003-02-02 20:29:39 +0000651 if id(obj) in memo:
Tim Petersf558da02003-01-28 02:09:55 +0000652 # Subtle. d was not in memo when we entered save_tuple(), so
653 # the process of saving the tuple's elements must have saved
654 # the tuple itself: the tuple is recursive. The proper action
655 # now is to throw away everything we put on the stack, and
656 # simply GET the tuple (it's already constructed). This check
657 # could have been done in the "for element" loop instead, but
658 # recursive tuples are a rare thing.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000659 get = self.get(memo[id(obj)][0])
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000660 if proto:
Tim Petersf558da02003-01-28 02:09:55 +0000661 write(POP_MARK + get)
662 else: # proto 0 -- POP_MARK not available
Tim Petersd97da802003-01-28 05:48:29 +0000663 write(POP * (n+1) + get)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000664 return
665
Tim Peters1d63c9f2003-02-02 20:29:39 +0000666 # No recursion.
Tim Peters518df0d2003-01-28 01:00:38 +0000667 self.write(TUPLE)
Tim Peters1d63c9f2003-02-02 20:29:39 +0000668 self.memoize(obj)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000669
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000670 dispatch[TupleType] = save_tuple
671
Tim Petersa6ae9a22003-01-28 16:58:41 +0000672 # save_empty_tuple() isn't used by anything in Python 2.3. However, I
673 # found a Pickler subclass in Zope3 that calls it, so it's not harmless
674 # to remove it.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000675 def save_empty_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000676 self.write(EMPTY_TUPLE)
677
Guido van Rossum3a41c612003-01-28 15:10:22 +0000678 def save_list(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000679 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000680
Tim Petersc32d8242001-04-10 02:48:53 +0000681 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000682 write(EMPTY_LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000683 else: # proto 0 -- can't use EMPTY_LIST
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000684 write(MARK + LIST)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000685
686 self.memoize(obj)
687 self._batch_appends(iter(obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000688
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000689 dispatch[ListType] = save_list
690
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000691 _BATCHSIZE = 1000
692
693 def _batch_appends(self, items):
694 # Helper to batch up APPENDS sequences
695 save = self.save
696 write = self.write
697
698 if not self.bin:
699 for x in items:
700 save(x)
701 write(APPEND)
702 return
703
704 r = xrange(self._BATCHSIZE)
705 while items is not None:
706 tmp = []
707 for i in r:
708 try:
709 tmp.append(items.next())
710 except StopIteration:
711 items = None
712 break
713 n = len(tmp)
714 if n > 1:
715 write(MARK)
716 for x in tmp:
717 save(x)
718 write(APPENDS)
719 elif n:
720 save(tmp[0])
721 write(APPEND)
722 # else tmp is empty, and we're done
723
Guido van Rossum3a41c612003-01-28 15:10:22 +0000724 def save_dict(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000725 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000726
Tim Petersc32d8242001-04-10 02:48:53 +0000727 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000728 write(EMPTY_DICT)
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000729 else: # proto 0 -- can't use EMPTY_DICT
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000730 write(MARK + DICT)
731
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000732 self.memoize(obj)
733 self._batch_setitems(obj.iteritems())
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000734
735 dispatch[DictionaryType] = save_dict
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000736 if not PyStringMap is None:
737 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000738
Guido van Rossum25cb7df2003-01-31 18:53:21 +0000739 def _batch_setitems(self, items):
740 # Helper to batch up SETITEMS sequences; proto >= 1 only
741 save = self.save
742 write = self.write
743
744 if not self.bin:
745 for k, v in items:
746 save(k)
747 save(v)
748 write(SETITEM)
749 return
750
751 r = xrange(self._BATCHSIZE)
752 while items is not None:
753 tmp = []
754 for i in r:
755 try:
756 tmp.append(items.next())
757 except StopIteration:
758 items = None
759 break
760 n = len(tmp)
761 if n > 1:
762 write(MARK)
763 for k, v in tmp:
764 save(k)
765 save(v)
766 write(SETITEMS)
767 elif n:
768 k, v = tmp[0]
769 save(k)
770 save(v)
771 write(SETITEM)
772 # else tmp is empty, and we're done
773
Guido van Rossum3a41c612003-01-28 15:10:22 +0000774 def save_inst(self, obj):
775 cls = obj.__class__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000776
777 memo = self.memo
778 write = self.write
779 save = self.save
780
Guido van Rossum3a41c612003-01-28 15:10:22 +0000781 if hasattr(obj, '__getinitargs__'):
782 args = obj.__getinitargs__()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000783 len(args) # XXX Assert it's a sequence
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000784 _keep_alive(args, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000785 else:
786 args = ()
787
788 write(MARK)
789
Tim Petersc32d8242001-04-10 02:48:53 +0000790 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000791 save(cls)
Tim Peters3b769832003-01-28 03:51:36 +0000792 for arg in args:
793 save(arg)
794 write(OBJ)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000795 else:
Tim Peters3b769832003-01-28 03:51:36 +0000796 for arg in args:
797 save(arg)
798 write(INST + cls.__module__ + '\n' + cls.__name__ + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000799
Guido van Rossum3a41c612003-01-28 15:10:22 +0000800 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000801
802 try:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000803 getstate = obj.__getstate__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000804 except AttributeError:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000805 stuff = obj.__dict__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000806 else:
807 stuff = getstate()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000808 _keep_alive(stuff, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000809 save(stuff)
810 write(BUILD)
Tim Peters3b769832003-01-28 03:51:36 +0000811
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000812 dispatch[InstanceType] = save_inst
813
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000814 def save_global(self, obj, name=None, pack=struct.pack):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000815 write = self.write
816 memo = self.memo
817
Tim Petersc32d8242001-04-10 02:48:53 +0000818 if name is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000819 name = obj.__name__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000820
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000821 module = getattr(obj, "__module__", None)
822 if module is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000823 module = whichmodule(obj, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000824
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000825 try:
826 __import__(module)
827 mod = sys.modules[module]
828 klass = getattr(mod, name)
829 except (ImportError, KeyError, AttributeError):
830 raise PicklingError(
831 "Can't pickle %r: it's not found as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000832 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000833 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000834 if klass is not obj:
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000835 raise PicklingError(
836 "Can't pickle %r: it's not the same object as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000837 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000838
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000839 if self.proto >= 2:
840 code = extension_registry.get((module, name))
841 if code:
842 assert code > 0
843 if code <= 0xff:
844 write(EXT1 + chr(code))
845 elif code <= 0xffff:
Guido van Rossumba884f32003-01-29 20:14:23 +0000846 write("%c%c%c" % (EXT2, code&0xff, code>>8))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000847 else:
848 write(EXT4 + pack("<i", code))
849 return
850
Tim Peters518df0d2003-01-28 01:00:38 +0000851 write(GLOBAL + module + '\n' + name + '\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000852 self.memoize(obj)
Tim Peters3b769832003-01-28 03:51:36 +0000853
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000854 dispatch[ClassType] = save_global
855 dispatch[FunctionType] = save_global
856 dispatch[BuiltinFunctionType] = save_global
Tim Peters6d6c1a32001-08-02 04:15:00 +0000857 dispatch[TypeType] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000858
Guido van Rossum1be31752003-01-28 15:19:53 +0000859# Pickling helpers
Guido van Rossuma48061a1995-01-10 00:31:14 +0000860
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000861def _slotnames(cls):
862 """Return a list of slot names for a given class.
863
864 This needs to find slots defined by the class and its bases, so we
865 can't simply return the __slots__ attribute. We must walk down
866 the Method Resolution Order and concatenate the __slots__ of each
867 class found there. (This assumes classes don't modify their
868 __slots__ attribute to misrepresent their slots after the class is
869 defined.)
870 """
871 if not hasattr(cls, "__slots__"):
872 return []
873 names = []
874 for c in cls.__mro__:
875 if "__slots__" in c.__dict__:
876 names += list(c.__dict__["__slots__"])
877 return names
878
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000879def _keep_alive(x, memo):
880 """Keeps a reference to the object x in the memo.
881
882 Because we remember objects by their id, we have
883 to assure that possibly temporary objects are kept
884 alive by referencing them.
885 We store a reference at the id of the memo, which should
886 normally not be used unless someone tries to deepcopy
887 the memo itself...
888 """
889 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000890 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000891 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000892 # aha, this is the first one :-)
893 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000894
895
Tim Petersc0c12b52003-01-29 00:56:17 +0000896# A cache for whichmodule(), mapping a function object to the name of
897# the module in which the function was found.
898
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000899classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000900
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000901def whichmodule(func, funcname):
902 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000903
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000904 Search sys.modules for the module.
905 Cache in classmap.
906 Return a module name.
Tim Petersc0c12b52003-01-29 00:56:17 +0000907 If the function cannot be found, return "__main__".
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000908 """
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000909 # Python functions should always get an __module__ from their globals.
910 mod = getattr(func, "__module__", None)
911 if mod is not None:
912 return mod
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000913 if func in classmap:
914 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000915
916 for name, module in sys.modules.items():
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000917 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000918 continue # skip dummy package entries
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000919 if name != '__main__' and \
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000920 hasattr(module, funcname) and \
921 getattr(module, funcname) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000922 break
923 else:
924 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000925 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000926 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000927
928
Guido van Rossum1be31752003-01-28 15:19:53 +0000929# Unpickling machinery
930
Guido van Rossuma48061a1995-01-10 00:31:14 +0000931class Unpickler:
932
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000933 def __init__(self, file):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000934 """This takes a file-like object for reading a pickle data stream.
935
Tim Peters5bd2a792003-02-01 16:45:06 +0000936 The protocol version of the pickle is detected automatically, so no
937 proto argument is needed.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000938
939 The file-like object must have two methods, a read() method that
940 takes an integer argument, and a readline() method that requires no
941 arguments. Both methods should return a string. Thus file-like
942 object can be a file object opened for reading, a StringIO object,
943 or any other custom object that meets this interface.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000944 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000945 self.readline = file.readline
946 self.read = file.read
947 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000948
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000949 def load(self):
Guido van Rossum3a41c612003-01-28 15:10:22 +0000950 """Read a pickled object representation from the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000951
Guido van Rossum3a41c612003-01-28 15:10:22 +0000952 Return the reconstituted object hierarchy specified in the file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000953 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000954 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000955 self.stack = []
956 self.append = self.stack.append
957 read = self.read
958 dispatch = self.dispatch
959 try:
960 while 1:
961 key = read(1)
962 dispatch[key](self)
Guido van Rossumff871742000-12-13 18:11:56 +0000963 except _Stop, stopinst:
964 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000965
Tim Petersc23d18a2003-01-28 01:41:51 +0000966 # Return largest index k such that self.stack[k] is self.mark.
967 # If the stack doesn't contain a mark, eventually raises IndexError.
968 # This could be sped by maintaining another stack, of indices at which
969 # the mark appears. For that matter, the latter stack would suffice,
970 # and we wouldn't need to push mark objects on self.stack at all.
971 # Doing so is probably a good thing, though, since if the pickle is
972 # corrupt (or hostile) we may get a clue from finding self.mark embedded
973 # in unpickled objects.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000974 def marker(self):
975 stack = self.stack
976 mark = self.mark
977 k = len(stack)-1
978 while stack[k] is not mark: k = k-1
979 return k
980
981 dispatch = {}
982
983 def load_eof(self):
984 raise EOFError
985 dispatch[''] = load_eof
986
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000987 def load_proto(self):
988 proto = ord(self.read(1))
989 if not 0 <= proto <= 2:
990 raise ValueError, "unsupported pickle protocol: %d" % proto
991 dispatch[PROTO] = load_proto
992
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000993 def load_persid(self):
994 pid = self.readline()[:-1]
995 self.append(self.persistent_load(pid))
996 dispatch[PERSID] = load_persid
997
998 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000999 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001000 self.append(self.persistent_load(pid))
1001 dispatch[BINPERSID] = load_binpersid
1002
1003 def load_none(self):
1004 self.append(None)
1005 dispatch[NONE] = load_none
1006
Guido van Rossum7d97d312003-01-28 04:25:27 +00001007 def load_false(self):
1008 self.append(False)
1009 dispatch[NEWFALSE] = load_false
1010
1011 def load_true(self):
1012 self.append(True)
1013 dispatch[NEWTRUE] = load_true
1014
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001015 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +00001016 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +00001017 if data == FALSE[1:]:
1018 val = False
1019 elif data == TRUE[1:]:
1020 val = True
1021 else:
1022 try:
1023 val = int(data)
1024 except ValueError:
1025 val = long(data)
1026 self.append(val)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001027 dispatch[INT] = load_int
1028
1029 def load_binint(self):
1030 self.append(mloads('i' + self.read(4)))
1031 dispatch[BININT] = load_binint
1032
1033 def load_binint1(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001034 self.append(ord(self.read(1)))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001035 dispatch[BININT1] = load_binint1
1036
1037 def load_binint2(self):
1038 self.append(mloads('i' + self.read(2) + '\000\000'))
1039 dispatch[BININT2] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +00001040
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001041 def load_long(self):
Guido van Rossumff871742000-12-13 18:11:56 +00001042 self.append(long(self.readline()[:-1], 0))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001043 dispatch[LONG] = load_long
1044
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001045 def load_long1(self):
1046 n = ord(self.read(1))
1047 bytes = self.read(n)
Tim Petersee1a53c2003-02-02 02:57:53 +00001048 self.append(decode_long(bytes))
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001049 dispatch[LONG1] = load_long1
1050
1051 def load_long4(self):
1052 n = mloads('i' + self.read(4))
1053 bytes = self.read(n)
Tim Petersee1a53c2003-02-02 02:57:53 +00001054 self.append(decode_long(bytes))
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001055 dispatch[LONG4] = load_long4
1056
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001057 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +00001058 self.append(float(self.readline()[:-1]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001059 dispatch[FLOAT] = load_float
1060
Guido van Rossumd3703791998-10-22 20:15:36 +00001061 def load_binfloat(self, unpack=struct.unpack):
1062 self.append(unpack('>d', self.read(8))[0])
1063 dispatch[BINFLOAT] = load_binfloat
1064
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001065 def load_string(self):
Jeremy Hyltonbe467e52000-09-15 15:14:51 +00001066 rep = self.readline()[:-1]
Tim Petersad5a7712003-01-28 16:23:33 +00001067 for q in "\"'": # double or single quote
Martin v. Löwis8a8da792002-08-14 07:46:28 +00001068 if rep.startswith(q):
1069 if not rep.endswith(q):
1070 raise ValueError, "insecure string pickle"
1071 rep = rep[len(q):-len(q)]
1072 break
1073 else:
Jeremy Hyltonbe467e52000-09-15 15:14:51 +00001074 raise ValueError, "insecure string pickle"
Martin v. Löwis8a8da792002-08-14 07:46:28 +00001075 self.append(rep.decode("string-escape"))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001076 dispatch[STRING] = load_string
1077
1078 def load_binstring(self):
1079 len = mloads('i' + self.read(4))
1080 self.append(self.read(len))
1081 dispatch[BINSTRING] = load_binstring
1082
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +00001083 def load_unicode(self):
1084 self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
1085 dispatch[UNICODE] = load_unicode
1086
1087 def load_binunicode(self):
1088 len = mloads('i' + self.read(4))
1089 self.append(unicode(self.read(len),'utf-8'))
1090 dispatch[BINUNICODE] = load_binunicode
1091
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001092 def load_short_binstring(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001093 len = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001094 self.append(self.read(len))
1095 dispatch[SHORT_BINSTRING] = load_short_binstring
1096
1097 def load_tuple(self):
1098 k = self.marker()
1099 self.stack[k:] = [tuple(self.stack[k+1:])]
1100 dispatch[TUPLE] = load_tuple
1101
1102 def load_empty_tuple(self):
1103 self.stack.append(())
1104 dispatch[EMPTY_TUPLE] = load_empty_tuple
1105
Guido van Rossum44f0ea52003-01-28 04:14:51 +00001106 def load_tuple1(self):
1107 self.stack[-1] = (self.stack[-1],)
1108 dispatch[TUPLE1] = load_tuple1
1109
1110 def load_tuple2(self):
1111 self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
1112 dispatch[TUPLE2] = load_tuple2
1113
1114 def load_tuple3(self):
1115 self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
1116 dispatch[TUPLE3] = load_tuple3
1117
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001118 def load_empty_list(self):
1119 self.stack.append([])
1120 dispatch[EMPTY_LIST] = load_empty_list
1121
1122 def load_empty_dictionary(self):
1123 self.stack.append({})
1124 dispatch[EMPTY_DICT] = load_empty_dictionary
1125
1126 def load_list(self):
1127 k = self.marker()
1128 self.stack[k:] = [self.stack[k+1:]]
1129 dispatch[LIST] = load_list
1130
1131 def load_dict(self):
1132 k = self.marker()
1133 d = {}
1134 items = self.stack[k+1:]
1135 for i in range(0, len(items), 2):
1136 key = items[i]
1137 value = items[i+1]
1138 d[key] = value
1139 self.stack[k:] = [d]
1140 dispatch[DICT] = load_dict
1141
Tim Petersd01c1e92003-01-30 15:41:46 +00001142 # INST and OBJ differ only in how they get a class object. It's not
1143 # only sensible to do the rest in a common routine, the two routines
1144 # previously diverged and grew different bugs.
1145 # klass is the class to instantiate, and k points to the topmost mark
1146 # object, following which are the arguments for klass.__init__.
1147 def _instantiate(self, klass, k):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001148 args = tuple(self.stack[k+1:])
1149 del self.stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001150 instantiated = 0
Tim Petersd01c1e92003-01-30 15:41:46 +00001151 if (not args and
1152 type(klass) is ClassType and
1153 not hasattr(klass, "__getinitargs__")):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001154 try:
1155 value = _EmptyClass()
1156 value.__class__ = klass
Guido van Rossumb19e2a31998-04-13 18:08:45 +00001157 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001158 except RuntimeError:
1159 # In restricted execution, assignment to inst.__class__ is
1160 # prohibited
1161 pass
1162 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +00001163 try:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001164 value = klass(*args)
Guido van Rossum743d17e1998-09-15 20:25:57 +00001165 except TypeError, err:
1166 raise TypeError, "in constructor for %s: %s" % (
1167 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001168 self.append(value)
Tim Petersd01c1e92003-01-30 15:41:46 +00001169
1170 def load_inst(self):
1171 module = self.readline()[:-1]
1172 name = self.readline()[:-1]
1173 klass = self.find_class(module, name)
1174 self._instantiate(klass, self.marker())
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001175 dispatch[INST] = load_inst
1176
1177 def load_obj(self):
Tim Petersd01c1e92003-01-30 15:41:46 +00001178 # Stack is ... markobject classobject arg1 arg2 ...
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001179 k = self.marker()
Tim Petersd01c1e92003-01-30 15:41:46 +00001180 klass = self.stack.pop(k+1)
1181 self._instantiate(klass, k)
Tim Peters2344fae2001-01-15 00:50:52 +00001182 dispatch[OBJ] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001183
Guido van Rossum3a41c612003-01-28 15:10:22 +00001184 def load_newobj(self):
1185 args = self.stack.pop()
1186 cls = self.stack[-1]
1187 obj = cls.__new__(cls, *args)
Guido van Rossum533dbcf2003-01-28 17:55:05 +00001188 self.stack[-1] = obj
Guido van Rossum3a41c612003-01-28 15:10:22 +00001189 dispatch[NEWOBJ] = load_newobj
1190
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001191 def load_global(self):
1192 module = self.readline()[:-1]
1193 name = self.readline()[:-1]
1194 klass = self.find_class(module, name)
1195 self.append(klass)
1196 dispatch[GLOBAL] = load_global
1197
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001198 def load_ext1(self):
1199 code = ord(self.read(1))
1200 self.get_extension(code)
1201 dispatch[EXT1] = load_ext1
1202
1203 def load_ext2(self):
1204 code = mloads('i' + self.read(2) + '\000\000')
1205 self.get_extension(code)
1206 dispatch[EXT2] = load_ext2
1207
1208 def load_ext4(self):
1209 code = mloads('i' + self.read(4))
1210 self.get_extension(code)
1211 dispatch[EXT4] = load_ext4
1212
1213 def get_extension(self, code):
1214 nil = []
1215 obj = extension_cache.get(code, nil)
1216 if obj is not nil:
1217 self.append(obj)
1218 return
1219 key = inverted_registry.get(code)
1220 if not key:
1221 raise ValueError("unregistered extension code %d" % code)
1222 obj = self.find_class(*key)
1223 extension_cache[code] = obj
1224 self.append(obj)
1225
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001226 def find_class(self, module, name):
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001227 # Subclasses may override this
Barry Warsawbf4d9592001-11-15 23:42:58 +00001228 __import__(module)
1229 mod = sys.modules[module]
1230 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001231 return klass
1232
1233 def load_reduce(self):
1234 stack = self.stack
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001235 args = stack.pop()
1236 func = stack[-1]
1237 if args is None:
Guido van Rossumbc64e222003-01-28 16:34:19 +00001238 # A hack for Jim Fulton's ExtensionClass, now deprecated
1239 warnings.warn("__basicnew__ special case is deprecated",
Tim Peters8ac14952002-05-23 15:15:30 +00001240 DeprecationWarning)
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001241 value = func.__basicnew__()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001242 else:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001243 value = func(*args)
1244 stack[-1] = value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001245 dispatch[REDUCE] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +00001246
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001247 def load_pop(self):
1248 del self.stack[-1]
1249 dispatch[POP] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +00001250
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001251 def load_pop_mark(self):
1252 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001253 del self.stack[k:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001254 dispatch[POP_MARK] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001255
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001256 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +00001257 self.append(self.stack[-1])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001258 dispatch[DUP] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +00001259
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001260 def load_get(self):
1261 self.append(self.memo[self.readline()[:-1]])
1262 dispatch[GET] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +00001263
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001264 def load_binget(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001265 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001266 self.append(self.memo[`i`])
1267 dispatch[BINGET] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001268
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001269 def load_long_binget(self):
1270 i = mloads('i' + self.read(4))
1271 self.append(self.memo[`i`])
1272 dispatch[LONG_BINGET] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001273
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001274 def load_put(self):
1275 self.memo[self.readline()[:-1]] = self.stack[-1]
1276 dispatch[PUT] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +00001277
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001278 def load_binput(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001279 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001280 self.memo[`i`] = self.stack[-1]
1281 dispatch[BINPUT] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001282
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001283 def load_long_binput(self):
1284 i = mloads('i' + self.read(4))
1285 self.memo[`i`] = self.stack[-1]
1286 dispatch[LONG_BINPUT] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001287
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001288 def load_append(self):
1289 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001290 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001291 list = stack[-1]
1292 list.append(value)
1293 dispatch[APPEND] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +00001294
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001295 def load_appends(self):
1296 stack = self.stack
1297 mark = self.marker()
1298 list = stack[mark - 1]
Tim Peters209ad952003-01-28 01:44:45 +00001299 list.extend(stack[mark + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001300 del stack[mark:]
1301 dispatch[APPENDS] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +00001302
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001303 def load_setitem(self):
1304 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001305 value = stack.pop()
1306 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001307 dict = stack[-1]
1308 dict[key] = value
1309 dispatch[SETITEM] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001310
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001311 def load_setitems(self):
1312 stack = self.stack
1313 mark = self.marker()
1314 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001315 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001316 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001317
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001318 del stack[mark:]
1319 dispatch[SETITEMS] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001320
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001321 def load_build(self):
1322 stack = self.stack
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001323 state = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001324 inst = stack[-1]
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001325 setstate = getattr(inst, "__setstate__", None)
1326 if setstate:
1327 setstate(state)
1328 return
1329 slotstate = None
1330 if isinstance(state, tuple) and len(state) == 2:
1331 state, slotstate = state
1332 if state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001333 try:
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001334 inst.__dict__.update(state)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001335 except RuntimeError:
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001336 # XXX In restricted execution, the instance's __dict__
1337 # is not accessible. Use the old way of unpickling
1338 # the instance variables. This is a semantic
1339 # difference when unpickling in restricted
1340 # vs. unrestricted modes.
1341 for k, v in state.items():
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001342 setattr(inst, k, v)
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001343 if slotstate:
1344 for k, v in slotstate.items():
1345 setattr(inst, k, v)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001346 dispatch[BUILD] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001347
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001348 def load_mark(self):
1349 self.append(self.mark)
1350 dispatch[MARK] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001351
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001352 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001353 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001354 raise _Stop(value)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001355 dispatch[STOP] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001356
Guido van Rossume467be61997-12-05 19:42:42 +00001357# Helper class for load_inst/load_obj
1358
1359class _EmptyClass:
1360 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001361
Tim Peters91149822003-01-31 03:43:58 +00001362# Encode/decode longs in linear time.
1363
1364import binascii as _binascii
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001365
1366def encode_long(x):
Tim Peters91149822003-01-31 03:43:58 +00001367 r"""Encode a long to a two's complement little-endian binary string.
Tim Peters4b23f2b2003-01-31 16:43:39 +00001368 Note that 0L is a special case, returning an empty string, to save a
1369 byte in the LONG1 pickling context.
1370
1371 >>> encode_long(0L)
1372 ''
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001373 >>> encode_long(255L)
1374 '\xff\x00'
1375 >>> encode_long(32767L)
1376 '\xff\x7f'
1377 >>> encode_long(-256L)
1378 '\x00\xff'
1379 >>> encode_long(-32768L)
1380 '\x00\x80'
1381 >>> encode_long(-128L)
1382 '\x80'
1383 >>> encode_long(127L)
1384 '\x7f'
1385 >>>
1386 """
Tim Peters91149822003-01-31 03:43:58 +00001387
1388 if x == 0:
Tim Peters4b23f2b2003-01-31 16:43:39 +00001389 return ''
Tim Peters91149822003-01-31 03:43:58 +00001390 if x > 0:
1391 ashex = hex(x)
1392 assert ashex.startswith("0x")
1393 njunkchars = 2 + ashex.endswith('L')
1394 nibbles = len(ashex) - njunkchars
1395 if nibbles & 1:
1396 # need an even # of nibbles for unhexlify
1397 ashex = "0x0" + ashex[2:]
Tim Peters4b23f2b2003-01-31 16:43:39 +00001398 elif int(ashex[2], 16) >= 8:
Tim Peters91149822003-01-31 03:43:58 +00001399 # "looks negative", so need a byte of sign bits
1400 ashex = "0x00" + ashex[2:]
1401 else:
1402 # Build the 256's-complement: (1L << nbytes) + x. The trick is
1403 # to find the number of bytes in linear time (although that should
1404 # really be a constant-time task).
1405 ashex = hex(-x)
1406 assert ashex.startswith("0x")
1407 njunkchars = 2 + ashex.endswith('L')
1408 nibbles = len(ashex) - njunkchars
1409 if nibbles & 1:
Tim Petersee1a53c2003-02-02 02:57:53 +00001410 # Extend to a full byte.
Tim Peters91149822003-01-31 03:43:58 +00001411 nibbles += 1
Tim Peters4b23f2b2003-01-31 16:43:39 +00001412 nbits = nibbles * 4
1413 x += 1L << nbits
Tim Peters91149822003-01-31 03:43:58 +00001414 assert x > 0
1415 ashex = hex(x)
Tim Petersee1a53c2003-02-02 02:57:53 +00001416 njunkchars = 2 + ashex.endswith('L')
1417 newnibbles = len(ashex) - njunkchars
1418 if newnibbles < nibbles:
1419 ashex = "0x" + "0" * (nibbles - newnibbles) + ashex[2:]
1420 if int(ashex[2], 16) < 8:
Tim Peters91149822003-01-31 03:43:58 +00001421 # "looks positive", so need a byte of sign bits
Tim Petersee1a53c2003-02-02 02:57:53 +00001422 ashex = "0xff" + ashex[2:]
Tim Peters91149822003-01-31 03:43:58 +00001423
1424 if ashex.endswith('L'):
1425 ashex = ashex[2:-1]
1426 else:
1427 ashex = ashex[2:]
Tim Petersee1a53c2003-02-02 02:57:53 +00001428 assert len(ashex) & 1 == 0, (x, ashex)
Tim Peters91149822003-01-31 03:43:58 +00001429 binary = _binascii.unhexlify(ashex)
1430 return binary[::-1]
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001431
1432def decode_long(data):
1433 r"""Decode a long from a two's complement little-endian binary string.
Tim Peters4b23f2b2003-01-31 16:43:39 +00001434
1435 >>> decode_long('')
1436 0L
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001437 >>> decode_long("\xff\x00")
1438 255L
1439 >>> decode_long("\xff\x7f")
1440 32767L
1441 >>> decode_long("\x00\xff")
1442 -256L
1443 >>> decode_long("\x00\x80")
1444 -32768L
1445 >>> decode_long("\x80")
1446 -128L
1447 >>> decode_long("\x7f")
1448 127L
1449 """
Tim Peters91149822003-01-31 03:43:58 +00001450
Tim Peters4b23f2b2003-01-31 16:43:39 +00001451 nbytes = len(data)
1452 if nbytes == 0:
1453 return 0L
Tim Peters91149822003-01-31 03:43:58 +00001454 ashex = _binascii.hexlify(data[::-1])
Tim Petersbf2674b2003-02-02 07:51:32 +00001455 n = long(ashex, 16) # quadratic time before Python 2.3; linear now
Tim Peters91149822003-01-31 03:43:58 +00001456 if data[-1] >= '\x80':
Tim Peters4b23f2b2003-01-31 16:43:39 +00001457 n -= 1L << (nbytes * 8)
Tim Peters91149822003-01-31 03:43:58 +00001458 return n
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001459
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001460# Shorthands
1461
Jeremy Hyltonabe2c622001-10-15 21:29:28 +00001462try:
1463 from cStringIO import StringIO
1464except ImportError:
1465 from StringIO import StringIO
Guido van Rossumc7c5e691996-07-22 22:26:07 +00001466
Guido van Rossum7eff63a2003-01-31 19:42:31 +00001467def dump(obj, file, proto=0):
Guido van Rossum3a41c612003-01-28 15:10:22 +00001468 Pickler(file, proto).dump(obj)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001469
Guido van Rossum7eff63a2003-01-31 19:42:31 +00001470def dumps(obj, proto=0):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001471 file = StringIO()
Guido van Rossum3a41c612003-01-28 15:10:22 +00001472 Pickler(file, proto).dump(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001473 return file.getvalue()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001474
1475def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001476 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001477
1478def loads(str):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001479 file = StringIO(str)
1480 return Unpickler(file).load()
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001481
1482# Doctest
1483
1484def _test():
1485 import doctest
1486 return doctest.testmod()
1487
1488if __name__ == "__main__":
1489 _test()