blob: d767d85c1587d8d32b5d3b813fc6aa4357d53a3f [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 Rossum3d8c01b2003-01-28 19:48:18 +000030from copy_reg import dispatch_table, safe_constructors, _reconstructor
Guido van Rossumd3703791998-10-22 20:15:36 +000031import marshal
32import sys
33import struct
Skip Montanaro23bafc62001-02-18 03:10:09 +000034import re
Guido van Rossumbc64e222003-01-28 16:34:19 +000035import warnings
Guido van Rossuma48061a1995-01-10 00:31:14 +000036
Skip Montanaro352674d2001-02-07 23:14:30 +000037__all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler",
38 "Unpickler", "dump", "dumps", "load", "loads"]
39
Guido van Rossumf29d3d62003-01-27 22:47:53 +000040# These are purely informational; no code usues these
41format_version = "2.0" # File format version we write
42compatible_formats = ["1.0", # Original protocol 0
Guido van Rossumbc64e222003-01-28 16:34:19 +000043 "1.1", # Protocol 0 with INST added
Guido van Rossumf29d3d62003-01-27 22:47:53 +000044 "1.2", # Original protocol 1
45 "1.3", # Protocol 1 with BINFLOAT added
46 "2.0", # Protocol 2
47 ] # Old format versions we can read
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000048
Guido van Rossume0b90422003-01-28 03:17:21 +000049# Why use struct.pack() for pickling but marshal.loads() for
50# unpickling? struct.pack() is 40% faster than marshal.loads(), but
51# marshal.loads() is twice as fast as struct.unpack()!
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000052mloads = marshal.loads
Guido van Rossum0c891ce1995-03-14 15:09:05 +000053
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000054class PickleError(Exception):
Neal Norwitzefbb67b2002-05-30 12:12:04 +000055 """A common base class for the other pickling exceptions."""
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000056 pass
57
58class PicklingError(PickleError):
59 """This exception is raised when an unpicklable object is passed to the
60 dump() method.
61
62 """
63 pass
64
65class UnpicklingError(PickleError):
66 """This exception is raised when there is a problem unpickling an object,
67 such as a security violation.
68
69 Note that other exceptions may also be raised during unpickling, including
70 (but not necessarily limited to) AttributeError, EOFError, ImportError,
71 and IndexError.
72
73 """
74 pass
Guido van Rossum7849da81995-03-09 14:08:35 +000075
Guido van Rossumff871742000-12-13 18:11:56 +000076class _Stop(Exception):
77 def __init__(self, value):
78 self.value = value
79
Guido van Rossum533dbcf2003-01-28 17:55:05 +000080# Jython has PyStringMap; it's a dict subclass with string keys
Jeremy Hylton2b9d0291998-05-27 22:38:22 +000081try:
82 from org.python.core import PyStringMap
83except ImportError:
84 PyStringMap = None
85
Guido van Rossum533dbcf2003-01-28 17:55:05 +000086# UnicodeType may or may not be exported (normally imported from types)
Guido van Rossumdbb718f2001-09-21 19:22:34 +000087try:
88 UnicodeType
89except NameError:
90 UnicodeType = None
91
Tim Peters22a449a2003-01-27 20:16:36 +000092# Pickle opcodes. See pickletools.py for extensive docs. The listing
93# here is in kind-of alphabetical order of 1-character pickle code.
94# pickletools groups them by purpose.
Guido van Rossumdbb718f2001-09-21 19:22:34 +000095
Tim Peters22a449a2003-01-27 20:16:36 +000096MARK = '(' # push special markobject on stack
97STOP = '.' # every pickle ends with STOP
98POP = '0' # discard topmost stack item
99POP_MARK = '1' # discard stack top through topmost markobject
100DUP = '2' # duplicate top stack item
101FLOAT = 'F' # push float object; decimal string argument
102INT = 'I' # push integer or bool; decimal string argument
103BININT = 'J' # push four-byte signed int
104BININT1 = 'K' # push 1-byte unsigned int
105LONG = 'L' # push long; decimal string argument
106BININT2 = 'M' # push 2-byte unsigned int
107NONE = 'N' # push None
108PERSID = 'P' # push persistent object; id is taken from string arg
109BINPERSID = 'Q' # " " " ; " " " " stack
110REDUCE = 'R' # apply callable to argtuple, both on stack
111STRING = 'S' # push string; NL-terminated string argument
112BINSTRING = 'T' # push string; counted binary string argument
113SHORT_BINSTRING = 'U' # " " ; " " " " < 256 bytes
114UNICODE = 'V' # push Unicode string; raw-unicode-escaped'd argument
115BINUNICODE = 'X' # " " " ; counted UTF-8 string argument
116APPEND = 'a' # append stack top to list below it
117BUILD = 'b' # call __setstate__ or __dict__.update()
118GLOBAL = 'c' # push self.find_class(modname, name); 2 string args
119DICT = 'd' # build a dict from stack items
120EMPTY_DICT = '}' # push empty dict
121APPENDS = 'e' # extend list on stack by topmost stack slice
122GET = 'g' # push item from memo on stack; index is string arg
123BINGET = 'h' # " " " " " " ; " " 1-byte arg
124INST = 'i' # build & push class instance
125LONG_BINGET = 'j' # push item from memo on stack; index is 4-byte arg
126LIST = 'l' # build list from topmost stack items
127EMPTY_LIST = ']' # push empty list
128OBJ = 'o' # build & push class instance
129PUT = 'p' # store stack top in memo; index is string arg
130BINPUT = 'q' # " " " " " ; " " 1-byte arg
131LONG_BINPUT = 'r' # " " " " " ; " " 4-byte arg
132SETITEM = 's' # add key+value pair to dict
133TUPLE = 't' # build tuple from topmost stack items
134EMPTY_TUPLE = ')' # push empty tuple
135SETITEMS = 'u' # modify dict by adding topmost key+value pairs
136BINFLOAT = 'G' # push float; arg is 8-byte float encoding
137
138TRUE = 'I01\n' # not an opcode; see INT docs in pickletools.py
139FALSE = 'I00\n' # not an opcode; see INT docs in pickletools.py
Guido van Rossum77f6a652002-04-03 22:41:51 +0000140
Tim Peterse1054782003-01-28 00:22:12 +0000141# Protocol 2 (not yet implemented).
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000142
Tim Peterse1054782003-01-28 00:22:12 +0000143PROTO = '\x80' # identify pickle protocol
144NEWOBJ = '\x81' # build object by applying cls.__new__ to argtuple
145EXT1 = '\x82' # push object from extension registry; 1-byte index
146EXT2 = '\x83' # ditto, but 2-byte index
147EXT4 = '\x84' # ditto, but 4-byte index
148TUPLE1 = '\x85' # build 1-tuple from stack top
149TUPLE2 = '\x86' # build 2-tuple from two topmost stack items
150TUPLE3 = '\x87' # build 3-tuple from three topmost stack items
151NEWTRUE = '\x88' # push True
152NEWFALSE = '\x89' # push False
153LONG1 = '\x8a' # push long from < 256 bytes
154LONG4 = '\x8b' # push really big long
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000155
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000156_tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3]
157
Guido van Rossuma48061a1995-01-10 00:31:14 +0000158
Skip Montanaro23bafc62001-02-18 03:10:09 +0000159__all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
Neal Norwitzd5ba4ae2002-02-11 18:12:06 +0000160del x
Skip Montanaro23bafc62001-02-18 03:10:09 +0000161
Guido van Rossum1be31752003-01-28 15:19:53 +0000162
163# Pickling machinery
164
Guido van Rossuma48061a1995-01-10 00:31:14 +0000165class Pickler:
166
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000167 def __init__(self, file, proto=1):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000168 """This takes a file-like object for writing a pickle data stream.
169
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000170 The optional proto argument tells the pickler to use the given
171 protocol; supported protocols are 0, 1, 2. The default
172 protocol is 1 (in previous Python versions the default was 0).
173
174 Protocol 1 is more efficient than protocol 0; protocol 2 is
175 more efficient than protocol 1. Protocol 2 is not the default
176 because it is not supported by older Python versions.
177
178 XXX Protocol 2 is not yet implemented.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000179
180 The file parameter must have a write() method that accepts a single
181 string argument. It can thus be an open file object, a StringIO
182 object, or any other custom object that meets this interface.
183
184 """
Guido van Rossum1be31752003-01-28 15:19:53 +0000185 if proto not in (0, 1, 2):
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000186 raise ValueError, "pickle protocol must be 0, 1 or 2"
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000187 self.write = file.write
188 self.memo = {}
Guido van Rossum1be31752003-01-28 15:19:53 +0000189 self.proto = int(proto)
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000190 self.bin = proto >= 1
Guido van Rossuma48061a1995-01-10 00:31:14 +0000191
Fred Drake7f781c92002-05-01 20:33:53 +0000192 def clear_memo(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000193 """Clears the pickler's "memo".
194
195 The memo is the data structure that remembers which objects the
Tim Petersb377f8a2003-01-28 00:23:36 +0000196 pickler has already seen, so that shared or recursive objects are
197 pickled by reference and not by value. This method is useful when
198 re-using picklers.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000199
200 """
Fred Drake7f781c92002-05-01 20:33:53 +0000201 self.memo.clear()
202
Guido van Rossum3a41c612003-01-28 15:10:22 +0000203 def dump(self, obj):
204 """Write a pickled representation of obj to the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000205
206 Either the binary or ASCII format will be used, depending on the
207 value of the bin flag passed to the constructor.
208
209 """
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000210 if self.proto >= 2:
211 self.write(PROTO + chr(self.proto))
Guido van Rossum3a41c612003-01-28 15:10:22 +0000212 self.save(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000213 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000214
Jeremy Hylton3422c992003-01-24 19:29:52 +0000215 def memoize(self, obj):
216 """Store an object in the memo."""
217
Tim Peterse46b73f2003-01-27 21:22:10 +0000218 # The Pickler memo is a dictionary mapping object ids to 2-tuples
219 # that contain the Unpickler memo key and the object being memoized.
220 # The memo key is written to the pickle and will become
Jeremy Hylton3422c992003-01-24 19:29:52 +0000221 # the key in the Unpickler's memo. The object is stored in the
Tim Peterse46b73f2003-01-27 21:22:10 +0000222 # Pickler memo so that transient objects are kept alive during
223 # pickling.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000224
Tim Peterse46b73f2003-01-27 21:22:10 +0000225 # The use of the Unpickler memo length as the memo key is just a
226 # convention. The only requirement is that the memo values be unique.
227 # But there appears no advantage to any other scheme, and this
Tim Peterscbd0a322003-01-28 00:24:43 +0000228 # scheme allows the Unpickler memo to be implemented as a plain (but
Tim Peterse46b73f2003-01-27 21:22:10 +0000229 # growable) array, indexed by memo key.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000230 memo_len = len(self.memo)
231 self.write(self.put(memo_len))
Tim Peters518df0d2003-01-28 01:00:38 +0000232 self.memo[id(obj)] = memo_len, obj
Jeremy Hylton3422c992003-01-24 19:29:52 +0000233
Tim Petersbb38e302003-01-27 21:25:41 +0000234 # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000235 def put(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000236 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000237 if i < 256:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000238 return BINPUT + chr(i)
239 else:
240 return LONG_BINPUT + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000241
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000242 return PUT + `i` + '\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000243
Tim Petersbb38e302003-01-27 21:25:41 +0000244 # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000245 def get(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 BINGET + chr(i)
249 else:
250 return LONG_BINGET + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000251
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000252 return GET + `i` + '\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000253
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000254 def save(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000255 # Check for persistent id (defined by a subclass)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000256 pid = self.persistent_id(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000257 if pid:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000258 self.save_pers(pid)
259 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000260
Guido van Rossumbc64e222003-01-28 16:34:19 +0000261 # Check the memo
262 x = self.memo.get(id(obj))
263 if x:
264 self.write(self.get(x[0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000265 return
266
Guido van Rossumbc64e222003-01-28 16:34:19 +0000267 # Check the type dispatch table
Guido van Rossum3a41c612003-01-28 15:10:22 +0000268 t = type(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000269 f = self.dispatch.get(t)
270 if f:
271 f(self, obj) # Call unbound method with explicit self
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000272 return
273
Guido van Rossumbc64e222003-01-28 16:34:19 +0000274 # Check for a class with a custom metaclass; treat as regular class
Tim Petersb32a8312003-01-28 00:48:09 +0000275 try:
276 issc = issubclass(t, TypeType)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000277 except TypeError: # t is not a class (old Boost; see SF #502085)
Tim Petersb32a8312003-01-28 00:48:09 +0000278 issc = 0
279 if issc:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000280 self.save_global(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000281 return
282
Guido van Rossumbc64e222003-01-28 16:34:19 +0000283 # Check copy_reg.dispatch_table
284 reduce = dispatch_table.get(t)
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000285 if not reduce:
286 # Check for a __reduce__ method.
287 # Subtle: get the unbound method from the class, so that
288 # protocol 2 can override the default __reduce__ that all
289 # classes inherit from object. This has the added
290 # advantage that the call always has the form reduce(obj)
291 reduce = getattr(t, "__reduce__", None)
292 if self.proto >= 2:
293 # Protocol 2 can do better than the default __reduce__
294 if reduce is object.__reduce__:
295 reduce = None
296 if not reduce:
Guido van Rossum54fb1922003-01-28 18:22:35 +0000297 self.save_newobj(obj)
298 return
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000299 if not reduce:
Guido van Rossumbc64e222003-01-28 16:34:19 +0000300 raise PicklingError("Can't pickle %r object: %r" %
301 (t.__name__, obj))
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000302 rv = reduce(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000303
Guido van Rossumbc64e222003-01-28 16:34:19 +0000304 # Check for string returned by reduce(), meaning "save as global"
305 if type(rv) is StringType:
306 self.save_global(obj, rv)
Tim Petersb32a8312003-01-28 00:48:09 +0000307 return
308
Guido van Rossumbc64e222003-01-28 16:34:19 +0000309 # Assert that reduce() returned a tuple
310 if type(rv) is not TupleType:
311 raise PicklingError("%s must return string or tuple" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000312
Guido van Rossumbc64e222003-01-28 16:34:19 +0000313 # Assert that it returned a 2-tuple or 3-tuple, and unpack it
314 l = len(rv)
315 if l == 2:
316 func, args = rv
Tim Petersb32a8312003-01-28 00:48:09 +0000317 state = None
Guido van Rossumbc64e222003-01-28 16:34:19 +0000318 elif l == 3:
319 func, args, state = rv
320 else:
321 raise PicklingError("Tuple returned by %s must have "
322 "exactly two or three elements" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000323
Guido van Rossumbc64e222003-01-28 16:34:19 +0000324 # Save the reduce() output and finally memoize the object
325 self.save_reduce(func, args, state)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000326 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000327
Guido van Rossum3a41c612003-01-28 15:10:22 +0000328 def persistent_id(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000329 # This exists so a subclass can override it
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000330 return None
331
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000332 def save_pers(self, pid):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000333 # Save a persistent id reference
Tim Petersbd1cdb92003-01-28 01:03:10 +0000334 if self.bin:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000335 self.save(pid)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000336 self.write(BINPERSID)
Tim Petersbd1cdb92003-01-28 01:03:10 +0000337 else:
338 self.write(PERSID + str(pid) + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000339
Guido van Rossumbc64e222003-01-28 16:34:19 +0000340 def save_reduce(self, func, args, state=None):
341 # This API is be called by some subclasses
342
343 # Assert that args is a tuple or None
344 if not isinstance(args, TupleType):
345 if args is None:
346 # A hack for Jim Fulton's ExtensionClass, now deprecated.
347 # See load_reduce()
348 warnings.warn("__basicnew__ special case is deprecated",
349 DeprecationWarning)
350 else:
351 raise PicklingError(
352 "args from reduce() should be a tuple")
353
354 # Assert that func is callable
355 if not callable(func):
356 raise PicklingError("func from reduce should be callable")
357
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000358 save = self.save
Guido van Rossumbc64e222003-01-28 16:34:19 +0000359 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000360
Guido van Rossumbc64e222003-01-28 16:34:19 +0000361 save(func)
362 save(args)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000363 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000364
Tim Petersc32d8242001-04-10 02:48:53 +0000365 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000366 save(state)
367 write(BUILD)
368
Guido van Rossum54fb1922003-01-28 18:22:35 +0000369 def save_newobj(self, obj):
370 # Save a new-style class instance, using protocol 2.
371 # XXX Much of this is still experimental.
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000372 assert self.proto >= 2 # This only works for protocol 2
Guido van Rossum54fb1922003-01-28 18:22:35 +0000373 t = type(obj)
Guido van Rossum54fb1922003-01-28 18:22:35 +0000374 getnewargs = getattr(obj, "__getnewargs__", None)
375 if getnewargs:
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000376 args = getnewargs() # This bette not reference obj
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000377 else:
378 for cls in int, long, float, complex, str, unicode, tuple:
379 if isinstance(obj, cls):
380 args = (cls(obj),)
381 break
382 else:
383 args = ()
384
385 save = self.save
386 write = self.write
387
Guido van Rossum54fb1922003-01-28 18:22:35 +0000388 self.save_global(t)
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000389 save(args)
390 write(NEWOBJ)
Guido van Rossum54fb1922003-01-28 18:22:35 +0000391 self.memoize(obj)
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000392
393 if isinstance(obj, list):
394 write(MARK)
395 for x in obj:
396 save(x)
397 write(APPENDS)
398 elif isinstance(obj, dict):
399 write(MARK)
400 for k, v in obj.iteritems():
401 save(k)
402 save(v)
403 write(SETITEMS)
404
Guido van Rossum54fb1922003-01-28 18:22:35 +0000405 getstate = getattr(obj, "__getstate__", None)
406 if getstate:
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000407 try:
408 state = getstate()
409 except TypeError, err:
410 # XXX Catch generic exception caused by __slots__
411 if str(err) != ("a class that defines __slots__ "
412 "without defining __getstate__ "
413 "cannot be pickled"):
414 print repr(str(err))
415 raise # Not that specific exception
416 getstate = None
417 if not getstate:
Guido van Rossum54fb1922003-01-28 18:22:35 +0000418 state = getattr(obj, "__dict__", None)
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000419 # If there are slots, the state becomes a tuple of two
420 # items: the first item the regular __dict__ or None, and
421 # the second a dict mapping slot names to slot values
422 names = _slotnames(t)
423 if names:
424 slots = {}
425 nil = []
426 for name in names:
427 value = getattr(obj, name, nil)
428 if value is not nil:
429 slots[name] = value
430 if slots:
431 state = (state, slots)
432
Guido van Rossum54fb1922003-01-28 18:22:35 +0000433 if state is not None:
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000434 save(state)
435 write(BUILD)
Guido van Rossum54fb1922003-01-28 18:22:35 +0000436
Guido van Rossumbc64e222003-01-28 16:34:19 +0000437 # Methods below this point are dispatched through the dispatch table
438
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000439 dispatch = {}
440
Guido van Rossum3a41c612003-01-28 15:10:22 +0000441 def save_none(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000442 self.write(NONE)
443 dispatch[NoneType] = save_none
444
Guido van Rossum3a41c612003-01-28 15:10:22 +0000445 def save_bool(self, obj):
Guido van Rossum7d97d312003-01-28 04:25:27 +0000446 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000447 self.write(obj and NEWTRUE or NEWFALSE)
Guido van Rossum7d97d312003-01-28 04:25:27 +0000448 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000449 self.write(obj and TRUE or FALSE)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000450 dispatch[bool] = save_bool
451
Guido van Rossum3a41c612003-01-28 15:10:22 +0000452 def save_int(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000453 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000454 # If the int is small enough to fit in a signed 4-byte 2's-comp
455 # format, we can store it more efficiently than the general
456 # case.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000457 # First one- and two-byte unsigned ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000458 if obj >= 0:
459 if obj <= 0xff:
460 self.write(BININT1 + chr(obj))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000461 return
Guido van Rossum3a41c612003-01-28 15:10:22 +0000462 if obj <= 0xffff:
463 self.write(BININT2 + chr(obj&0xff) + chr(obj>>8))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000464 return
465 # Next check for 4-byte signed ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000466 high_bits = obj >> 31 # note that Python shift sign-extends
Tim Petersd95c2df2003-01-28 03:41:54 +0000467 if high_bits == 0 or high_bits == -1:
Tim Peters44714002001-04-10 05:02:52 +0000468 # All high bits are copies of bit 2**31, so the value
469 # fits in a 4-byte signed int.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000470 self.write(BININT + pack("<i", obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000471 return
Tim Peters44714002001-04-10 05:02:52 +0000472 # Text pickle, or int too big to fit in signed 4-byte format.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000473 self.write(INT + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000474 dispatch[IntType] = save_int
475
Guido van Rossum3a41c612003-01-28 15:10:22 +0000476 def save_long(self, obj, pack=struct.pack):
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000477 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000478 bytes = encode_long(obj)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000479 n = len(bytes)
480 if n < 256:
481 self.write(LONG1 + chr(n) + bytes)
482 else:
483 self.write(LONG4 + pack("<i", n) + bytes)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000484 self.write(LONG + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000485 dispatch[LongType] = save_long
486
Guido van Rossum3a41c612003-01-28 15:10:22 +0000487 def save_float(self, obj, pack=struct.pack):
Guido van Rossumd3703791998-10-22 20:15:36 +0000488 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000489 self.write(BINFLOAT + pack('>d', obj))
Guido van Rossumd3703791998-10-22 20:15:36 +0000490 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000491 self.write(FLOAT + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000492 dispatch[FloatType] = save_float
493
Guido van Rossum3a41c612003-01-28 15:10:22 +0000494 def save_string(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000495 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000496 n = len(obj)
Tim Petersbbf63cd2003-01-27 21:15:36 +0000497 if n < 256:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000498 self.write(SHORT_BINSTRING + chr(n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000499 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000500 self.write(BINSTRING + pack("<i", n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000501 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000502 self.write(STRING + `obj` + '\n')
503 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000504 dispatch[StringType] = save_string
505
Guido van Rossum3a41c612003-01-28 15:10:22 +0000506 def save_unicode(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000507 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000508 encoding = obj.encode('utf-8')
Tim Petersbbf63cd2003-01-27 21:15:36 +0000509 n = len(encoding)
Guido van Rossum5c938d02003-01-28 03:03:08 +0000510 self.write(BINUNICODE + pack("<i", n) + encoding)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000511 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000512 obj = obj.replace("\\", "\\u005c")
513 obj = obj.replace("\n", "\\u000a")
514 self.write(UNICODE + obj.encode('raw-unicode-escape') + '\n')
515 self.memoize(obj)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000516 dispatch[UnicodeType] = save_unicode
517
Guido van Rossum31584cb2001-01-22 14:53:29 +0000518 if StringType == UnicodeType:
519 # This is true for Jython
Guido van Rossum3a41c612003-01-28 15:10:22 +0000520 def save_string(self, obj, pack=struct.pack):
521 unicode = obj.isunicode()
Guido van Rossum31584cb2001-01-22 14:53:29 +0000522
Tim Petersc32d8242001-04-10 02:48:53 +0000523 if self.bin:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000524 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000525 obj = obj.encode("utf-8")
526 l = len(obj)
Tim Petersc32d8242001-04-10 02:48:53 +0000527 if l < 256 and not unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000528 self.write(SHORT_BINSTRING + chr(l) + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000529 else:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000530 s = pack("<i", l)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000531 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000532 self.write(BINUNICODE + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000533 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000534 self.write(BINSTRING + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000535 else:
Tim Peters658cba62001-02-09 20:06:00 +0000536 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000537 obj = obj.replace("\\", "\\u005c")
538 obj = obj.replace("\n", "\\u000a")
539 obj = obj.encode('raw-unicode-escape')
540 self.write(UNICODE + obj + '\n')
Guido van Rossum31584cb2001-01-22 14:53:29 +0000541 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000542 self.write(STRING + `obj` + '\n')
543 self.memoize(obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000544 dispatch[StringType] = save_string
Tim Peters658cba62001-02-09 20:06:00 +0000545
Guido van Rossum3a41c612003-01-28 15:10:22 +0000546 def save_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000547 write = self.write
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000548 proto = self.proto
549
Guido van Rossum3a41c612003-01-28 15:10:22 +0000550 n = len(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000551 if n == 0 and proto:
552 write(EMPTY_TUPLE)
553 return
554
555 save = self.save
556 memo = self.memo
557 if n <= 3 and proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000558 for element in obj:
Tim Petersd97da802003-01-28 05:48:29 +0000559 save(element)
560 # Subtle. Same as in the big comment below.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000561 if id(obj) in memo:
562 get = self.get(memo[id(obj)][0])
Tim Petersd97da802003-01-28 05:48:29 +0000563 write(POP * n + get)
564 else:
565 write(_tuplesize2code[n])
Guido van Rossum3a41c612003-01-28 15:10:22 +0000566 self.memoize(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000567 return
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000568
Tim Petersff57bff2003-01-28 05:34:53 +0000569 # proto 0, or proto 1 and tuple isn't empty, or proto > 1 and tuple
570 # has more than 3 elements.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000571 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000572 for element in obj:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000573 save(element)
574
Guido van Rossum3a41c612003-01-28 15:10:22 +0000575 if n and id(obj) in memo:
Tim Petersf558da02003-01-28 02:09:55 +0000576 # Subtle. d was not in memo when we entered save_tuple(), so
577 # the process of saving the tuple's elements must have saved
578 # the tuple itself: the tuple is recursive. The proper action
579 # now is to throw away everything we put on the stack, and
580 # simply GET the tuple (it's already constructed). This check
581 # could have been done in the "for element" loop instead, but
582 # recursive tuples are a rare thing.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000583 get = self.get(memo[id(obj)][0])
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000584 if proto:
Tim Petersf558da02003-01-28 02:09:55 +0000585 write(POP_MARK + get)
586 else: # proto 0 -- POP_MARK not available
Tim Petersd97da802003-01-28 05:48:29 +0000587 write(POP * (n+1) + get)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000588 return
589
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000590 # No recursion (including the empty-tuple case for protocol 0).
Tim Peters518df0d2003-01-28 01:00:38 +0000591 self.write(TUPLE)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000592 if obj: # No need to memoize empty tuple
593 self.memoize(obj)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000594
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000595 dispatch[TupleType] = save_tuple
596
Tim Petersa6ae9a22003-01-28 16:58:41 +0000597 # save_empty_tuple() isn't used by anything in Python 2.3. However, I
598 # found a Pickler subclass in Zope3 that calls it, so it's not harmless
599 # to remove it.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000600 def save_empty_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000601 self.write(EMPTY_TUPLE)
602
Guido van Rossum3a41c612003-01-28 15:10:22 +0000603 def save_list(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000604 write = self.write
605 save = self.save
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000606
Tim Petersc32d8242001-04-10 02:48:53 +0000607 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000608 write(EMPTY_LIST)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000609 self.memoize(obj)
610 n = len(obj)
Tim Peters21c18f02003-01-28 01:15:46 +0000611 if n > 1:
612 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000613 for element in obj:
Tim Peters21c18f02003-01-28 01:15:46 +0000614 save(element)
615 write(APPENDS)
616 elif n:
617 assert n == 1
Guido van Rossum3a41c612003-01-28 15:10:22 +0000618 save(obj[0])
Tim Peters21c18f02003-01-28 01:15:46 +0000619 write(APPEND)
620 # else the list is empty, and we're already done
621
622 else: # proto 0 -- can't use EMPTY_LIST or APPENDS
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000623 write(MARK + LIST)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000624 self.memoize(obj)
625 for element in obj:
Tim Peters21c18f02003-01-28 01:15:46 +0000626 save(element)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000627 write(APPEND)
628
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000629 dispatch[ListType] = save_list
630
Guido van Rossum3a41c612003-01-28 15:10:22 +0000631 def save_dict(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000632 write = self.write
633 save = self.save
Guido van Rossum3a41c612003-01-28 15:10:22 +0000634 items = obj.iteritems()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000635
Tim Petersc32d8242001-04-10 02:48:53 +0000636 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000637 write(EMPTY_DICT)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000638 self.memoize(obj)
639 if len(obj) > 1:
Tim Peters064567e2003-01-28 01:34:43 +0000640 write(MARK)
641 for key, value in items:
642 save(key)
643 save(value)
644 write(SETITEMS)
645 return
Tim Peters82ca59e2003-01-28 16:47:59 +0000646 # else (dict is empty or a singleton), fall through to the
647 # SETITEM code at the end
Tim Peters064567e2003-01-28 01:34:43 +0000648 else: # proto 0 -- can't use EMPTY_DICT or SETITEMS
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000649 write(MARK + DICT)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000650 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000651
Guido van Rossum3a41c612003-01-28 15:10:22 +0000652 # proto 0 or len(obj) < 2
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000653 for key, value in items:
654 save(key)
655 save(value)
Tim Peters064567e2003-01-28 01:34:43 +0000656 write(SETITEM)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000657
658 dispatch[DictionaryType] = save_dict
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000659 if not PyStringMap is None:
660 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000661
Guido van Rossum3a41c612003-01-28 15:10:22 +0000662 def save_inst(self, obj):
663 cls = obj.__class__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000664
665 memo = self.memo
666 write = self.write
667 save = self.save
668
Guido van Rossum3a41c612003-01-28 15:10:22 +0000669 if hasattr(obj, '__getinitargs__'):
670 args = obj.__getinitargs__()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000671 len(args) # XXX Assert it's a sequence
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000672 _keep_alive(args, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000673 else:
674 args = ()
675
676 write(MARK)
677
Tim Petersc32d8242001-04-10 02:48:53 +0000678 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000679 save(cls)
Tim Peters3b769832003-01-28 03:51:36 +0000680 for arg in args:
681 save(arg)
682 write(OBJ)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000683 else:
Tim Peters3b769832003-01-28 03:51:36 +0000684 for arg in args:
685 save(arg)
686 write(INST + cls.__module__ + '\n' + cls.__name__ + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000687
Guido van Rossum3a41c612003-01-28 15:10:22 +0000688 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000689
690 try:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000691 getstate = obj.__getstate__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000692 except AttributeError:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000693 stuff = obj.__dict__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000694 else:
695 stuff = getstate()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000696 _keep_alive(stuff, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000697 save(stuff)
698 write(BUILD)
Tim Peters3b769832003-01-28 03:51:36 +0000699
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000700 dispatch[InstanceType] = save_inst
701
Guido van Rossum3a41c612003-01-28 15:10:22 +0000702 def save_global(self, obj, name = None):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000703 write = self.write
704 memo = self.memo
705
Tim Petersc32d8242001-04-10 02:48:53 +0000706 if name is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000707 name = obj.__name__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000708
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000709 try:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000710 module = obj.__module__
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000711 except AttributeError:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000712 module = whichmodule(obj, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000713
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000714 try:
715 __import__(module)
716 mod = sys.modules[module]
717 klass = getattr(mod, name)
718 except (ImportError, KeyError, AttributeError):
719 raise PicklingError(
720 "Can't pickle %r: it's not found as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000721 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000722 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000723 if klass is not obj:
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000724 raise PicklingError(
725 "Can't pickle %r: it's not the same object as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000726 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000727
Tim Peters518df0d2003-01-28 01:00:38 +0000728 write(GLOBAL + module + '\n' + name + '\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000729 self.memoize(obj)
Tim Peters3b769832003-01-28 03:51:36 +0000730
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000731 dispatch[ClassType] = save_global
732 dispatch[FunctionType] = save_global
733 dispatch[BuiltinFunctionType] = save_global
Tim Peters6d6c1a32001-08-02 04:15:00 +0000734 dispatch[TypeType] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000735
Guido van Rossum1be31752003-01-28 15:19:53 +0000736# Pickling helpers
Guido van Rossuma48061a1995-01-10 00:31:14 +0000737
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000738def _slotnames(cls):
739 """Return a list of slot names for a given class.
740
741 This needs to find slots defined by the class and its bases, so we
742 can't simply return the __slots__ attribute. We must walk down
743 the Method Resolution Order and concatenate the __slots__ of each
744 class found there. (This assumes classes don't modify their
745 __slots__ attribute to misrepresent their slots after the class is
746 defined.)
747 """
748 if not hasattr(cls, "__slots__"):
749 return []
750 names = []
751 for c in cls.__mro__:
752 if "__slots__" in c.__dict__:
753 names += list(c.__dict__["__slots__"])
754 return names
755
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000756def _keep_alive(x, memo):
757 """Keeps a reference to the object x in the memo.
758
759 Because we remember objects by their id, we have
760 to assure that possibly temporary objects are kept
761 alive by referencing them.
762 We store a reference at the id of the memo, which should
763 normally not be used unless someone tries to deepcopy
764 the memo itself...
765 """
766 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000767 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000768 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000769 # aha, this is the first one :-)
770 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000771
772
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000773classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000774
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000775def whichmodule(func, funcname):
776 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000777
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000778 Search sys.modules for the module.
779 Cache in classmap.
780 Return a module name.
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000781 If the function cannot be found, return __main__.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000782 """
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000783 if func in classmap:
784 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000785
786 for name, module in sys.modules.items():
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000787 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000788 continue # skip dummy package entries
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000789 if name != '__main__' and \
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000790 hasattr(module, funcname) and \
791 getattr(module, funcname) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000792 break
793 else:
794 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000795 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000796 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000797
798
Guido van Rossum1be31752003-01-28 15:19:53 +0000799# Unpickling machinery
800
Guido van Rossuma48061a1995-01-10 00:31:14 +0000801class Unpickler:
802
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000803 def __init__(self, file):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000804 """This takes a file-like object for reading a pickle data stream.
805
806 This class automatically determines whether the data stream was
807 written in binary mode or not, so it does not need a flag as in
808 the Pickler class factory.
809
810 The file-like object must have two methods, a read() method that
811 takes an integer argument, and a readline() method that requires no
812 arguments. Both methods should return a string. Thus file-like
813 object can be a file object opened for reading, a StringIO object,
814 or any other custom object that meets this interface.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000815 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000816 self.readline = file.readline
817 self.read = file.read
818 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000819
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000820 def load(self):
Guido van Rossum3a41c612003-01-28 15:10:22 +0000821 """Read a pickled object representation from the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000822
Guido van Rossum3a41c612003-01-28 15:10:22 +0000823 Return the reconstituted object hierarchy specified in the file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000824 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000825 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000826 self.stack = []
827 self.append = self.stack.append
828 read = self.read
829 dispatch = self.dispatch
830 try:
831 while 1:
832 key = read(1)
833 dispatch[key](self)
Guido van Rossumff871742000-12-13 18:11:56 +0000834 except _Stop, stopinst:
835 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000836
Tim Petersc23d18a2003-01-28 01:41:51 +0000837 # Return largest index k such that self.stack[k] is self.mark.
838 # If the stack doesn't contain a mark, eventually raises IndexError.
839 # This could be sped by maintaining another stack, of indices at which
840 # the mark appears. For that matter, the latter stack would suffice,
841 # and we wouldn't need to push mark objects on self.stack at all.
842 # Doing so is probably a good thing, though, since if the pickle is
843 # corrupt (or hostile) we may get a clue from finding self.mark embedded
844 # in unpickled objects.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000845 def marker(self):
846 stack = self.stack
847 mark = self.mark
848 k = len(stack)-1
849 while stack[k] is not mark: k = k-1
850 return k
851
852 dispatch = {}
853
854 def load_eof(self):
855 raise EOFError
856 dispatch[''] = load_eof
857
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000858 def load_proto(self):
859 proto = ord(self.read(1))
860 if not 0 <= proto <= 2:
861 raise ValueError, "unsupported pickle protocol: %d" % proto
862 dispatch[PROTO] = load_proto
863
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000864 def load_persid(self):
865 pid = self.readline()[:-1]
866 self.append(self.persistent_load(pid))
867 dispatch[PERSID] = load_persid
868
869 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000870 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000871 self.append(self.persistent_load(pid))
872 dispatch[BINPERSID] = load_binpersid
873
874 def load_none(self):
875 self.append(None)
876 dispatch[NONE] = load_none
877
Guido van Rossum7d97d312003-01-28 04:25:27 +0000878 def load_false(self):
879 self.append(False)
880 dispatch[NEWFALSE] = load_false
881
882 def load_true(self):
883 self.append(True)
884 dispatch[NEWTRUE] = load_true
885
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000886 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000887 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000888 if data == FALSE[1:]:
889 val = False
890 elif data == TRUE[1:]:
891 val = True
892 else:
893 try:
894 val = int(data)
895 except ValueError:
896 val = long(data)
897 self.append(val)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000898 dispatch[INT] = load_int
899
900 def load_binint(self):
901 self.append(mloads('i' + self.read(4)))
902 dispatch[BININT] = load_binint
903
904 def load_binint1(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000905 self.append(ord(self.read(1)))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000906 dispatch[BININT1] = load_binint1
907
908 def load_binint2(self):
909 self.append(mloads('i' + self.read(2) + '\000\000'))
910 dispatch[BININT2] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000911
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000912 def load_long(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000913 self.append(long(self.readline()[:-1], 0))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000914 dispatch[LONG] = load_long
915
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000916 def load_long1(self):
917 n = ord(self.read(1))
918 bytes = self.read(n)
919 return decode_long(bytes)
920 dispatch[LONG1] = load_long1
921
922 def load_long4(self):
923 n = mloads('i' + self.read(4))
924 bytes = self.read(n)
925 return decode_long(bytes)
926 dispatch[LONG4] = load_long4
927
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000928 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000929 self.append(float(self.readline()[:-1]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000930 dispatch[FLOAT] = load_float
931
Guido van Rossumd3703791998-10-22 20:15:36 +0000932 def load_binfloat(self, unpack=struct.unpack):
933 self.append(unpack('>d', self.read(8))[0])
934 dispatch[BINFLOAT] = load_binfloat
935
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000936 def load_string(self):
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000937 rep = self.readline()[:-1]
Tim Petersad5a7712003-01-28 16:23:33 +0000938 for q in "\"'": # double or single quote
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000939 if rep.startswith(q):
940 if not rep.endswith(q):
941 raise ValueError, "insecure string pickle"
942 rep = rep[len(q):-len(q)]
943 break
944 else:
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000945 raise ValueError, "insecure string pickle"
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000946 self.append(rep.decode("string-escape"))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000947 dispatch[STRING] = load_string
948
949 def load_binstring(self):
950 len = mloads('i' + self.read(4))
951 self.append(self.read(len))
952 dispatch[BINSTRING] = load_binstring
953
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000954 def load_unicode(self):
955 self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
956 dispatch[UNICODE] = load_unicode
957
958 def load_binunicode(self):
959 len = mloads('i' + self.read(4))
960 self.append(unicode(self.read(len),'utf-8'))
961 dispatch[BINUNICODE] = load_binunicode
962
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000963 def load_short_binstring(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000964 len = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000965 self.append(self.read(len))
966 dispatch[SHORT_BINSTRING] = load_short_binstring
967
968 def load_tuple(self):
969 k = self.marker()
970 self.stack[k:] = [tuple(self.stack[k+1:])]
971 dispatch[TUPLE] = load_tuple
972
973 def load_empty_tuple(self):
974 self.stack.append(())
975 dispatch[EMPTY_TUPLE] = load_empty_tuple
976
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000977 def load_tuple1(self):
978 self.stack[-1] = (self.stack[-1],)
979 dispatch[TUPLE1] = load_tuple1
980
981 def load_tuple2(self):
982 self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
983 dispatch[TUPLE2] = load_tuple2
984
985 def load_tuple3(self):
986 self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
987 dispatch[TUPLE3] = load_tuple3
988
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000989 def load_empty_list(self):
990 self.stack.append([])
991 dispatch[EMPTY_LIST] = load_empty_list
992
993 def load_empty_dictionary(self):
994 self.stack.append({})
995 dispatch[EMPTY_DICT] = load_empty_dictionary
996
997 def load_list(self):
998 k = self.marker()
999 self.stack[k:] = [self.stack[k+1:]]
1000 dispatch[LIST] = load_list
1001
1002 def load_dict(self):
1003 k = self.marker()
1004 d = {}
1005 items = self.stack[k+1:]
1006 for i in range(0, len(items), 2):
1007 key = items[i]
1008 value = items[i+1]
1009 d[key] = value
1010 self.stack[k:] = [d]
1011 dispatch[DICT] = load_dict
1012
1013 def load_inst(self):
1014 k = self.marker()
1015 args = tuple(self.stack[k+1:])
1016 del self.stack[k:]
1017 module = self.readline()[:-1]
1018 name = self.readline()[:-1]
1019 klass = self.find_class(module, name)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001020 instantiated = 0
1021 if (not args and type(klass) is ClassType and
1022 not hasattr(klass, "__getinitargs__")):
1023 try:
1024 value = _EmptyClass()
1025 value.__class__ = klass
Guido van Rossumb19e2a31998-04-13 18:08:45 +00001026 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001027 except RuntimeError:
1028 # In restricted execution, assignment to inst.__class__ is
1029 # prohibited
1030 pass
1031 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +00001032 try:
Barry Warsawbf4d9592001-11-15 23:42:58 +00001033 if not hasattr(klass, '__safe_for_unpickling__'):
1034 raise UnpicklingError('%s is not safe for unpickling' %
1035 klass)
Guido van Rossum743d17e1998-09-15 20:25:57 +00001036 value = apply(klass, args)
1037 except TypeError, err:
1038 raise TypeError, "in constructor for %s: %s" % (
1039 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001040 self.append(value)
1041 dispatch[INST] = load_inst
1042
1043 def load_obj(self):
1044 stack = self.stack
1045 k = self.marker()
1046 klass = stack[k + 1]
1047 del stack[k + 1]
Tim Peters2344fae2001-01-15 00:50:52 +00001048 args = tuple(stack[k + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001049 del stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001050 instantiated = 0
1051 if (not args and type(klass) is ClassType and
1052 not hasattr(klass, "__getinitargs__")):
1053 try:
1054 value = _EmptyClass()
1055 value.__class__ = klass
1056 instantiated = 1
1057 except RuntimeError:
1058 # In restricted execution, assignment to inst.__class__ is
1059 # prohibited
1060 pass
1061 if not instantiated:
1062 value = apply(klass, args)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001063 self.append(value)
Tim Peters2344fae2001-01-15 00:50:52 +00001064 dispatch[OBJ] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001065
Guido van Rossum3a41c612003-01-28 15:10:22 +00001066 def load_newobj(self):
1067 args = self.stack.pop()
1068 cls = self.stack[-1]
1069 obj = cls.__new__(cls, *args)
Guido van Rossum533dbcf2003-01-28 17:55:05 +00001070 self.stack[-1] = obj
Guido van Rossum3a41c612003-01-28 15:10:22 +00001071 dispatch[NEWOBJ] = load_newobj
1072
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001073 def load_global(self):
1074 module = self.readline()[:-1]
1075 name = self.readline()[:-1]
1076 klass = self.find_class(module, name)
1077 self.append(klass)
1078 dispatch[GLOBAL] = load_global
1079
1080 def find_class(self, module, name):
Barry Warsawbf4d9592001-11-15 23:42:58 +00001081 __import__(module)
1082 mod = sys.modules[module]
1083 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001084 return klass
1085
1086 def load_reduce(self):
1087 stack = self.stack
1088
1089 callable = stack[-2]
1090 arg_tup = stack[-1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001091 del stack[-2:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001092
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001093 if type(callable) is not ClassType:
Raymond Hettinger54f02222002-06-01 14:18:47 +00001094 if not callable in safe_constructors:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001095 try:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001096 safe = callable.__safe_for_unpickling__
1097 except AttributeError:
1098 safe = None
Guido van Rossuma48061a1995-01-10 00:31:14 +00001099
Tim Petersc32d8242001-04-10 02:48:53 +00001100 if not safe:
Tim Peters2344fae2001-01-15 00:50:52 +00001101 raise UnpicklingError, "%s is not safe for " \
1102 "unpickling" % callable
Guido van Rossuma48061a1995-01-10 00:31:14 +00001103
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001104 if arg_tup is None:
Guido van Rossumbc64e222003-01-28 16:34:19 +00001105 # A hack for Jim Fulton's ExtensionClass, now deprecated
1106 warnings.warn("__basicnew__ special case is deprecated",
Tim Peters8ac14952002-05-23 15:15:30 +00001107 DeprecationWarning)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001108 value = callable.__basicnew__()
1109 else:
1110 value = apply(callable, arg_tup)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001111 self.append(value)
1112 dispatch[REDUCE] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +00001113
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001114 def load_pop(self):
1115 del self.stack[-1]
1116 dispatch[POP] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +00001117
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001118 def load_pop_mark(self):
1119 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001120 del self.stack[k:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001121 dispatch[POP_MARK] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001122
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001123 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +00001124 self.append(self.stack[-1])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001125 dispatch[DUP] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +00001126
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001127 def load_get(self):
1128 self.append(self.memo[self.readline()[:-1]])
1129 dispatch[GET] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +00001130
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001131 def load_binget(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001132 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001133 self.append(self.memo[`i`])
1134 dispatch[BINGET] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001135
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001136 def load_long_binget(self):
1137 i = mloads('i' + self.read(4))
1138 self.append(self.memo[`i`])
1139 dispatch[LONG_BINGET] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001140
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001141 def load_put(self):
1142 self.memo[self.readline()[:-1]] = self.stack[-1]
1143 dispatch[PUT] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +00001144
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001145 def load_binput(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001146 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001147 self.memo[`i`] = self.stack[-1]
1148 dispatch[BINPUT] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001149
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001150 def load_long_binput(self):
1151 i = mloads('i' + self.read(4))
1152 self.memo[`i`] = self.stack[-1]
1153 dispatch[LONG_BINPUT] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001154
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001155 def load_append(self):
1156 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001157 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001158 list = stack[-1]
1159 list.append(value)
1160 dispatch[APPEND] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +00001161
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001162 def load_appends(self):
1163 stack = self.stack
1164 mark = self.marker()
1165 list = stack[mark - 1]
Tim Peters209ad952003-01-28 01:44:45 +00001166 list.extend(stack[mark + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001167 del stack[mark:]
1168 dispatch[APPENDS] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +00001169
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001170 def load_setitem(self):
1171 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001172 value = stack.pop()
1173 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001174 dict = stack[-1]
1175 dict[key] = value
1176 dispatch[SETITEM] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001177
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001178 def load_setitems(self):
1179 stack = self.stack
1180 mark = self.marker()
1181 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001182 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001183 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001184
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001185 del stack[mark:]
1186 dispatch[SETITEMS] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001187
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001188 def load_build(self):
1189 stack = self.stack
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001190 state = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001191 inst = stack[-1]
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001192 setstate = getattr(inst, "__setstate__", None)
1193 if setstate:
1194 setstate(state)
1195 return
1196 slotstate = None
1197 if isinstance(state, tuple) and len(state) == 2:
1198 state, slotstate = state
1199 if state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001200 try:
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001201 inst.__dict__.update(state)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001202 except RuntimeError:
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001203 # XXX In restricted execution, the instance's __dict__
1204 # is not accessible. Use the old way of unpickling
1205 # the instance variables. This is a semantic
1206 # difference when unpickling in restricted
1207 # vs. unrestricted modes.
1208 for k, v in state.items():
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001209 setattr(inst, k, v)
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001210 if slotstate:
1211 for k, v in slotstate.items():
1212 setattr(inst, k, v)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001213 dispatch[BUILD] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001214
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001215 def load_mark(self):
1216 self.append(self.mark)
1217 dispatch[MARK] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001218
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001219 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001220 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001221 raise _Stop(value)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001222 dispatch[STOP] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001223
Guido van Rossume467be61997-12-05 19:42:42 +00001224# Helper class for load_inst/load_obj
1225
1226class _EmptyClass:
1227 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001228
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001229# Encode/decode longs.
1230
1231def encode_long(x):
1232 r"""Encode a long to a two's complement little-ending binary string.
1233 >>> encode_long(255L)
1234 '\xff\x00'
1235 >>> encode_long(32767L)
1236 '\xff\x7f'
1237 >>> encode_long(-256L)
1238 '\x00\xff'
1239 >>> encode_long(-32768L)
1240 '\x00\x80'
1241 >>> encode_long(-128L)
1242 '\x80'
1243 >>> encode_long(127L)
1244 '\x7f'
1245 >>>
1246 """
Guido van Rossum3d8c01b2003-01-28 19:48:18 +00001247 # XXX This is still a quadratic algorithm.
1248 # Should use hex() to get started.
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001249 digits = []
1250 while not -128 <= x < 128:
1251 digits.append(x & 0xff)
1252 x >>= 8
1253 digits.append(x & 0xff)
1254 return "".join(map(chr, digits))
1255
1256def decode_long(data):
1257 r"""Decode a long from a two's complement little-endian binary string.
1258 >>> decode_long("\xff\x00")
1259 255L
1260 >>> decode_long("\xff\x7f")
1261 32767L
1262 >>> decode_long("\x00\xff")
1263 -256L
1264 >>> decode_long("\x00\x80")
1265 -32768L
1266 >>> decode_long("\x80")
1267 -128L
1268 >>> decode_long("\x7f")
1269 127L
1270 """
Guido van Rossum3d8c01b2003-01-28 19:48:18 +00001271 # XXX This is quadratic too.
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001272 x = 0L
1273 i = 0L
1274 for c in data:
1275 x |= long(ord(c)) << i
1276 i += 8L
1277 if data and ord(c) >= 0x80:
1278 x -= 1L << i
1279 return x
1280
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001281# Shorthands
1282
Jeremy Hyltonabe2c622001-10-15 21:29:28 +00001283try:
1284 from cStringIO import StringIO
1285except ImportError:
1286 from StringIO import StringIO
Guido van Rossumc7c5e691996-07-22 22:26:07 +00001287
Guido van Rossum3a41c612003-01-28 15:10:22 +00001288def dump(obj, file, proto=1):
1289 Pickler(file, proto).dump(obj)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001290
Guido van Rossum3a41c612003-01-28 15:10:22 +00001291def dumps(obj, proto=1):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001292 file = StringIO()
Guido van Rossum3a41c612003-01-28 15:10:22 +00001293 Pickler(file, proto).dump(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001294 return file.getvalue()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001295
1296def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001297 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001298
1299def loads(str):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001300 file = StringIO(str)
1301 return Unpickler(file).load()
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001302
1303# Doctest
1304
1305def _test():
1306 import doctest
1307 return doctest.testmod()
1308
1309if __name__ == "__main__":
1310 _test()