blob: e36e6a6c90c1a4f48176ef97d3b670c1662b25ab [file] [log] [blame]
Guido van Rossum54f22ed2000-02-04 15:10:34 +00001"""Create portable serialized representations of Python objects.
Guido van Rossuma48061a1995-01-10 00:31:14 +00002
Guido van Rossume467be61997-12-05 19:42:42 +00003See module cPickle for a (much) faster implementation.
4See module copy_reg for a mechanism for registering custom picklers.
Tim Peters22a449a2003-01-27 20:16:36 +00005See module pickletools source for extensive comments.
Guido van Rossuma48061a1995-01-10 00:31:14 +00006
Guido van Rossume467be61997-12-05 19:42:42 +00007Classes:
Guido van Rossuma48061a1995-01-10 00:31:14 +00008
Guido van Rossume467be61997-12-05 19:42:42 +00009 Pickler
10 Unpickler
Guido van Rossuma48061a1995-01-10 00:31:14 +000011
Guido van Rossume467be61997-12-05 19:42:42 +000012Functions:
Guido van Rossuma48061a1995-01-10 00:31:14 +000013
Guido van Rossume467be61997-12-05 19:42:42 +000014 dump(object, file)
15 dumps(object) -> string
16 load(file) -> object
17 loads(string) -> object
Guido van Rossuma48061a1995-01-10 00:31:14 +000018
Guido van Rossume467be61997-12-05 19:42:42 +000019Misc variables:
Guido van Rossuma48061a1995-01-10 00:31:14 +000020
Fred Drakefe82acc1998-02-13 03:24:48 +000021 __version__
Guido van Rossume467be61997-12-05 19:42:42 +000022 format_version
23 compatible_formats
Guido van Rossuma48061a1995-01-10 00:31:14 +000024
Guido van Rossuma48061a1995-01-10 00:31:14 +000025"""
26
Guido van Rossum743d17e1998-09-15 20:25:57 +000027__version__ = "$Revision$" # Code version
Guido van Rossuma48061a1995-01-10 00:31:14 +000028
29from types import *
Guido van Rossumb26a97a2003-01-28 22:29:13 +000030from copy_reg import dispatch_table, _reconstructor
Guido van Rossum255f3ee2003-01-29 06:14:11 +000031from copy_reg import extension_registry, inverted_registry, extension_cache
Guido van Rossumd3703791998-10-22 20:15:36 +000032import marshal
33import sys
34import struct
Skip Montanaro23bafc62001-02-18 03:10:09 +000035import re
Guido van Rossumbc64e222003-01-28 16:34:19 +000036import warnings
Guido van Rossuma48061a1995-01-10 00:31:14 +000037
Skip Montanaro352674d2001-02-07 23:14:30 +000038__all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler",
39 "Unpickler", "dump", "dumps", "load", "loads"]
40
Tim Petersc0c12b52003-01-29 00:56:17 +000041# These are purely informational; no code uses these.
Guido van Rossumf29d3d62003-01-27 22:47:53 +000042format_version = "2.0" # File format version we write
43compatible_formats = ["1.0", # Original protocol 0
Guido van Rossumbc64e222003-01-28 16:34:19 +000044 "1.1", # Protocol 0 with INST added
Guido van Rossumf29d3d62003-01-27 22:47:53 +000045 "1.2", # Original protocol 1
46 "1.3", # Protocol 1 with BINFLOAT added
47 "2.0", # Protocol 2
48 ] # Old format versions we can read
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000049
Guido van Rossume0b90422003-01-28 03:17:21 +000050# Why use struct.pack() for pickling but marshal.loads() for
Tim Petersc0c12b52003-01-29 00:56:17 +000051# unpickling? struct.pack() is 40% faster than marshal.dumps(), but
Guido van Rossume0b90422003-01-28 03:17:21 +000052# marshal.loads() is twice as fast as struct.unpack()!
Guido van Rossumb72cf2d1997-04-09 17:32:51 +000053mloads = marshal.loads
Guido van Rossum0c891ce1995-03-14 15:09:05 +000054
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000055class PickleError(Exception):
Neal Norwitzefbb67b2002-05-30 12:12:04 +000056 """A common base class for the other pickling exceptions."""
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000057 pass
58
59class PicklingError(PickleError):
60 """This exception is raised when an unpicklable object is passed to the
61 dump() method.
62
63 """
64 pass
65
66class UnpicklingError(PickleError):
67 """This exception is raised when there is a problem unpickling an object,
68 such as a security violation.
69
70 Note that other exceptions may also be raised during unpickling, including
71 (but not necessarily limited to) AttributeError, EOFError, ImportError,
72 and IndexError.
73
74 """
75 pass
Guido van Rossum7849da81995-03-09 14:08:35 +000076
Tim Petersc0c12b52003-01-29 00:56:17 +000077# An instance of _Stop is raised by Unpickler.load_stop() in response to
78# the STOP opcode, passing the object that is the result of unpickling.
Guido van Rossumff871742000-12-13 18:11:56 +000079class _Stop(Exception):
80 def __init__(self, value):
81 self.value = value
82
Guido van Rossum533dbcf2003-01-28 17:55:05 +000083# Jython has PyStringMap; it's a dict subclass with string keys
Jeremy Hylton2b9d0291998-05-27 22:38:22 +000084try:
85 from org.python.core import PyStringMap
86except ImportError:
87 PyStringMap = None
88
Guido van Rossum533dbcf2003-01-28 17:55:05 +000089# UnicodeType may or may not be exported (normally imported from types)
Guido van Rossumdbb718f2001-09-21 19:22:34 +000090try:
91 UnicodeType
92except NameError:
93 UnicodeType = None
94
Tim Peters22a449a2003-01-27 20:16:36 +000095# Pickle opcodes. See pickletools.py for extensive docs. The listing
96# here is in kind-of alphabetical order of 1-character pickle code.
97# pickletools groups them by purpose.
Guido van Rossumdbb718f2001-09-21 19:22:34 +000098
Tim Peters22a449a2003-01-27 20:16:36 +000099MARK = '(' # push special markobject on stack
100STOP = '.' # every pickle ends with STOP
101POP = '0' # discard topmost stack item
102POP_MARK = '1' # discard stack top through topmost markobject
103DUP = '2' # duplicate top stack item
104FLOAT = 'F' # push float object; decimal string argument
105INT = 'I' # push integer or bool; decimal string argument
106BININT = 'J' # push four-byte signed int
107BININT1 = 'K' # push 1-byte unsigned int
108LONG = 'L' # push long; decimal string argument
109BININT2 = 'M' # push 2-byte unsigned int
110NONE = 'N' # push None
111PERSID = 'P' # push persistent object; id is taken from string arg
112BINPERSID = 'Q' # " " " ; " " " " stack
113REDUCE = 'R' # apply callable to argtuple, both on stack
114STRING = 'S' # push string; NL-terminated string argument
115BINSTRING = 'T' # push string; counted binary string argument
116SHORT_BINSTRING = 'U' # " " ; " " " " < 256 bytes
117UNICODE = 'V' # push Unicode string; raw-unicode-escaped'd argument
118BINUNICODE = 'X' # " " " ; counted UTF-8 string argument
119APPEND = 'a' # append stack top to list below it
120BUILD = 'b' # call __setstate__ or __dict__.update()
121GLOBAL = 'c' # push self.find_class(modname, name); 2 string args
122DICT = 'd' # build a dict from stack items
123EMPTY_DICT = '}' # push empty dict
124APPENDS = 'e' # extend list on stack by topmost stack slice
125GET = 'g' # push item from memo on stack; index is string arg
126BINGET = 'h' # " " " " " " ; " " 1-byte arg
127INST = 'i' # build & push class instance
128LONG_BINGET = 'j' # push item from memo on stack; index is 4-byte arg
129LIST = 'l' # build list from topmost stack items
130EMPTY_LIST = ']' # push empty list
131OBJ = 'o' # build & push class instance
132PUT = 'p' # store stack top in memo; index is string arg
133BINPUT = 'q' # " " " " " ; " " 1-byte arg
134LONG_BINPUT = 'r' # " " " " " ; " " 4-byte arg
135SETITEM = 's' # add key+value pair to dict
136TUPLE = 't' # build tuple from topmost stack items
137EMPTY_TUPLE = ')' # push empty tuple
138SETITEMS = 'u' # modify dict by adding topmost key+value pairs
139BINFLOAT = 'G' # push float; arg is 8-byte float encoding
140
141TRUE = 'I01\n' # not an opcode; see INT docs in pickletools.py
142FALSE = 'I00\n' # not an opcode; see INT docs in pickletools.py
Guido van Rossum77f6a652002-04-03 22:41:51 +0000143
Guido van Rossum586c9e82003-01-29 06:16:12 +0000144# Protocol 2
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000145
Tim Peterse1054782003-01-28 00:22:12 +0000146PROTO = '\x80' # identify pickle protocol
147NEWOBJ = '\x81' # build object by applying cls.__new__ to argtuple
148EXT1 = '\x82' # push object from extension registry; 1-byte index
149EXT2 = '\x83' # ditto, but 2-byte index
150EXT4 = '\x84' # ditto, but 4-byte index
151TUPLE1 = '\x85' # build 1-tuple from stack top
152TUPLE2 = '\x86' # build 2-tuple from two topmost stack items
153TUPLE3 = '\x87' # build 3-tuple from three topmost stack items
154NEWTRUE = '\x88' # push True
155NEWFALSE = '\x89' # push False
156LONG1 = '\x8a' # push long from < 256 bytes
157LONG4 = '\x8b' # push really big long
Guido van Rossum5a2d8f52003-01-27 21:44:25 +0000158
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000159_tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3]
160
Guido van Rossuma48061a1995-01-10 00:31:14 +0000161
Skip Montanaro23bafc62001-02-18 03:10:09 +0000162__all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
Neal Norwitzd5ba4ae2002-02-11 18:12:06 +0000163del x
Skip Montanaro23bafc62001-02-18 03:10:09 +0000164
Guido van Rossum1be31752003-01-28 15:19:53 +0000165
166# Pickling machinery
167
Guido van Rossuma48061a1995-01-10 00:31:14 +0000168class Pickler:
169
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000170 def __init__(self, file, proto=1):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000171 """This takes a file-like object for writing a pickle data stream.
172
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000173 The optional proto argument tells the pickler to use the given
174 protocol; supported protocols are 0, 1, 2. The default
175 protocol is 1 (in previous Python versions the default was 0).
176
177 Protocol 1 is more efficient than protocol 0; protocol 2 is
178 more efficient than protocol 1. Protocol 2 is not the default
179 because it is not supported by older Python versions.
180
181 XXX Protocol 2 is not yet implemented.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000182
183 The file parameter must have a write() method that accepts a single
184 string argument. It can thus be an open file object, a StringIO
185 object, or any other custom object that meets this interface.
186
187 """
Guido van Rossum1be31752003-01-28 15:19:53 +0000188 if proto not in (0, 1, 2):
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000189 raise ValueError, "pickle protocol must be 0, 1 or 2"
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000190 self.write = file.write
191 self.memo = {}
Guido van Rossum1be31752003-01-28 15:19:53 +0000192 self.proto = int(proto)
Guido van Rossumf29d3d62003-01-27 22:47:53 +0000193 self.bin = proto >= 1
Guido van Rossuma48061a1995-01-10 00:31:14 +0000194
Fred Drake7f781c92002-05-01 20:33:53 +0000195 def clear_memo(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000196 """Clears the pickler's "memo".
197
198 The memo is the data structure that remembers which objects the
Tim Petersb377f8a2003-01-28 00:23:36 +0000199 pickler has already seen, so that shared or recursive objects are
200 pickled by reference and not by value. This method is useful when
201 re-using picklers.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000202
203 """
Fred Drake7f781c92002-05-01 20:33:53 +0000204 self.memo.clear()
205
Guido van Rossum3a41c612003-01-28 15:10:22 +0000206 def dump(self, obj):
207 """Write a pickled representation of obj to the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000208
209 Either the binary or ASCII format will be used, depending on the
210 value of the bin flag passed to the constructor.
211
212 """
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000213 if self.proto >= 2:
214 self.write(PROTO + chr(self.proto))
Guido van Rossum3a41c612003-01-28 15:10:22 +0000215 self.save(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000216 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000217
Jeremy Hylton3422c992003-01-24 19:29:52 +0000218 def memoize(self, obj):
219 """Store an object in the memo."""
220
Tim Peterse46b73f2003-01-27 21:22:10 +0000221 # The Pickler memo is a dictionary mapping object ids to 2-tuples
222 # that contain the Unpickler memo key and the object being memoized.
223 # The memo key is written to the pickle and will become
Jeremy Hylton3422c992003-01-24 19:29:52 +0000224 # the key in the Unpickler's memo. The object is stored in the
Tim Peterse46b73f2003-01-27 21:22:10 +0000225 # Pickler memo so that transient objects are kept alive during
226 # pickling.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000227
Tim Peterse46b73f2003-01-27 21:22:10 +0000228 # The use of the Unpickler memo length as the memo key is just a
229 # convention. The only requirement is that the memo values be unique.
230 # But there appears no advantage to any other scheme, and this
Tim Peterscbd0a322003-01-28 00:24:43 +0000231 # scheme allows the Unpickler memo to be implemented as a plain (but
Tim Peterse46b73f2003-01-27 21:22:10 +0000232 # growable) array, indexed by memo key.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000233 memo_len = len(self.memo)
234 self.write(self.put(memo_len))
Tim Peters518df0d2003-01-28 01:00:38 +0000235 self.memo[id(obj)] = memo_len, obj
Jeremy Hylton3422c992003-01-24 19:29:52 +0000236
Tim Petersbb38e302003-01-27 21:25:41 +0000237 # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000238 def put(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000239 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000240 if i < 256:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000241 return BINPUT + chr(i)
242 else:
243 return LONG_BINPUT + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000244
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000245 return PUT + `i` + '\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000246
Tim Petersbb38e302003-01-27 21:25:41 +0000247 # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000248 def get(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000249 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000250 if i < 256:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000251 return BINGET + chr(i)
252 else:
253 return LONG_BINGET + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000254
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000255 return GET + `i` + '\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000256
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000257 def save(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000258 # Check for persistent id (defined by a subclass)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000259 pid = self.persistent_id(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000260 if pid:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000261 self.save_pers(pid)
262 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000263
Guido van Rossumbc64e222003-01-28 16:34:19 +0000264 # Check the memo
265 x = self.memo.get(id(obj))
266 if x:
267 self.write(self.get(x[0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000268 return
269
Guido van Rossumbc64e222003-01-28 16:34:19 +0000270 # Check the type dispatch table
Guido van Rossum3a41c612003-01-28 15:10:22 +0000271 t = type(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000272 f = self.dispatch.get(t)
273 if f:
274 f(self, obj) # Call unbound method with explicit self
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000275 return
276
Guido van Rossumbc64e222003-01-28 16:34:19 +0000277 # Check for a class with a custom metaclass; treat as regular class
Tim Petersb32a8312003-01-28 00:48:09 +0000278 try:
279 issc = issubclass(t, TypeType)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000280 except TypeError: # t is not a class (old Boost; see SF #502085)
Tim Petersb32a8312003-01-28 00:48:09 +0000281 issc = 0
282 if issc:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000283 self.save_global(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000284 return
285
Guido van Rossumbc64e222003-01-28 16:34:19 +0000286 # Check copy_reg.dispatch_table
287 reduce = dispatch_table.get(t)
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000288 if not reduce:
289 # Check for a __reduce__ method.
290 # Subtle: get the unbound method from the class, so that
291 # protocol 2 can override the default __reduce__ that all
292 # classes inherit from object. This has the added
293 # advantage that the call always has the form reduce(obj)
294 reduce = getattr(t, "__reduce__", None)
295 if self.proto >= 2:
296 # Protocol 2 can do better than the default __reduce__
297 if reduce is object.__reduce__:
298 reduce = None
299 if not reduce:
Guido van Rossum54fb1922003-01-28 18:22:35 +0000300 self.save_newobj(obj)
301 return
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000302 if not reduce:
Guido van Rossumbc64e222003-01-28 16:34:19 +0000303 raise PicklingError("Can't pickle %r object: %r" %
304 (t.__name__, obj))
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000305 rv = reduce(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000306
Guido van Rossumbc64e222003-01-28 16:34:19 +0000307 # Check for string returned by reduce(), meaning "save as global"
308 if type(rv) is StringType:
309 self.save_global(obj, rv)
Tim Petersb32a8312003-01-28 00:48:09 +0000310 return
311
Guido van Rossumbc64e222003-01-28 16:34:19 +0000312 # Assert that reduce() returned a tuple
313 if type(rv) is not TupleType:
314 raise PicklingError("%s must return string or tuple" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000315
Guido van Rossumbc64e222003-01-28 16:34:19 +0000316 # Assert that it returned a 2-tuple or 3-tuple, and unpack it
317 l = len(rv)
318 if l == 2:
319 func, args = rv
Tim Petersb32a8312003-01-28 00:48:09 +0000320 state = None
Guido van Rossumbc64e222003-01-28 16:34:19 +0000321 elif l == 3:
322 func, args, state = rv
323 else:
324 raise PicklingError("Tuple returned by %s must have "
325 "exactly two or three elements" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000326
Guido van Rossumbc64e222003-01-28 16:34:19 +0000327 # Save the reduce() output and finally memoize the object
328 self.save_reduce(func, args, state)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000329 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000330
Guido van Rossum3a41c612003-01-28 15:10:22 +0000331 def persistent_id(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000332 # This exists so a subclass can override it
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000333 return None
334
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000335 def save_pers(self, pid):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000336 # Save a persistent id reference
Tim Petersbd1cdb92003-01-28 01:03:10 +0000337 if self.bin:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000338 self.save(pid)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000339 self.write(BINPERSID)
Tim Petersbd1cdb92003-01-28 01:03:10 +0000340 else:
341 self.write(PERSID + str(pid) + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000342
Guido van Rossumbc64e222003-01-28 16:34:19 +0000343 def save_reduce(self, func, args, state=None):
344 # This API is be called by some subclasses
345
346 # Assert that args is a tuple or None
347 if not isinstance(args, TupleType):
348 if args is None:
349 # A hack for Jim Fulton's ExtensionClass, now deprecated.
350 # See load_reduce()
351 warnings.warn("__basicnew__ special case is deprecated",
352 DeprecationWarning)
353 else:
354 raise PicklingError(
355 "args from reduce() should be a tuple")
356
357 # Assert that func is callable
358 if not callable(func):
359 raise PicklingError("func from reduce should be callable")
360
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000361 save = self.save
Guido van Rossumbc64e222003-01-28 16:34:19 +0000362 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000363
Guido van Rossumbc64e222003-01-28 16:34:19 +0000364 save(func)
365 save(args)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000366 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000367
Tim Petersc32d8242001-04-10 02:48:53 +0000368 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000369 save(state)
370 write(BUILD)
371
Guido van Rossum54fb1922003-01-28 18:22:35 +0000372 def save_newobj(self, obj):
373 # Save a new-style class instance, using protocol 2.
Guido van Rossum4e2491d2003-01-28 22:31:25 +0000374 # XXX This is still experimental.
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000375 assert self.proto >= 2 # This only works for protocol 2
Guido van Rossum54fb1922003-01-28 18:22:35 +0000376 t = type(obj)
Guido van Rossum54fb1922003-01-28 18:22:35 +0000377 getnewargs = getattr(obj, "__getnewargs__", None)
378 if getnewargs:
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000379 args = getnewargs() # This bette not reference obj
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000380 else:
Guido van Rossum4e2491d2003-01-28 22:31:25 +0000381 # XXX These types should each grow a __getnewargs__
382 # implementation so this special-casing is unnecessary.
Guido van Rossumb26a97a2003-01-28 22:29:13 +0000383 for cls in int, long, float, complex, str, UnicodeType, tuple:
384 if cls and isinstance(obj, cls):
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000385 args = (cls(obj),)
386 break
387 else:
388 args = ()
389
390 save = self.save
391 write = self.write
392
Guido van Rossum54fb1922003-01-28 18:22:35 +0000393 self.save_global(t)
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000394 save(args)
395 write(NEWOBJ)
Guido van Rossum54fb1922003-01-28 18:22:35 +0000396 self.memoize(obj)
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000397
398 if isinstance(obj, list):
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000399 n = len(obj)
400 if n > 1:
401 write(MARK)
402 for x in obj:
403 save(x)
404 write(APPENDS)
405 elif n == 1:
406 save(obj[0])
407 write(APPEND)
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000408 elif isinstance(obj, dict):
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000409 n = len(obj)
410 if n > 1:
411 write(MARK)
412 for k, v in obj.iteritems():
413 save(k)
414 save(v)
415 write(SETITEMS)
416 elif n == 1:
417 k, v = obj.items()[0]
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000418 save(k)
419 save(v)
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000420 write(SETITEM)
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000421
Guido van Rossum54fb1922003-01-28 18:22:35 +0000422 getstate = getattr(obj, "__getstate__", None)
423 if getstate:
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000424 try:
425 state = getstate()
426 except TypeError, err:
427 # XXX Catch generic exception caused by __slots__
428 if str(err) != ("a class that defines __slots__ "
429 "without defining __getstate__ "
430 "cannot be pickled"):
431 print repr(str(err))
432 raise # Not that specific exception
433 getstate = None
434 if not getstate:
Guido van Rossum54fb1922003-01-28 18:22:35 +0000435 state = getattr(obj, "__dict__", None)
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000436 if not state:
437 state = None
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000438 # If there are slots, the state becomes a tuple of two
439 # items: the first item the regular __dict__ or None, and
440 # the second a dict mapping slot names to slot values
441 names = _slotnames(t)
442 if names:
443 slots = {}
444 nil = []
445 for name in names:
446 value = getattr(obj, name, nil)
447 if value is not nil:
448 slots[name] = value
449 if slots:
450 state = (state, slots)
451
Guido van Rossum54fb1922003-01-28 18:22:35 +0000452 if state is not None:
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000453 save(state)
454 write(BUILD)
Guido van Rossum54fb1922003-01-28 18:22:35 +0000455
Guido van Rossumbc64e222003-01-28 16:34:19 +0000456 # Methods below this point are dispatched through the dispatch table
457
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000458 dispatch = {}
459
Guido van Rossum3a41c612003-01-28 15:10:22 +0000460 def save_none(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000461 self.write(NONE)
462 dispatch[NoneType] = save_none
463
Guido van Rossum3a41c612003-01-28 15:10:22 +0000464 def save_bool(self, obj):
Guido van Rossum7d97d312003-01-28 04:25:27 +0000465 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000466 self.write(obj and NEWTRUE or NEWFALSE)
Guido van Rossum7d97d312003-01-28 04:25:27 +0000467 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000468 self.write(obj and TRUE or FALSE)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000469 dispatch[bool] = save_bool
470
Guido van Rossum3a41c612003-01-28 15:10:22 +0000471 def save_int(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000472 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000473 # If the int is small enough to fit in a signed 4-byte 2's-comp
474 # format, we can store it more efficiently than the general
475 # case.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000476 # First one- and two-byte unsigned ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000477 if obj >= 0:
478 if obj <= 0xff:
479 self.write(BININT1 + chr(obj))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000480 return
Guido van Rossum3a41c612003-01-28 15:10:22 +0000481 if obj <= 0xffff:
482 self.write(BININT2 + chr(obj&0xff) + chr(obj>>8))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000483 return
484 # Next check for 4-byte signed ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000485 high_bits = obj >> 31 # note that Python shift sign-extends
Tim Petersd95c2df2003-01-28 03:41:54 +0000486 if high_bits == 0 or high_bits == -1:
Tim Peters44714002001-04-10 05:02:52 +0000487 # All high bits are copies of bit 2**31, so the value
488 # fits in a 4-byte signed int.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000489 self.write(BININT + pack("<i", obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000490 return
Tim Peters44714002001-04-10 05:02:52 +0000491 # Text pickle, or int too big to fit in signed 4-byte format.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000492 self.write(INT + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000493 dispatch[IntType] = save_int
494
Guido van Rossum3a41c612003-01-28 15:10:22 +0000495 def save_long(self, obj, pack=struct.pack):
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000496 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000497 bytes = encode_long(obj)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000498 n = len(bytes)
499 if n < 256:
500 self.write(LONG1 + chr(n) + bytes)
501 else:
502 self.write(LONG4 + pack("<i", n) + bytes)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000503 self.write(LONG + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000504 dispatch[LongType] = save_long
505
Guido van Rossum3a41c612003-01-28 15:10:22 +0000506 def save_float(self, obj, pack=struct.pack):
Guido van Rossumd3703791998-10-22 20:15:36 +0000507 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000508 self.write(BINFLOAT + pack('>d', obj))
Guido van Rossumd3703791998-10-22 20:15:36 +0000509 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000510 self.write(FLOAT + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000511 dispatch[FloatType] = save_float
512
Guido van Rossum3a41c612003-01-28 15:10:22 +0000513 def save_string(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000514 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000515 n = len(obj)
Tim Petersbbf63cd2003-01-27 21:15:36 +0000516 if n < 256:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000517 self.write(SHORT_BINSTRING + chr(n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000518 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000519 self.write(BINSTRING + pack("<i", n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000520 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000521 self.write(STRING + `obj` + '\n')
522 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000523 dispatch[StringType] = save_string
524
Guido van Rossum3a41c612003-01-28 15:10:22 +0000525 def save_unicode(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000526 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000527 encoding = obj.encode('utf-8')
Tim Petersbbf63cd2003-01-27 21:15:36 +0000528 n = len(encoding)
Guido van Rossum5c938d02003-01-28 03:03:08 +0000529 self.write(BINUNICODE + pack("<i", n) + encoding)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000530 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000531 obj = obj.replace("\\", "\\u005c")
532 obj = obj.replace("\n", "\\u000a")
533 self.write(UNICODE + obj.encode('raw-unicode-escape') + '\n')
534 self.memoize(obj)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000535 dispatch[UnicodeType] = save_unicode
536
Guido van Rossum31584cb2001-01-22 14:53:29 +0000537 if StringType == UnicodeType:
538 # This is true for Jython
Guido van Rossum3a41c612003-01-28 15:10:22 +0000539 def save_string(self, obj, pack=struct.pack):
540 unicode = obj.isunicode()
Guido van Rossum31584cb2001-01-22 14:53:29 +0000541
Tim Petersc32d8242001-04-10 02:48:53 +0000542 if self.bin:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000543 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000544 obj = obj.encode("utf-8")
545 l = len(obj)
Tim Petersc32d8242001-04-10 02:48:53 +0000546 if l < 256 and not unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000547 self.write(SHORT_BINSTRING + chr(l) + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000548 else:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000549 s = pack("<i", l)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000550 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000551 self.write(BINUNICODE + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000552 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000553 self.write(BINSTRING + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000554 else:
Tim Peters658cba62001-02-09 20:06:00 +0000555 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000556 obj = obj.replace("\\", "\\u005c")
557 obj = obj.replace("\n", "\\u000a")
558 obj = obj.encode('raw-unicode-escape')
559 self.write(UNICODE + obj + '\n')
Guido van Rossum31584cb2001-01-22 14:53:29 +0000560 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000561 self.write(STRING + `obj` + '\n')
562 self.memoize(obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000563 dispatch[StringType] = save_string
Tim Peters658cba62001-02-09 20:06:00 +0000564
Guido van Rossum3a41c612003-01-28 15:10:22 +0000565 def save_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000566 write = self.write
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000567 proto = self.proto
568
Guido van Rossum3a41c612003-01-28 15:10:22 +0000569 n = len(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000570 if n == 0 and proto:
571 write(EMPTY_TUPLE)
572 return
573
574 save = self.save
575 memo = self.memo
576 if n <= 3 and proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000577 for element in obj:
Tim Petersd97da802003-01-28 05:48:29 +0000578 save(element)
579 # Subtle. Same as in the big comment below.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000580 if id(obj) in memo:
581 get = self.get(memo[id(obj)][0])
Tim Petersd97da802003-01-28 05:48:29 +0000582 write(POP * n + get)
583 else:
584 write(_tuplesize2code[n])
Guido van Rossum3a41c612003-01-28 15:10:22 +0000585 self.memoize(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000586 return
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000587
Tim Petersff57bff2003-01-28 05:34:53 +0000588 # proto 0, or proto 1 and tuple isn't empty, or proto > 1 and tuple
589 # has more than 3 elements.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000590 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000591 for element in obj:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000592 save(element)
593
Guido van Rossum3a41c612003-01-28 15:10:22 +0000594 if n and id(obj) in memo:
Tim Petersf558da02003-01-28 02:09:55 +0000595 # Subtle. d was not in memo when we entered save_tuple(), so
596 # the process of saving the tuple's elements must have saved
597 # the tuple itself: the tuple is recursive. The proper action
598 # now is to throw away everything we put on the stack, and
599 # simply GET the tuple (it's already constructed). This check
600 # could have been done in the "for element" loop instead, but
601 # recursive tuples are a rare thing.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000602 get = self.get(memo[id(obj)][0])
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000603 if proto:
Tim Petersf558da02003-01-28 02:09:55 +0000604 write(POP_MARK + get)
605 else: # proto 0 -- POP_MARK not available
Tim Petersd97da802003-01-28 05:48:29 +0000606 write(POP * (n+1) + get)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000607 return
608
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000609 # No recursion (including the empty-tuple case for protocol 0).
Tim Peters518df0d2003-01-28 01:00:38 +0000610 self.write(TUPLE)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000611 if obj: # No need to memoize empty tuple
612 self.memoize(obj)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000613
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000614 dispatch[TupleType] = save_tuple
615
Tim Petersa6ae9a22003-01-28 16:58:41 +0000616 # save_empty_tuple() isn't used by anything in Python 2.3. However, I
617 # found a Pickler subclass in Zope3 that calls it, so it's not harmless
618 # to remove it.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000619 def save_empty_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000620 self.write(EMPTY_TUPLE)
621
Guido van Rossum3a41c612003-01-28 15:10:22 +0000622 def save_list(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000623 write = self.write
624 save = self.save
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000625
Tim Petersc32d8242001-04-10 02:48:53 +0000626 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000627 write(EMPTY_LIST)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000628 self.memoize(obj)
629 n = len(obj)
Tim Peters21c18f02003-01-28 01:15:46 +0000630 if n > 1:
631 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000632 for element in obj:
Tim Peters21c18f02003-01-28 01:15:46 +0000633 save(element)
634 write(APPENDS)
635 elif n:
636 assert n == 1
Guido van Rossum3a41c612003-01-28 15:10:22 +0000637 save(obj[0])
Tim Peters21c18f02003-01-28 01:15:46 +0000638 write(APPEND)
639 # else the list is empty, and we're already done
640
641 else: # proto 0 -- can't use EMPTY_LIST or APPENDS
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000642 write(MARK + LIST)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000643 self.memoize(obj)
644 for element in obj:
Tim Peters21c18f02003-01-28 01:15:46 +0000645 save(element)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000646 write(APPEND)
647
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000648 dispatch[ListType] = save_list
649
Guido van Rossum3a41c612003-01-28 15:10:22 +0000650 def save_dict(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000651 write = self.write
652 save = self.save
Guido van Rossum3a41c612003-01-28 15:10:22 +0000653 items = obj.iteritems()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000654
Tim Petersc32d8242001-04-10 02:48:53 +0000655 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000656 write(EMPTY_DICT)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000657 self.memoize(obj)
658 if len(obj) > 1:
Tim Peters064567e2003-01-28 01:34:43 +0000659 write(MARK)
660 for key, value in items:
661 save(key)
662 save(value)
663 write(SETITEMS)
664 return
Tim Peters82ca59e2003-01-28 16:47:59 +0000665 # else (dict is empty or a singleton), fall through to the
666 # SETITEM code at the end
Tim Peters064567e2003-01-28 01:34:43 +0000667 else: # proto 0 -- can't use EMPTY_DICT or SETITEMS
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000668 write(MARK + DICT)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000669 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000670
Guido van Rossum3a41c612003-01-28 15:10:22 +0000671 # proto 0 or len(obj) < 2
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000672 for key, value in items:
673 save(key)
674 save(value)
Tim Peters064567e2003-01-28 01:34:43 +0000675 write(SETITEM)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000676
677 dispatch[DictionaryType] = save_dict
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000678 if not PyStringMap is None:
679 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000680
Guido van Rossum3a41c612003-01-28 15:10:22 +0000681 def save_inst(self, obj):
682 cls = obj.__class__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000683
684 memo = self.memo
685 write = self.write
686 save = self.save
687
Guido van Rossum3a41c612003-01-28 15:10:22 +0000688 if hasattr(obj, '__getinitargs__'):
689 args = obj.__getinitargs__()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000690 len(args) # XXX Assert it's a sequence
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000691 _keep_alive(args, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000692 else:
693 args = ()
694
695 write(MARK)
696
Tim Petersc32d8242001-04-10 02:48:53 +0000697 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000698 save(cls)
Tim Peters3b769832003-01-28 03:51:36 +0000699 for arg in args:
700 save(arg)
701 write(OBJ)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000702 else:
Tim Peters3b769832003-01-28 03:51:36 +0000703 for arg in args:
704 save(arg)
705 write(INST + cls.__module__ + '\n' + cls.__name__ + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000706
Guido van Rossum3a41c612003-01-28 15:10:22 +0000707 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000708
709 try:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000710 getstate = obj.__getstate__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000711 except AttributeError:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000712 stuff = obj.__dict__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000713 else:
714 stuff = getstate()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000715 _keep_alive(stuff, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000716 save(stuff)
717 write(BUILD)
Tim Peters3b769832003-01-28 03:51:36 +0000718
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000719 dispatch[InstanceType] = save_inst
720
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000721 def save_global(self, obj, name=None, pack=struct.pack):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000722 write = self.write
723 memo = self.memo
724
Tim Petersc32d8242001-04-10 02:48:53 +0000725 if name is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000726 name = obj.__name__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000727
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000728 try:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000729 module = obj.__module__
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000730 except AttributeError:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000731 module = whichmodule(obj, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000732
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000733 try:
734 __import__(module)
735 mod = sys.modules[module]
736 klass = getattr(mod, name)
737 except (ImportError, KeyError, AttributeError):
738 raise PicklingError(
739 "Can't pickle %r: it's not found as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000740 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000741 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000742 if klass is not obj:
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000743 raise PicklingError(
744 "Can't pickle %r: it's not the same object as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000745 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000746
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000747 if self.proto >= 2:
748 code = extension_registry.get((module, name))
749 if code:
750 assert code > 0
751 if code <= 0xff:
752 write(EXT1 + chr(code))
753 elif code <= 0xffff:
754 write(EXT2 + chr(code&0xff) + chr(code>>8))
755 else:
756 write(EXT4 + pack("<i", code))
757 return
758
Tim Peters518df0d2003-01-28 01:00:38 +0000759 write(GLOBAL + module + '\n' + name + '\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000760 self.memoize(obj)
Tim Peters3b769832003-01-28 03:51:36 +0000761
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000762 dispatch[ClassType] = save_global
763 dispatch[FunctionType] = save_global
764 dispatch[BuiltinFunctionType] = save_global
Tim Peters6d6c1a32001-08-02 04:15:00 +0000765 dispatch[TypeType] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000766
Guido van Rossum1be31752003-01-28 15:19:53 +0000767# Pickling helpers
Guido van Rossuma48061a1995-01-10 00:31:14 +0000768
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000769def _slotnames(cls):
770 """Return a list of slot names for a given class.
771
772 This needs to find slots defined by the class and its bases, so we
773 can't simply return the __slots__ attribute. We must walk down
774 the Method Resolution Order and concatenate the __slots__ of each
775 class found there. (This assumes classes don't modify their
776 __slots__ attribute to misrepresent their slots after the class is
777 defined.)
778 """
779 if not hasattr(cls, "__slots__"):
780 return []
781 names = []
782 for c in cls.__mro__:
783 if "__slots__" in c.__dict__:
784 names += list(c.__dict__["__slots__"])
785 return names
786
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000787def _keep_alive(x, memo):
788 """Keeps a reference to the object x in the memo.
789
790 Because we remember objects by their id, we have
791 to assure that possibly temporary objects are kept
792 alive by referencing them.
793 We store a reference at the id of the memo, which should
794 normally not be used unless someone tries to deepcopy
795 the memo itself...
796 """
797 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000798 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000799 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000800 # aha, this is the first one :-)
801 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000802
803
Tim Petersc0c12b52003-01-29 00:56:17 +0000804# A cache for whichmodule(), mapping a function object to the name of
805# the module in which the function was found.
806
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000807classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000808
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000809def whichmodule(func, funcname):
810 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000811
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000812 Search sys.modules for the module.
813 Cache in classmap.
814 Return a module name.
Tim Petersc0c12b52003-01-29 00:56:17 +0000815 If the function cannot be found, return "__main__".
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000816 """
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000817 if func in classmap:
818 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000819
820 for name, module in sys.modules.items():
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000821 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000822 continue # skip dummy package entries
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000823 if name != '__main__' and \
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000824 hasattr(module, funcname) and \
825 getattr(module, funcname) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000826 break
827 else:
828 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000829 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000830 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000831
832
Guido van Rossum1be31752003-01-28 15:19:53 +0000833# Unpickling machinery
834
Guido van Rossuma48061a1995-01-10 00:31:14 +0000835class Unpickler:
836
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000837 def __init__(self, file):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000838 """This takes a file-like object for reading a pickle data stream.
839
840 This class automatically determines whether the data stream was
841 written in binary mode or not, so it does not need a flag as in
842 the Pickler class factory.
843
844 The file-like object must have two methods, a read() method that
845 takes an integer argument, and a readline() method that requires no
846 arguments. Both methods should return a string. Thus file-like
847 object can be a file object opened for reading, a StringIO object,
848 or any other custom object that meets this interface.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000849 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000850 self.readline = file.readline
851 self.read = file.read
852 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000853
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000854 def load(self):
Guido van Rossum3a41c612003-01-28 15:10:22 +0000855 """Read a pickled object representation from the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000856
Guido van Rossum3a41c612003-01-28 15:10:22 +0000857 Return the reconstituted object hierarchy specified in the file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000858 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000859 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000860 self.stack = []
861 self.append = self.stack.append
862 read = self.read
863 dispatch = self.dispatch
864 try:
865 while 1:
866 key = read(1)
867 dispatch[key](self)
Guido van Rossumff871742000-12-13 18:11:56 +0000868 except _Stop, stopinst:
869 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000870
Tim Petersc23d18a2003-01-28 01:41:51 +0000871 # Return largest index k such that self.stack[k] is self.mark.
872 # If the stack doesn't contain a mark, eventually raises IndexError.
873 # This could be sped by maintaining another stack, of indices at which
874 # the mark appears. For that matter, the latter stack would suffice,
875 # and we wouldn't need to push mark objects on self.stack at all.
876 # Doing so is probably a good thing, though, since if the pickle is
877 # corrupt (or hostile) we may get a clue from finding self.mark embedded
878 # in unpickled objects.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000879 def marker(self):
880 stack = self.stack
881 mark = self.mark
882 k = len(stack)-1
883 while stack[k] is not mark: k = k-1
884 return k
885
886 dispatch = {}
887
888 def load_eof(self):
889 raise EOFError
890 dispatch[''] = load_eof
891
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000892 def load_proto(self):
893 proto = ord(self.read(1))
894 if not 0 <= proto <= 2:
895 raise ValueError, "unsupported pickle protocol: %d" % proto
896 dispatch[PROTO] = load_proto
897
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000898 def load_persid(self):
899 pid = self.readline()[:-1]
900 self.append(self.persistent_load(pid))
901 dispatch[PERSID] = load_persid
902
903 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000904 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000905 self.append(self.persistent_load(pid))
906 dispatch[BINPERSID] = load_binpersid
907
908 def load_none(self):
909 self.append(None)
910 dispatch[NONE] = load_none
911
Guido van Rossum7d97d312003-01-28 04:25:27 +0000912 def load_false(self):
913 self.append(False)
914 dispatch[NEWFALSE] = load_false
915
916 def load_true(self):
917 self.append(True)
918 dispatch[NEWTRUE] = load_true
919
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000920 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000921 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000922 if data == FALSE[1:]:
923 val = False
924 elif data == TRUE[1:]:
925 val = True
926 else:
927 try:
928 val = int(data)
929 except ValueError:
930 val = long(data)
931 self.append(val)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000932 dispatch[INT] = load_int
933
934 def load_binint(self):
935 self.append(mloads('i' + self.read(4)))
936 dispatch[BININT] = load_binint
937
938 def load_binint1(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000939 self.append(ord(self.read(1)))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000940 dispatch[BININT1] = load_binint1
941
942 def load_binint2(self):
943 self.append(mloads('i' + self.read(2) + '\000\000'))
944 dispatch[BININT2] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +0000945
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000946 def load_long(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000947 self.append(long(self.readline()[:-1], 0))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000948 dispatch[LONG] = load_long
949
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000950 def load_long1(self):
951 n = ord(self.read(1))
952 bytes = self.read(n)
953 return decode_long(bytes)
954 dispatch[LONG1] = load_long1
955
956 def load_long4(self):
957 n = mloads('i' + self.read(4))
958 bytes = self.read(n)
959 return decode_long(bytes)
960 dispatch[LONG4] = load_long4
961
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000962 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +0000963 self.append(float(self.readline()[:-1]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000964 dispatch[FLOAT] = load_float
965
Guido van Rossumd3703791998-10-22 20:15:36 +0000966 def load_binfloat(self, unpack=struct.unpack):
967 self.append(unpack('>d', self.read(8))[0])
968 dispatch[BINFLOAT] = load_binfloat
969
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000970 def load_string(self):
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000971 rep = self.readline()[:-1]
Tim Petersad5a7712003-01-28 16:23:33 +0000972 for q in "\"'": # double or single quote
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000973 if rep.startswith(q):
974 if not rep.endswith(q):
975 raise ValueError, "insecure string pickle"
976 rep = rep[len(q):-len(q)]
977 break
978 else:
Jeremy Hyltonbe467e52000-09-15 15:14:51 +0000979 raise ValueError, "insecure string pickle"
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000980 self.append(rep.decode("string-escape"))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000981 dispatch[STRING] = load_string
982
983 def load_binstring(self):
984 len = mloads('i' + self.read(4))
985 self.append(self.read(len))
986 dispatch[BINSTRING] = load_binstring
987
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000988 def load_unicode(self):
989 self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
990 dispatch[UNICODE] = load_unicode
991
992 def load_binunicode(self):
993 len = mloads('i' + self.read(4))
994 self.append(unicode(self.read(len),'utf-8'))
995 dispatch[BINUNICODE] = load_binunicode
996
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000997 def load_short_binstring(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +0000998 len = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000999 self.append(self.read(len))
1000 dispatch[SHORT_BINSTRING] = load_short_binstring
1001
1002 def load_tuple(self):
1003 k = self.marker()
1004 self.stack[k:] = [tuple(self.stack[k+1:])]
1005 dispatch[TUPLE] = load_tuple
1006
1007 def load_empty_tuple(self):
1008 self.stack.append(())
1009 dispatch[EMPTY_TUPLE] = load_empty_tuple
1010
Guido van Rossum44f0ea52003-01-28 04:14:51 +00001011 def load_tuple1(self):
1012 self.stack[-1] = (self.stack[-1],)
1013 dispatch[TUPLE1] = load_tuple1
1014
1015 def load_tuple2(self):
1016 self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
1017 dispatch[TUPLE2] = load_tuple2
1018
1019 def load_tuple3(self):
1020 self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
1021 dispatch[TUPLE3] = load_tuple3
1022
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001023 def load_empty_list(self):
1024 self.stack.append([])
1025 dispatch[EMPTY_LIST] = load_empty_list
1026
1027 def load_empty_dictionary(self):
1028 self.stack.append({})
1029 dispatch[EMPTY_DICT] = load_empty_dictionary
1030
1031 def load_list(self):
1032 k = self.marker()
1033 self.stack[k:] = [self.stack[k+1:]]
1034 dispatch[LIST] = load_list
1035
1036 def load_dict(self):
1037 k = self.marker()
1038 d = {}
1039 items = self.stack[k+1:]
1040 for i in range(0, len(items), 2):
1041 key = items[i]
1042 value = items[i+1]
1043 d[key] = value
1044 self.stack[k:] = [d]
1045 dispatch[DICT] = load_dict
1046
1047 def load_inst(self):
1048 k = self.marker()
1049 args = tuple(self.stack[k+1:])
1050 del self.stack[k:]
1051 module = self.readline()[:-1]
1052 name = self.readline()[:-1]
1053 klass = self.find_class(module, name)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001054 instantiated = 0
1055 if (not args and type(klass) is ClassType and
1056 not hasattr(klass, "__getinitargs__")):
1057 try:
1058 value = _EmptyClass()
1059 value.__class__ = klass
Guido van Rossumb19e2a31998-04-13 18:08:45 +00001060 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001061 except RuntimeError:
1062 # In restricted execution, assignment to inst.__class__ is
1063 # prohibited
1064 pass
1065 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +00001066 try:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001067 value = klass(*args)
Guido van Rossum743d17e1998-09-15 20:25:57 +00001068 except TypeError, err:
1069 raise TypeError, "in constructor for %s: %s" % (
1070 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001071 self.append(value)
1072 dispatch[INST] = load_inst
1073
1074 def load_obj(self):
1075 stack = self.stack
1076 k = self.marker()
1077 klass = stack[k + 1]
1078 del stack[k + 1]
Tim Peters2344fae2001-01-15 00:50:52 +00001079 args = tuple(stack[k + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001080 del stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001081 instantiated = 0
1082 if (not args and type(klass) is ClassType and
1083 not hasattr(klass, "__getinitargs__")):
1084 try:
1085 value = _EmptyClass()
1086 value.__class__ = klass
1087 instantiated = 1
1088 except RuntimeError:
1089 # In restricted execution, assignment to inst.__class__ is
1090 # prohibited
1091 pass
1092 if not instantiated:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001093 value = klass(*args)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001094 self.append(value)
Tim Peters2344fae2001-01-15 00:50:52 +00001095 dispatch[OBJ] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001096
Guido van Rossum3a41c612003-01-28 15:10:22 +00001097 def load_newobj(self):
1098 args = self.stack.pop()
1099 cls = self.stack[-1]
1100 obj = cls.__new__(cls, *args)
Guido van Rossum533dbcf2003-01-28 17:55:05 +00001101 self.stack[-1] = obj
Guido van Rossum3a41c612003-01-28 15:10:22 +00001102 dispatch[NEWOBJ] = load_newobj
1103
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001104 def load_global(self):
1105 module = self.readline()[:-1]
1106 name = self.readline()[:-1]
1107 klass = self.find_class(module, name)
1108 self.append(klass)
1109 dispatch[GLOBAL] = load_global
1110
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001111 def load_ext1(self):
1112 code = ord(self.read(1))
1113 self.get_extension(code)
1114 dispatch[EXT1] = load_ext1
1115
1116 def load_ext2(self):
1117 code = mloads('i' + self.read(2) + '\000\000')
1118 self.get_extension(code)
1119 dispatch[EXT2] = load_ext2
1120
1121 def load_ext4(self):
1122 code = mloads('i' + self.read(4))
1123 self.get_extension(code)
1124 dispatch[EXT4] = load_ext4
1125
1126 def get_extension(self, code):
1127 nil = []
1128 obj = extension_cache.get(code, nil)
1129 if obj is not nil:
1130 self.append(obj)
1131 return
1132 key = inverted_registry.get(code)
1133 if not key:
1134 raise ValueError("unregistered extension code %d" % code)
1135 obj = self.find_class(*key)
1136 extension_cache[code] = obj
1137 self.append(obj)
1138
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001139 def find_class(self, module, name):
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001140 # Subclasses may override this
Barry Warsawbf4d9592001-11-15 23:42:58 +00001141 __import__(module)
1142 mod = sys.modules[module]
1143 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001144 return klass
1145
1146 def load_reduce(self):
1147 stack = self.stack
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001148 args = stack.pop()
1149 func = stack[-1]
1150 if args is None:
Guido van Rossumbc64e222003-01-28 16:34:19 +00001151 # A hack for Jim Fulton's ExtensionClass, now deprecated
1152 warnings.warn("__basicnew__ special case is deprecated",
Tim Peters8ac14952002-05-23 15:15:30 +00001153 DeprecationWarning)
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001154 value = func.__basicnew__()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001155 else:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001156 value = func(*args)
1157 stack[-1] = value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001158 dispatch[REDUCE] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +00001159
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001160 def load_pop(self):
1161 del self.stack[-1]
1162 dispatch[POP] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +00001163
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001164 def load_pop_mark(self):
1165 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001166 del self.stack[k:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001167 dispatch[POP_MARK] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001168
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001169 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +00001170 self.append(self.stack[-1])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001171 dispatch[DUP] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +00001172
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001173 def load_get(self):
1174 self.append(self.memo[self.readline()[:-1]])
1175 dispatch[GET] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +00001176
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001177 def load_binget(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001178 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001179 self.append(self.memo[`i`])
1180 dispatch[BINGET] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001181
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001182 def load_long_binget(self):
1183 i = mloads('i' + self.read(4))
1184 self.append(self.memo[`i`])
1185 dispatch[LONG_BINGET] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001186
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001187 def load_put(self):
1188 self.memo[self.readline()[:-1]] = self.stack[-1]
1189 dispatch[PUT] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +00001190
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001191 def load_binput(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001192 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001193 self.memo[`i`] = self.stack[-1]
1194 dispatch[BINPUT] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001195
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001196 def load_long_binput(self):
1197 i = mloads('i' + self.read(4))
1198 self.memo[`i`] = self.stack[-1]
1199 dispatch[LONG_BINPUT] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001200
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001201 def load_append(self):
1202 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001203 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001204 list = stack[-1]
1205 list.append(value)
1206 dispatch[APPEND] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +00001207
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001208 def load_appends(self):
1209 stack = self.stack
1210 mark = self.marker()
1211 list = stack[mark - 1]
Tim Peters209ad952003-01-28 01:44:45 +00001212 list.extend(stack[mark + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001213 del stack[mark:]
1214 dispatch[APPENDS] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +00001215
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001216 def load_setitem(self):
1217 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001218 value = stack.pop()
1219 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001220 dict = stack[-1]
1221 dict[key] = value
1222 dispatch[SETITEM] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001223
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001224 def load_setitems(self):
1225 stack = self.stack
1226 mark = self.marker()
1227 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001228 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001229 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001230
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001231 del stack[mark:]
1232 dispatch[SETITEMS] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001233
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001234 def load_build(self):
1235 stack = self.stack
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001236 state = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001237 inst = stack[-1]
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001238 setstate = getattr(inst, "__setstate__", None)
1239 if setstate:
1240 setstate(state)
1241 return
1242 slotstate = None
1243 if isinstance(state, tuple) and len(state) == 2:
1244 state, slotstate = state
1245 if state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001246 try:
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001247 inst.__dict__.update(state)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001248 except RuntimeError:
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001249 # XXX In restricted execution, the instance's __dict__
1250 # is not accessible. Use the old way of unpickling
1251 # the instance variables. This is a semantic
1252 # difference when unpickling in restricted
1253 # vs. unrestricted modes.
1254 for k, v in state.items():
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001255 setattr(inst, k, v)
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001256 if slotstate:
1257 for k, v in slotstate.items():
1258 setattr(inst, k, v)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001259 dispatch[BUILD] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001260
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001261 def load_mark(self):
1262 self.append(self.mark)
1263 dispatch[MARK] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001264
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001265 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001266 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001267 raise _Stop(value)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001268 dispatch[STOP] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001269
Guido van Rossume467be61997-12-05 19:42:42 +00001270# Helper class for load_inst/load_obj
1271
1272class _EmptyClass:
1273 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001274
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001275# Encode/decode longs.
1276
1277def encode_long(x):
1278 r"""Encode a long to a two's complement little-ending binary string.
1279 >>> encode_long(255L)
1280 '\xff\x00'
1281 >>> encode_long(32767L)
1282 '\xff\x7f'
1283 >>> encode_long(-256L)
1284 '\x00\xff'
1285 >>> encode_long(-32768L)
1286 '\x00\x80'
1287 >>> encode_long(-128L)
1288 '\x80'
1289 >>> encode_long(127L)
1290 '\x7f'
1291 >>>
1292 """
Guido van Rossum3d8c01b2003-01-28 19:48:18 +00001293 # XXX This is still a quadratic algorithm.
1294 # Should use hex() to get started.
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001295 digits = []
1296 while not -128 <= x < 128:
1297 digits.append(x & 0xff)
1298 x >>= 8
1299 digits.append(x & 0xff)
1300 return "".join(map(chr, digits))
1301
1302def decode_long(data):
1303 r"""Decode a long from a two's complement little-endian binary string.
1304 >>> decode_long("\xff\x00")
1305 255L
1306 >>> decode_long("\xff\x7f")
1307 32767L
1308 >>> decode_long("\x00\xff")
1309 -256L
1310 >>> decode_long("\x00\x80")
1311 -32768L
1312 >>> decode_long("\x80")
1313 -128L
1314 >>> decode_long("\x7f")
1315 127L
1316 """
Guido van Rossum3d8c01b2003-01-28 19:48:18 +00001317 # XXX This is quadratic too.
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001318 x = 0L
1319 i = 0L
1320 for c in data:
1321 x |= long(ord(c)) << i
1322 i += 8L
1323 if data and ord(c) >= 0x80:
1324 x -= 1L << i
1325 return x
1326
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001327# Shorthands
1328
Jeremy Hyltonabe2c622001-10-15 21:29:28 +00001329try:
1330 from cStringIO import StringIO
1331except ImportError:
1332 from StringIO import StringIO
Guido van Rossumc7c5e691996-07-22 22:26:07 +00001333
Guido van Rossum3a41c612003-01-28 15:10:22 +00001334def dump(obj, file, proto=1):
1335 Pickler(file, proto).dump(obj)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001336
Guido van Rossum3a41c612003-01-28 15:10:22 +00001337def dumps(obj, proto=1):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001338 file = StringIO()
Guido van Rossum3a41c612003-01-28 15:10:22 +00001339 Pickler(file, proto).dump(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001340 return file.getvalue()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001341
1342def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001343 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001344
1345def loads(str):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001346 file = StringIO(str)
1347 return Unpickler(file).load()
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001348
1349# Doctest
1350
1351def _test():
1352 import doctest
1353 return doctest.testmod()
1354
1355if __name__ == "__main__":
1356 _test()