blob: b9bafce964ba8024ccdd7c1f2c0fe6435d0418fd [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 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.
Guido van Rossum4e2491d2003-01-28 22:31:25 +0000371 # XXX 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:
Guido van Rossum4e2491d2003-01-28 22:31:25 +0000378 # XXX These types should each grow a __getnewargs__
379 # implementation so this special-casing is unnecessary.
Guido van Rossumb26a97a2003-01-28 22:29:13 +0000380 for cls in int, long, float, complex, str, UnicodeType, tuple:
381 if cls and isinstance(obj, cls):
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000382 args = (cls(obj),)
383 break
384 else:
385 args = ()
386
387 save = self.save
388 write = self.write
389
Guido van Rossum54fb1922003-01-28 18:22:35 +0000390 self.save_global(t)
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000391 save(args)
392 write(NEWOBJ)
Guido van Rossum54fb1922003-01-28 18:22:35 +0000393 self.memoize(obj)
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000394
395 if isinstance(obj, list):
396 write(MARK)
397 for x in obj:
398 save(x)
399 write(APPENDS)
400 elif isinstance(obj, dict):
401 write(MARK)
402 for k, v in obj.iteritems():
403 save(k)
404 save(v)
405 write(SETITEMS)
406
Guido van Rossum54fb1922003-01-28 18:22:35 +0000407 getstate = getattr(obj, "__getstate__", None)
408 if getstate:
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000409 try:
410 state = getstate()
411 except TypeError, err:
412 # XXX Catch generic exception caused by __slots__
413 if str(err) != ("a class that defines __slots__ "
414 "without defining __getstate__ "
415 "cannot be pickled"):
416 print repr(str(err))
417 raise # Not that specific exception
418 getstate = None
419 if not getstate:
Guido van Rossum54fb1922003-01-28 18:22:35 +0000420 state = getattr(obj, "__dict__", None)
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000421 # If there are slots, the state becomes a tuple of two
422 # items: the first item the regular __dict__ or None, and
423 # the second a dict mapping slot names to slot values
424 names = _slotnames(t)
425 if names:
426 slots = {}
427 nil = []
428 for name in names:
429 value = getattr(obj, name, nil)
430 if value is not nil:
431 slots[name] = value
432 if slots:
433 state = (state, slots)
434
Guido van Rossum54fb1922003-01-28 18:22:35 +0000435 if state is not None:
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000436 save(state)
437 write(BUILD)
Guido van Rossum54fb1922003-01-28 18:22:35 +0000438
Guido van Rossumbc64e222003-01-28 16:34:19 +0000439 # Methods below this point are dispatched through the dispatch table
440
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000441 dispatch = {}
442
Guido van Rossum3a41c612003-01-28 15:10:22 +0000443 def save_none(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000444 self.write(NONE)
445 dispatch[NoneType] = save_none
446
Guido van Rossum3a41c612003-01-28 15:10:22 +0000447 def save_bool(self, obj):
Guido van Rossum7d97d312003-01-28 04:25:27 +0000448 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000449 self.write(obj and NEWTRUE or NEWFALSE)
Guido van Rossum7d97d312003-01-28 04:25:27 +0000450 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000451 self.write(obj and TRUE or FALSE)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000452 dispatch[bool] = save_bool
453
Guido van Rossum3a41c612003-01-28 15:10:22 +0000454 def save_int(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000455 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000456 # If the int is small enough to fit in a signed 4-byte 2's-comp
457 # format, we can store it more efficiently than the general
458 # case.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000459 # First one- and two-byte unsigned ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000460 if obj >= 0:
461 if obj <= 0xff:
462 self.write(BININT1 + chr(obj))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000463 return
Guido van Rossum3a41c612003-01-28 15:10:22 +0000464 if obj <= 0xffff:
465 self.write(BININT2 + chr(obj&0xff) + chr(obj>>8))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000466 return
467 # Next check for 4-byte signed ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000468 high_bits = obj >> 31 # note that Python shift sign-extends
Tim Petersd95c2df2003-01-28 03:41:54 +0000469 if high_bits == 0 or high_bits == -1:
Tim Peters44714002001-04-10 05:02:52 +0000470 # All high bits are copies of bit 2**31, so the value
471 # fits in a 4-byte signed int.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000472 self.write(BININT + pack("<i", obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000473 return
Tim Peters44714002001-04-10 05:02:52 +0000474 # Text pickle, or int too big to fit in signed 4-byte format.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000475 self.write(INT + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000476 dispatch[IntType] = save_int
477
Guido van Rossum3a41c612003-01-28 15:10:22 +0000478 def save_long(self, obj, pack=struct.pack):
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000479 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000480 bytes = encode_long(obj)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000481 n = len(bytes)
482 if n < 256:
483 self.write(LONG1 + chr(n) + bytes)
484 else:
485 self.write(LONG4 + pack("<i", n) + bytes)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000486 self.write(LONG + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000487 dispatch[LongType] = save_long
488
Guido van Rossum3a41c612003-01-28 15:10:22 +0000489 def save_float(self, obj, pack=struct.pack):
Guido van Rossumd3703791998-10-22 20:15:36 +0000490 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000491 self.write(BINFLOAT + pack('>d', obj))
Guido van Rossumd3703791998-10-22 20:15:36 +0000492 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000493 self.write(FLOAT + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000494 dispatch[FloatType] = save_float
495
Guido van Rossum3a41c612003-01-28 15:10:22 +0000496 def save_string(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000497 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000498 n = len(obj)
Tim Petersbbf63cd2003-01-27 21:15:36 +0000499 if n < 256:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000500 self.write(SHORT_BINSTRING + chr(n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000501 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000502 self.write(BINSTRING + pack("<i", n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000503 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000504 self.write(STRING + `obj` + '\n')
505 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000506 dispatch[StringType] = save_string
507
Guido van Rossum3a41c612003-01-28 15:10:22 +0000508 def save_unicode(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000509 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000510 encoding = obj.encode('utf-8')
Tim Petersbbf63cd2003-01-27 21:15:36 +0000511 n = len(encoding)
Guido van Rossum5c938d02003-01-28 03:03:08 +0000512 self.write(BINUNICODE + pack("<i", n) + encoding)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000513 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000514 obj = obj.replace("\\", "\\u005c")
515 obj = obj.replace("\n", "\\u000a")
516 self.write(UNICODE + obj.encode('raw-unicode-escape') + '\n')
517 self.memoize(obj)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000518 dispatch[UnicodeType] = save_unicode
519
Guido van Rossum31584cb2001-01-22 14:53:29 +0000520 if StringType == UnicodeType:
521 # This is true for Jython
Guido van Rossum3a41c612003-01-28 15:10:22 +0000522 def save_string(self, obj, pack=struct.pack):
523 unicode = obj.isunicode()
Guido van Rossum31584cb2001-01-22 14:53:29 +0000524
Tim Petersc32d8242001-04-10 02:48:53 +0000525 if self.bin:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000526 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000527 obj = obj.encode("utf-8")
528 l = len(obj)
Tim Petersc32d8242001-04-10 02:48:53 +0000529 if l < 256 and not unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000530 self.write(SHORT_BINSTRING + chr(l) + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000531 else:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000532 s = pack("<i", l)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000533 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000534 self.write(BINUNICODE + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000535 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000536 self.write(BINSTRING + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000537 else:
Tim Peters658cba62001-02-09 20:06:00 +0000538 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000539 obj = obj.replace("\\", "\\u005c")
540 obj = obj.replace("\n", "\\u000a")
541 obj = obj.encode('raw-unicode-escape')
542 self.write(UNICODE + obj + '\n')
Guido van Rossum31584cb2001-01-22 14:53:29 +0000543 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000544 self.write(STRING + `obj` + '\n')
545 self.memoize(obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000546 dispatch[StringType] = save_string
Tim Peters658cba62001-02-09 20:06:00 +0000547
Guido van Rossum3a41c612003-01-28 15:10:22 +0000548 def save_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000549 write = self.write
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000550 proto = self.proto
551
Guido van Rossum3a41c612003-01-28 15:10:22 +0000552 n = len(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000553 if n == 0 and proto:
554 write(EMPTY_TUPLE)
555 return
556
557 save = self.save
558 memo = self.memo
559 if n <= 3 and proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000560 for element in obj:
Tim Petersd97da802003-01-28 05:48:29 +0000561 save(element)
562 # Subtle. Same as in the big comment below.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000563 if id(obj) in memo:
564 get = self.get(memo[id(obj)][0])
Tim Petersd97da802003-01-28 05:48:29 +0000565 write(POP * n + get)
566 else:
567 write(_tuplesize2code[n])
Guido van Rossum3a41c612003-01-28 15:10:22 +0000568 self.memoize(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000569 return
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000570
Tim Petersff57bff2003-01-28 05:34:53 +0000571 # proto 0, or proto 1 and tuple isn't empty, or proto > 1 and tuple
572 # has more than 3 elements.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000573 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000574 for element in obj:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000575 save(element)
576
Guido van Rossum3a41c612003-01-28 15:10:22 +0000577 if n and id(obj) in memo:
Tim Petersf558da02003-01-28 02:09:55 +0000578 # Subtle. d was not in memo when we entered save_tuple(), so
579 # the process of saving the tuple's elements must have saved
580 # the tuple itself: the tuple is recursive. The proper action
581 # now is to throw away everything we put on the stack, and
582 # simply GET the tuple (it's already constructed). This check
583 # could have been done in the "for element" loop instead, but
584 # recursive tuples are a rare thing.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000585 get = self.get(memo[id(obj)][0])
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000586 if proto:
Tim Petersf558da02003-01-28 02:09:55 +0000587 write(POP_MARK + get)
588 else: # proto 0 -- POP_MARK not available
Tim Petersd97da802003-01-28 05:48:29 +0000589 write(POP * (n+1) + get)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000590 return
591
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000592 # No recursion (including the empty-tuple case for protocol 0).
Tim Peters518df0d2003-01-28 01:00:38 +0000593 self.write(TUPLE)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000594 if obj: # No need to memoize empty tuple
595 self.memoize(obj)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000596
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000597 dispatch[TupleType] = save_tuple
598
Tim Petersa6ae9a22003-01-28 16:58:41 +0000599 # save_empty_tuple() isn't used by anything in Python 2.3. However, I
600 # found a Pickler subclass in Zope3 that calls it, so it's not harmless
601 # to remove it.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000602 def save_empty_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000603 self.write(EMPTY_TUPLE)
604
Guido van Rossum3a41c612003-01-28 15:10:22 +0000605 def save_list(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000606 write = self.write
607 save = self.save
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000608
Tim Petersc32d8242001-04-10 02:48:53 +0000609 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000610 write(EMPTY_LIST)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000611 self.memoize(obj)
612 n = len(obj)
Tim Peters21c18f02003-01-28 01:15:46 +0000613 if n > 1:
614 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000615 for element in obj:
Tim Peters21c18f02003-01-28 01:15:46 +0000616 save(element)
617 write(APPENDS)
618 elif n:
619 assert n == 1
Guido van Rossum3a41c612003-01-28 15:10:22 +0000620 save(obj[0])
Tim Peters21c18f02003-01-28 01:15:46 +0000621 write(APPEND)
622 # else the list is empty, and we're already done
623
624 else: # proto 0 -- can't use EMPTY_LIST or APPENDS
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000625 write(MARK + LIST)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000626 self.memoize(obj)
627 for element in obj:
Tim Peters21c18f02003-01-28 01:15:46 +0000628 save(element)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000629 write(APPEND)
630
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000631 dispatch[ListType] = save_list
632
Guido van Rossum3a41c612003-01-28 15:10:22 +0000633 def save_dict(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000634 write = self.write
635 save = self.save
Guido van Rossum3a41c612003-01-28 15:10:22 +0000636 items = obj.iteritems()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000637
Tim Petersc32d8242001-04-10 02:48:53 +0000638 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000639 write(EMPTY_DICT)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000640 self.memoize(obj)
641 if len(obj) > 1:
Tim Peters064567e2003-01-28 01:34:43 +0000642 write(MARK)
643 for key, value in items:
644 save(key)
645 save(value)
646 write(SETITEMS)
647 return
Tim Peters82ca59e2003-01-28 16:47:59 +0000648 # else (dict is empty or a singleton), fall through to the
649 # SETITEM code at the end
Tim Peters064567e2003-01-28 01:34:43 +0000650 else: # proto 0 -- can't use EMPTY_DICT or SETITEMS
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000651 write(MARK + DICT)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000652 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000653
Guido van Rossum3a41c612003-01-28 15:10:22 +0000654 # proto 0 or len(obj) < 2
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000655 for key, value in items:
656 save(key)
657 save(value)
Tim Peters064567e2003-01-28 01:34:43 +0000658 write(SETITEM)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000659
660 dispatch[DictionaryType] = save_dict
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000661 if not PyStringMap is None:
662 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000663
Guido van Rossum3a41c612003-01-28 15:10:22 +0000664 def save_inst(self, obj):
665 cls = obj.__class__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000666
667 memo = self.memo
668 write = self.write
669 save = self.save
670
Guido van Rossum3a41c612003-01-28 15:10:22 +0000671 if hasattr(obj, '__getinitargs__'):
672 args = obj.__getinitargs__()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000673 len(args) # XXX Assert it's a sequence
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000674 _keep_alive(args, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000675 else:
676 args = ()
677
678 write(MARK)
679
Tim Petersc32d8242001-04-10 02:48:53 +0000680 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000681 save(cls)
Tim Peters3b769832003-01-28 03:51:36 +0000682 for arg in args:
683 save(arg)
684 write(OBJ)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000685 else:
Tim Peters3b769832003-01-28 03:51:36 +0000686 for arg in args:
687 save(arg)
688 write(INST + cls.__module__ + '\n' + cls.__name__ + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000689
Guido van Rossum3a41c612003-01-28 15:10:22 +0000690 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000691
692 try:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000693 getstate = obj.__getstate__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000694 except AttributeError:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000695 stuff = obj.__dict__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000696 else:
697 stuff = getstate()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000698 _keep_alive(stuff, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000699 save(stuff)
700 write(BUILD)
Tim Peters3b769832003-01-28 03:51:36 +0000701
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000702 dispatch[InstanceType] = save_inst
703
Guido van Rossum3a41c612003-01-28 15:10:22 +0000704 def save_global(self, obj, name = None):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000705 write = self.write
706 memo = self.memo
707
Tim Petersc32d8242001-04-10 02:48:53 +0000708 if name is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000709 name = obj.__name__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000710
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000711 try:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000712 module = obj.__module__
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000713 except AttributeError:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000714 module = whichmodule(obj, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000715
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000716 try:
717 __import__(module)
718 mod = sys.modules[module]
719 klass = getattr(mod, name)
720 except (ImportError, KeyError, AttributeError):
721 raise PicklingError(
722 "Can't pickle %r: it's not found as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000723 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000724 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000725 if klass is not obj:
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000726 raise PicklingError(
727 "Can't pickle %r: it's not the same object as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000728 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000729
Tim Peters518df0d2003-01-28 01:00:38 +0000730 write(GLOBAL + module + '\n' + name + '\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000731 self.memoize(obj)
Tim Peters3b769832003-01-28 03:51:36 +0000732
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000733 dispatch[ClassType] = save_global
734 dispatch[FunctionType] = save_global
735 dispatch[BuiltinFunctionType] = save_global
Tim Peters6d6c1a32001-08-02 04:15:00 +0000736 dispatch[TypeType] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000737
Guido van Rossum1be31752003-01-28 15:19:53 +0000738# Pickling helpers
Guido van Rossuma48061a1995-01-10 00:31:14 +0000739
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000740def _slotnames(cls):
741 """Return a list of slot names for a given class.
742
743 This needs to find slots defined by the class and its bases, so we
744 can't simply return the __slots__ attribute. We must walk down
745 the Method Resolution Order and concatenate the __slots__ of each
746 class found there. (This assumes classes don't modify their
747 __slots__ attribute to misrepresent their slots after the class is
748 defined.)
749 """
750 if not hasattr(cls, "__slots__"):
751 return []
752 names = []
753 for c in cls.__mro__:
754 if "__slots__" in c.__dict__:
755 names += list(c.__dict__["__slots__"])
756 return names
757
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000758def _keep_alive(x, memo):
759 """Keeps a reference to the object x in the memo.
760
761 Because we remember objects by their id, we have
762 to assure that possibly temporary objects are kept
763 alive by referencing them.
764 We store a reference at the id of the memo, which should
765 normally not be used unless someone tries to deepcopy
766 the memo itself...
767 """
768 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000769 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000770 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000771 # aha, this is the first one :-)
772 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000773
774
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000775classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000776
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000777def whichmodule(func, funcname):
778 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000779
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000780 Search sys.modules for the module.
781 Cache in classmap.
782 Return a module name.
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000783 If the function cannot be found, return __main__.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000784 """
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000785 if func in classmap:
786 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000787
788 for name, module in sys.modules.items():
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000789 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000790 continue # skip dummy package entries
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000791 if name != '__main__' and \
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000792 hasattr(module, funcname) and \
793 getattr(module, funcname) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000794 break
795 else:
796 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000797 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000798 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000799
800
Guido van Rossum1be31752003-01-28 15:19:53 +0000801# Unpickling machinery
802
Guido van Rossuma48061a1995-01-10 00:31:14 +0000803class Unpickler:
804
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000805 def __init__(self, file):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000806 """This takes a file-like object for reading a pickle data stream.
807
808 This class automatically determines whether the data stream was
809 written in binary mode or not, so it does not need a flag as in
810 the Pickler class factory.
811
812 The file-like object must have two methods, a read() method that
813 takes an integer argument, and a readline() method that requires no
814 arguments. Both methods should return a string. Thus file-like
815 object can be a file object opened for reading, a StringIO object,
816 or any other custom object that meets this interface.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000817 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000818 self.readline = file.readline
819 self.read = file.read
820 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000821
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000822 def load(self):
Guido van Rossum3a41c612003-01-28 15:10:22 +0000823 """Read a pickled object representation from the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000824
Guido van Rossum3a41c612003-01-28 15:10:22 +0000825 Return the reconstituted object hierarchy specified in the file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000826 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000827 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000828 self.stack = []
829 self.append = self.stack.append
830 read = self.read
831 dispatch = self.dispatch
832 try:
833 while 1:
834 key = read(1)
835 dispatch[key](self)
Guido van Rossumff871742000-12-13 18:11:56 +0000836 except _Stop, stopinst:
837 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000838
Tim Petersc23d18a2003-01-28 01:41:51 +0000839 # Return largest index k such that self.stack[k] is self.mark.
840 # If the stack doesn't contain a mark, eventually raises IndexError.
841 # This could be sped by maintaining another stack, of indices at which
842 # the mark appears. For that matter, the latter stack would suffice,
843 # and we wouldn't need to push mark objects on self.stack at all.
844 # Doing so is probably a good thing, though, since if the pickle is
845 # corrupt (or hostile) we may get a clue from finding self.mark embedded
846 # in unpickled objects.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000847 def marker(self):
848 stack = self.stack
849 mark = self.mark
850 k = len(stack)-1
851 while stack[k] is not mark: k = k-1
852 return k
853
854 dispatch = {}
855
856 def load_eof(self):
857 raise EOFError
858 dispatch[''] = load_eof
859
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000860 def load_proto(self):
861 proto = ord(self.read(1))
862 if not 0 <= proto <= 2:
863 raise ValueError, "unsupported pickle protocol: %d" % proto
864 dispatch[PROTO] = load_proto
865
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000866 def load_persid(self):
867 pid = self.readline()[:-1]
868 self.append(self.persistent_load(pid))
869 dispatch[PERSID] = load_persid
870
871 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000872 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000873 self.append(self.persistent_load(pid))
874 dispatch[BINPERSID] = load_binpersid
875
876 def load_none(self):
877 self.append(None)
878 dispatch[NONE] = load_none
879
Guido van Rossum7d97d312003-01-28 04:25:27 +0000880 def load_false(self):
881 self.append(False)
882 dispatch[NEWFALSE] = load_false
883
884 def load_true(self):
885 self.append(True)
886 dispatch[NEWTRUE] = load_true
887
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000888 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000889 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000890 if data == FALSE[1:]:
891 val = False
892 elif data == TRUE[1:]:
893 val = True
894 else:
895 try:
896 val = int(data)
897 except ValueError:
898 val = long(data)
899 self.append(val)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000900 dispatch[INT] = load_int
901
902 def load_binint(self):
903 self.append(mloads('i' + self.read(4)))
904 dispatch[BININT] = load_binint
905
906 def load_binint1(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000907 self.append(ord(self.read(1)))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000908 dispatch[BININT1] = load_binint1
909
910 def load_binint2(self):
911 self.append(mloads('i' + self.read(2) + '\000\000'))
912 dispatch[BININT2] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000913
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000914 def load_long(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000915 self.append(long(self.readline()[:-1], 0))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000916 dispatch[LONG] = load_long
917
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000918 def load_long1(self):
919 n = ord(self.read(1))
920 bytes = self.read(n)
921 return decode_long(bytes)
922 dispatch[LONG1] = load_long1
923
924 def load_long4(self):
925 n = mloads('i' + self.read(4))
926 bytes = self.read(n)
927 return decode_long(bytes)
928 dispatch[LONG4] = load_long4
929
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000930 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000931 self.append(float(self.readline()[:-1]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000932 dispatch[FLOAT] = load_float
933
Guido van Rossumd3703791998-10-22 20:15:36 +0000934 def load_binfloat(self, unpack=struct.unpack):
935 self.append(unpack('>d', self.read(8))[0])
936 dispatch[BINFLOAT] = load_binfloat
937
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000938 def load_string(self):
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000939 rep = self.readline()[:-1]
Tim Petersad5a7712003-01-28 16:23:33 +0000940 for q in "\"'": # double or single quote
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000941 if rep.startswith(q):
942 if not rep.endswith(q):
943 raise ValueError, "insecure string pickle"
944 rep = rep[len(q):-len(q)]
945 break
946 else:
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000947 raise ValueError, "insecure string pickle"
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000948 self.append(rep.decode("string-escape"))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000949 dispatch[STRING] = load_string
950
951 def load_binstring(self):
952 len = mloads('i' + self.read(4))
953 self.append(self.read(len))
954 dispatch[BINSTRING] = load_binstring
955
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000956 def load_unicode(self):
957 self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
958 dispatch[UNICODE] = load_unicode
959
960 def load_binunicode(self):
961 len = mloads('i' + self.read(4))
962 self.append(unicode(self.read(len),'utf-8'))
963 dispatch[BINUNICODE] = load_binunicode
964
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000965 def load_short_binstring(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000966 len = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000967 self.append(self.read(len))
968 dispatch[SHORT_BINSTRING] = load_short_binstring
969
970 def load_tuple(self):
971 k = self.marker()
972 self.stack[k:] = [tuple(self.stack[k+1:])]
973 dispatch[TUPLE] = load_tuple
974
975 def load_empty_tuple(self):
976 self.stack.append(())
977 dispatch[EMPTY_TUPLE] = load_empty_tuple
978
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000979 def load_tuple1(self):
980 self.stack[-1] = (self.stack[-1],)
981 dispatch[TUPLE1] = load_tuple1
982
983 def load_tuple2(self):
984 self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
985 dispatch[TUPLE2] = load_tuple2
986
987 def load_tuple3(self):
988 self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
989 dispatch[TUPLE3] = load_tuple3
990
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000991 def load_empty_list(self):
992 self.stack.append([])
993 dispatch[EMPTY_LIST] = load_empty_list
994
995 def load_empty_dictionary(self):
996 self.stack.append({})
997 dispatch[EMPTY_DICT] = load_empty_dictionary
998
999 def load_list(self):
1000 k = self.marker()
1001 self.stack[k:] = [self.stack[k+1:]]
1002 dispatch[LIST] = load_list
1003
1004 def load_dict(self):
1005 k = self.marker()
1006 d = {}
1007 items = self.stack[k+1:]
1008 for i in range(0, len(items), 2):
1009 key = items[i]
1010 value = items[i+1]
1011 d[key] = value
1012 self.stack[k:] = [d]
1013 dispatch[DICT] = load_dict
1014
1015 def load_inst(self):
1016 k = self.marker()
1017 args = tuple(self.stack[k+1:])
1018 del self.stack[k:]
1019 module = self.readline()[:-1]
1020 name = self.readline()[:-1]
1021 klass = self.find_class(module, name)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001022 instantiated = 0
1023 if (not args and type(klass) is ClassType and
1024 not hasattr(klass, "__getinitargs__")):
1025 try:
1026 value = _EmptyClass()
1027 value.__class__ = klass
Guido van Rossumb19e2a31998-04-13 18:08:45 +00001028 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001029 except RuntimeError:
1030 # In restricted execution, assignment to inst.__class__ is
1031 # prohibited
1032 pass
1033 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +00001034 try:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001035 value = klass(*args)
Guido van Rossum743d17e1998-09-15 20:25:57 +00001036 except TypeError, err:
1037 raise TypeError, "in constructor for %s: %s" % (
1038 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001039 self.append(value)
1040 dispatch[INST] = load_inst
1041
1042 def load_obj(self):
1043 stack = self.stack
1044 k = self.marker()
1045 klass = stack[k + 1]
1046 del stack[k + 1]
Tim Peters2344fae2001-01-15 00:50:52 +00001047 args = tuple(stack[k + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001048 del stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001049 instantiated = 0
1050 if (not args and type(klass) is ClassType and
1051 not hasattr(klass, "__getinitargs__")):
1052 try:
1053 value = _EmptyClass()
1054 value.__class__ = klass
1055 instantiated = 1
1056 except RuntimeError:
1057 # In restricted execution, assignment to inst.__class__ is
1058 # prohibited
1059 pass
1060 if not instantiated:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001061 value = klass(*args)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001062 self.append(value)
Tim Peters2344fae2001-01-15 00:50:52 +00001063 dispatch[OBJ] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001064
Guido van Rossum3a41c612003-01-28 15:10:22 +00001065 def load_newobj(self):
1066 args = self.stack.pop()
1067 cls = self.stack[-1]
1068 obj = cls.__new__(cls, *args)
Guido van Rossum533dbcf2003-01-28 17:55:05 +00001069 self.stack[-1] = obj
Guido van Rossum3a41c612003-01-28 15:10:22 +00001070 dispatch[NEWOBJ] = load_newobj
1071
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001072 def load_global(self):
1073 module = self.readline()[:-1]
1074 name = self.readline()[:-1]
1075 klass = self.find_class(module, name)
1076 self.append(klass)
1077 dispatch[GLOBAL] = load_global
1078
1079 def find_class(self, module, name):
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001080 # Subclasses may override this
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
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001088 args = stack.pop()
1089 func = stack[-1]
1090 if args is None:
Guido van Rossumbc64e222003-01-28 16:34:19 +00001091 # A hack for Jim Fulton's ExtensionClass, now deprecated
1092 warnings.warn("__basicnew__ special case is deprecated",
Tim Peters8ac14952002-05-23 15:15:30 +00001093 DeprecationWarning)
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001094 value = func.__basicnew__()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001095 else:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001096 value = func(*args)
1097 stack[-1] = value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001098 dispatch[REDUCE] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +00001099
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001100 def load_pop(self):
1101 del self.stack[-1]
1102 dispatch[POP] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +00001103
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001104 def load_pop_mark(self):
1105 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001106 del self.stack[k:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001107 dispatch[POP_MARK] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001108
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001109 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +00001110 self.append(self.stack[-1])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001111 dispatch[DUP] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +00001112
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001113 def load_get(self):
1114 self.append(self.memo[self.readline()[:-1]])
1115 dispatch[GET] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +00001116
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001117 def load_binget(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001118 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001119 self.append(self.memo[`i`])
1120 dispatch[BINGET] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001121
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001122 def load_long_binget(self):
1123 i = mloads('i' + self.read(4))
1124 self.append(self.memo[`i`])
1125 dispatch[LONG_BINGET] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001126
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001127 def load_put(self):
1128 self.memo[self.readline()[:-1]] = self.stack[-1]
1129 dispatch[PUT] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +00001130
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001131 def load_binput(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001132 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001133 self.memo[`i`] = self.stack[-1]
1134 dispatch[BINPUT] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001135
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001136 def load_long_binput(self):
1137 i = mloads('i' + self.read(4))
1138 self.memo[`i`] = self.stack[-1]
1139 dispatch[LONG_BINPUT] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001140
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001141 def load_append(self):
1142 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001143 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001144 list = stack[-1]
1145 list.append(value)
1146 dispatch[APPEND] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +00001147
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001148 def load_appends(self):
1149 stack = self.stack
1150 mark = self.marker()
1151 list = stack[mark - 1]
Tim Peters209ad952003-01-28 01:44:45 +00001152 list.extend(stack[mark + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001153 del stack[mark:]
1154 dispatch[APPENDS] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +00001155
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001156 def load_setitem(self):
1157 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001158 value = stack.pop()
1159 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001160 dict = stack[-1]
1161 dict[key] = value
1162 dispatch[SETITEM] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001163
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001164 def load_setitems(self):
1165 stack = self.stack
1166 mark = self.marker()
1167 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001168 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001169 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001170
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001171 del stack[mark:]
1172 dispatch[SETITEMS] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001173
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001174 def load_build(self):
1175 stack = self.stack
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001176 state = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001177 inst = stack[-1]
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001178 setstate = getattr(inst, "__setstate__", None)
1179 if setstate:
1180 setstate(state)
1181 return
1182 slotstate = None
1183 if isinstance(state, tuple) and len(state) == 2:
1184 state, slotstate = state
1185 if state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001186 try:
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001187 inst.__dict__.update(state)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001188 except RuntimeError:
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001189 # XXX In restricted execution, the instance's __dict__
1190 # is not accessible. Use the old way of unpickling
1191 # the instance variables. This is a semantic
1192 # difference when unpickling in restricted
1193 # vs. unrestricted modes.
1194 for k, v in state.items():
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001195 setattr(inst, k, v)
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001196 if slotstate:
1197 for k, v in slotstate.items():
1198 setattr(inst, k, v)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001199 dispatch[BUILD] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001200
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001201 def load_mark(self):
1202 self.append(self.mark)
1203 dispatch[MARK] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001204
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001205 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001206 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001207 raise _Stop(value)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001208 dispatch[STOP] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001209
Guido van Rossume467be61997-12-05 19:42:42 +00001210# Helper class for load_inst/load_obj
1211
1212class _EmptyClass:
1213 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001214
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001215# Encode/decode longs.
1216
1217def encode_long(x):
1218 r"""Encode a long to a two's complement little-ending binary string.
1219 >>> encode_long(255L)
1220 '\xff\x00'
1221 >>> encode_long(32767L)
1222 '\xff\x7f'
1223 >>> encode_long(-256L)
1224 '\x00\xff'
1225 >>> encode_long(-32768L)
1226 '\x00\x80'
1227 >>> encode_long(-128L)
1228 '\x80'
1229 >>> encode_long(127L)
1230 '\x7f'
1231 >>>
1232 """
Guido van Rossum3d8c01b2003-01-28 19:48:18 +00001233 # XXX This is still a quadratic algorithm.
1234 # Should use hex() to get started.
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001235 digits = []
1236 while not -128 <= x < 128:
1237 digits.append(x & 0xff)
1238 x >>= 8
1239 digits.append(x & 0xff)
1240 return "".join(map(chr, digits))
1241
1242def decode_long(data):
1243 r"""Decode a long from a two's complement little-endian binary string.
1244 >>> decode_long("\xff\x00")
1245 255L
1246 >>> decode_long("\xff\x7f")
1247 32767L
1248 >>> decode_long("\x00\xff")
1249 -256L
1250 >>> decode_long("\x00\x80")
1251 -32768L
1252 >>> decode_long("\x80")
1253 -128L
1254 >>> decode_long("\x7f")
1255 127L
1256 """
Guido van Rossum3d8c01b2003-01-28 19:48:18 +00001257 # XXX This is quadratic too.
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001258 x = 0L
1259 i = 0L
1260 for c in data:
1261 x |= long(ord(c)) << i
1262 i += 8L
1263 if data and ord(c) >= 0x80:
1264 x -= 1L << i
1265 return x
1266
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001267# Shorthands
1268
Jeremy Hyltonabe2c622001-10-15 21:29:28 +00001269try:
1270 from cStringIO import StringIO
1271except ImportError:
1272 from StringIO import StringIO
Guido van Rossumc7c5e691996-07-22 22:26:07 +00001273
Guido van Rossum3a41c612003-01-28 15:10:22 +00001274def dump(obj, file, proto=1):
1275 Pickler(file, proto).dump(obj)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001276
Guido van Rossum3a41c612003-01-28 15:10:22 +00001277def dumps(obj, proto=1):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001278 file = StringIO()
Guido van Rossum3a41c612003-01-28 15:10:22 +00001279 Pickler(file, proto).dump(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001280 return file.getvalue()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001281
1282def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001283 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001284
1285def loads(str):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001286 file = StringIO(str)
1287 return Unpickler(file).load()
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001288
1289# Doctest
1290
1291def _test():
1292 import doctest
1293 return doctest.testmod()
1294
1295if __name__ == "__main__":
1296 _test()