blob: e365bd11d9d0b3f2c58c0c7a7cea31a670cebb70 [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 Rossum5d9113d2003-01-29 17:58:45 +0000194 self.fast = 0
Guido van Rossuma48061a1995-01-10 00:31:14 +0000195
Fred Drake7f781c92002-05-01 20:33:53 +0000196 def clear_memo(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000197 """Clears the pickler's "memo".
198
199 The memo is the data structure that remembers which objects the
Tim Petersb377f8a2003-01-28 00:23:36 +0000200 pickler has already seen, so that shared or recursive objects are
201 pickled by reference and not by value. This method is useful when
202 re-using picklers.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000203
204 """
Fred Drake7f781c92002-05-01 20:33:53 +0000205 self.memo.clear()
206
Guido van Rossum3a41c612003-01-28 15:10:22 +0000207 def dump(self, obj):
208 """Write a pickled representation of obj to the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000209
210 Either the binary or ASCII format will be used, depending on the
211 value of the bin flag passed to the constructor.
212
213 """
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000214 if self.proto >= 2:
215 self.write(PROTO + chr(self.proto))
Guido van Rossum3a41c612003-01-28 15:10:22 +0000216 self.save(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000217 self.write(STOP)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000218
Jeremy Hylton3422c992003-01-24 19:29:52 +0000219 def memoize(self, obj):
220 """Store an object in the memo."""
221
Tim Peterse46b73f2003-01-27 21:22:10 +0000222 # The Pickler memo is a dictionary mapping object ids to 2-tuples
223 # that contain the Unpickler memo key and the object being memoized.
224 # The memo key is written to the pickle and will become
Jeremy Hylton3422c992003-01-24 19:29:52 +0000225 # the key in the Unpickler's memo. The object is stored in the
Tim Peterse46b73f2003-01-27 21:22:10 +0000226 # Pickler memo so that transient objects are kept alive during
227 # pickling.
Jeremy Hylton3422c992003-01-24 19:29:52 +0000228
Tim Peterse46b73f2003-01-27 21:22:10 +0000229 # The use of the Unpickler memo length as the memo key is just a
230 # convention. The only requirement is that the memo values be unique.
231 # But there appears no advantage to any other scheme, and this
Tim Peterscbd0a322003-01-28 00:24:43 +0000232 # scheme allows the Unpickler memo to be implemented as a plain (but
Tim Peterse46b73f2003-01-27 21:22:10 +0000233 # growable) array, indexed by memo key.
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000234 if self.fast:
235 return
Guido van Rossum9b40e802003-01-30 06:37:41 +0000236 assert id(obj) not in self.memo
Jeremy Hylton3422c992003-01-24 19:29:52 +0000237 memo_len = len(self.memo)
238 self.write(self.put(memo_len))
Tim Peters518df0d2003-01-28 01:00:38 +0000239 self.memo[id(obj)] = memo_len, obj
Jeremy Hylton3422c992003-01-24 19:29:52 +0000240
Tim Petersbb38e302003-01-27 21:25:41 +0000241 # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000242 def put(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000243 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000244 if i < 256:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000245 return BINPUT + chr(i)
246 else:
247 return LONG_BINPUT + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000248
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000249 return PUT + `i` + '\n'
Guido van Rossuma48061a1995-01-10 00:31:14 +0000250
Tim Petersbb38e302003-01-27 21:25:41 +0000251 # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000252 def get(self, i, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000253 if self.bin:
Tim Petersc32d8242001-04-10 02:48:53 +0000254 if i < 256:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000255 return BINGET + chr(i)
256 else:
257 return LONG_BINGET + pack("<i", i)
Guido van Rossuma48061a1995-01-10 00:31:14 +0000258
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000259 return GET + `i` + '\n'
Tim Peters2344fae2001-01-15 00:50:52 +0000260
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000261 def save(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000262 # Check for persistent id (defined by a subclass)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000263 pid = self.persistent_id(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000264 if pid:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000265 self.save_pers(pid)
266 return
Guido van Rossuma48061a1995-01-10 00:31:14 +0000267
Guido van Rossumbc64e222003-01-28 16:34:19 +0000268 # Check the memo
269 x = self.memo.get(id(obj))
270 if x:
271 self.write(self.get(x[0]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000272 return
273
Guido van Rossumbc64e222003-01-28 16:34:19 +0000274 # Check the type dispatch table
Guido van Rossum3a41c612003-01-28 15:10:22 +0000275 t = type(obj)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000276 f = self.dispatch.get(t)
277 if f:
278 f(self, obj) # Call unbound method with explicit self
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000279 return
280
Guido van Rossumbc64e222003-01-28 16:34:19 +0000281 # Check for a class with a custom metaclass; treat as regular class
Tim Petersb32a8312003-01-28 00:48:09 +0000282 try:
283 issc = issubclass(t, TypeType)
Guido van Rossumbc64e222003-01-28 16:34:19 +0000284 except TypeError: # t is not a class (old Boost; see SF #502085)
Tim Petersb32a8312003-01-28 00:48:09 +0000285 issc = 0
286 if issc:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000287 self.save_global(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000288 return
289
Guido van Rossumbc64e222003-01-28 16:34:19 +0000290 # Check copy_reg.dispatch_table
291 reduce = dispatch_table.get(t)
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000292 if not reduce:
293 # Check for a __reduce__ method.
294 # Subtle: get the unbound method from the class, so that
295 # protocol 2 can override the default __reduce__ that all
296 # classes inherit from object. This has the added
297 # advantage that the call always has the form reduce(obj)
298 reduce = getattr(t, "__reduce__", None)
299 if self.proto >= 2:
300 # Protocol 2 can do better than the default __reduce__
301 if reduce is object.__reduce__:
302 reduce = None
303 if not reduce:
Guido van Rossum54fb1922003-01-28 18:22:35 +0000304 self.save_newobj(obj)
305 return
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000306 if not reduce:
Guido van Rossumbc64e222003-01-28 16:34:19 +0000307 raise PicklingError("Can't pickle %r object: %r" %
308 (t.__name__, obj))
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000309 rv = reduce(obj)
Tim Petersb32a8312003-01-28 00:48:09 +0000310
Guido van Rossumbc64e222003-01-28 16:34:19 +0000311 # Check for string returned by reduce(), meaning "save as global"
312 if type(rv) is StringType:
313 self.save_global(obj, rv)
Tim Petersb32a8312003-01-28 00:48:09 +0000314 return
315
Guido van Rossumbc64e222003-01-28 16:34:19 +0000316 # Assert that reduce() returned a tuple
317 if type(rv) is not TupleType:
318 raise PicklingError("%s must return string or tuple" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000319
Guido van Rossumbc64e222003-01-28 16:34:19 +0000320 # Assert that it returned a 2-tuple or 3-tuple, and unpack it
321 l = len(rv)
322 if l == 2:
323 func, args = rv
Tim Petersb32a8312003-01-28 00:48:09 +0000324 state = None
Guido van Rossumbc64e222003-01-28 16:34:19 +0000325 elif l == 3:
326 func, args, state = rv
327 else:
328 raise PicklingError("Tuple returned by %s must have "
329 "exactly two or three elements" % reduce)
Tim Petersb32a8312003-01-28 00:48:09 +0000330
Guido van Rossumbc64e222003-01-28 16:34:19 +0000331 # Save the reduce() output and finally memoize the object
Guido van Rossumf7f45172003-01-31 17:17:49 +0000332 self.save_reduce(func, args, state, obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000333
Guido van Rossum3a41c612003-01-28 15:10:22 +0000334 def persistent_id(self, obj):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000335 # This exists so a subclass can override it
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000336 return None
337
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000338 def save_pers(self, pid):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000339 # Save a persistent id reference
Tim Petersbd1cdb92003-01-28 01:03:10 +0000340 if self.bin:
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000341 self.save(pid)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000342 self.write(BINPERSID)
Tim Petersbd1cdb92003-01-28 01:03:10 +0000343 else:
344 self.write(PERSID + str(pid) + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000345
Guido van Rossumf7f45172003-01-31 17:17:49 +0000346 def save_reduce(self, func, args, state=None, obj=None):
Guido van Rossumbc64e222003-01-28 16:34:19 +0000347 # This API is be called by some subclasses
348
349 # Assert that args is a tuple or None
350 if not isinstance(args, TupleType):
351 if args is None:
352 # A hack for Jim Fulton's ExtensionClass, now deprecated.
353 # See load_reduce()
354 warnings.warn("__basicnew__ special case is deprecated",
355 DeprecationWarning)
356 else:
357 raise PicklingError(
358 "args from reduce() should be a tuple")
359
360 # Assert that func is callable
361 if not callable(func):
362 raise PicklingError("func from reduce should be callable")
363
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000364 save = self.save
Guido van Rossumbc64e222003-01-28 16:34:19 +0000365 write = self.write
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000366
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000367 # Protocol 2 special case: if func's name is __newobj__, use NEWOBJ
368 if self.proto >= 2 and getattr(func, "__name__", "") == "__newobj__":
369 # A __reduce__ implementation can direct protocol 2 to
370 # use the more efficient NEWOBJ opcode, while still
371 # allowing protocol 0 and 1 to work normally. For this to
372 # work, the function returned by __reduce__ should be
373 # called __newobj__, and its first argument should be a
374 # new-style class. The implementation for __newobj__
375 # should be as follows, although pickle has no way to
376 # verify this:
377 #
378 # def __newobj__(cls, *args):
379 # return cls.__new__(cls, *args)
380 #
381 # Protocols 0 and 1 will pickle a reference to __newobj__,
382 # while protocol 2 (and above) will pickle a reference to
383 # cls, the remaining args tuple, and the NEWOBJ code,
384 # which calls cls.__new__(cls, *args) at unpickling time
385 # (see load_newobj below). If __reduce__ returns a
386 # three-tuple, the state from the third tuple item will be
387 # pickled regardless of the protocol, calling __setstate__
388 # at unpickling time (see load_build below).
389 #
390 # Note that no standard __newobj__ implementation exists;
391 # you have to provide your own. This is to enforce
392 # compatibility with Python 2.2 (pickles written using
393 # protocol 0 or 1 in Python 2.3 should be unpicklable by
394 # Python 2.2).
395 cls = args[0]
396 if not hasattr(cls, "__new__"):
397 raise PicklingError(
398 "args[0] from __newobj__ args has no __new__")
Guido van Rossumf7f45172003-01-31 17:17:49 +0000399 if obj is not None and cls is not obj.__class__:
400 raise PicklingError(
401 "args[0] from __newobj__ args has the wrong class")
Guido van Rossumd053b4b2003-01-31 16:51:45 +0000402 args = args[1:]
403 save(cls)
404 save(args)
405 write(NEWOBJ)
406 else:
407 save(func)
408 save(args)
409 write(REDUCE)
Tim Peters2344fae2001-01-15 00:50:52 +0000410
Guido van Rossumf7f45172003-01-31 17:17:49 +0000411 if obj is not None:
412 self.memoize(obj)
413
Tim Petersc32d8242001-04-10 02:48:53 +0000414 if state is not None:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000415 save(state)
416 write(BUILD)
417
Guido van Rossum54fb1922003-01-28 18:22:35 +0000418 def save_newobj(self, obj):
419 # Save a new-style class instance, using protocol 2.
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000420 assert self.proto >= 2 # This only works for protocol 2
Guido van Rossum54fb1922003-01-28 18:22:35 +0000421 t = type(obj)
Guido van Rossum54fb1922003-01-28 18:22:35 +0000422 getnewargs = getattr(obj, "__getnewargs__", None)
423 if getnewargs:
Neal Norwitzd1740682003-01-31 04:04:23 +0000424 args = getnewargs() # This better not reference obj
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000425 else:
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000426 args = ()
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000427
428 save = self.save
429 write = self.write
430
Guido van Rossum9b40e802003-01-30 06:37:41 +0000431 self.save(t)
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000432 save(args)
433 write(NEWOBJ)
Guido van Rossum54fb1922003-01-28 18:22:35 +0000434 self.memoize(obj)
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000435
436 if isinstance(obj, list):
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000437 n = len(obj)
438 if n > 1:
439 write(MARK)
440 for x in obj:
441 save(x)
442 write(APPENDS)
443 elif n == 1:
444 save(obj[0])
445 write(APPEND)
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000446 elif isinstance(obj, dict):
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000447 n = len(obj)
448 if n > 1:
449 write(MARK)
450 for k, v in obj.iteritems():
451 save(k)
452 save(v)
453 write(SETITEMS)
454 elif n == 1:
455 k, v = obj.items()[0]
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000456 save(k)
457 save(v)
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000458 write(SETITEM)
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000459
Guido van Rossum54fb1922003-01-28 18:22:35 +0000460 getstate = getattr(obj, "__getstate__", None)
Guido van Rossum45486172003-01-30 05:39:04 +0000461
Guido van Rossum54fb1922003-01-28 18:22:35 +0000462 if getstate:
Guido van Rossum4fba2202003-01-30 05:41:19 +0000463 # A class may define both __getstate__ and __getnewargs__.
464 # If they are the same function, we ignore __getstate__.
465 # This is for the benefit of protocols 0 and 1, which don't
466 # use __getnewargs__. Note that the only way to make them
467 # the same function is something like this:
468 #
469 # class C(object):
470 # def __getstate__(self):
471 # return ...
472 # __getnewargs__ = __getstate__
473 #
474 # No tricks are needed to ignore __setstate__; it simply
475 # won't be called when we don't generate BUILD.
476 # Also note that when __getnewargs__ and __getstate__ are
477 # the same function, we don't do the default thing of
478 # looking for __dict__ and slots either -- it is assumed
479 # that __getnewargs__ returns all the state there is
480 # (which should be a safe assumption since __getstate__
481 # returns the *same* state).
482 if getstate == getnewargs:
483 return
484
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000485 try:
486 state = getstate()
487 except TypeError, err:
488 # XXX Catch generic exception caused by __slots__
489 if str(err) != ("a class that defines __slots__ "
490 "without defining __getstate__ "
491 "cannot be pickled"):
492 print repr(str(err))
493 raise # Not that specific exception
494 getstate = None
Guido van Rossum4fba2202003-01-30 05:41:19 +0000495
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000496 if not getstate:
Guido van Rossum54fb1922003-01-28 18:22:35 +0000497 state = getattr(obj, "__dict__", None)
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000498 if not state:
499 state = None
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000500 # If there are slots, the state becomes a tuple of two
501 # items: the first item the regular __dict__ or None, and
502 # the second a dict mapping slot names to slot values
503 names = _slotnames(t)
504 if names:
505 slots = {}
506 nil = []
507 for name in names:
508 value = getattr(obj, name, nil)
509 if value is not nil:
510 slots[name] = value
511 if slots:
512 state = (state, slots)
513
Guido van Rossum54fb1922003-01-28 18:22:35 +0000514 if state is not None:
Guido van Rossum3d8c01b2003-01-28 19:48:18 +0000515 save(state)
516 write(BUILD)
Guido van Rossum54fb1922003-01-28 18:22:35 +0000517
Guido van Rossumbc64e222003-01-28 16:34:19 +0000518 # Methods below this point are dispatched through the dispatch table
519
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000520 dispatch = {}
521
Guido van Rossum3a41c612003-01-28 15:10:22 +0000522 def save_none(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000523 self.write(NONE)
524 dispatch[NoneType] = save_none
525
Guido van Rossum3a41c612003-01-28 15:10:22 +0000526 def save_bool(self, obj):
Guido van Rossum7d97d312003-01-28 04:25:27 +0000527 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000528 self.write(obj and NEWTRUE or NEWFALSE)
Guido van Rossum7d97d312003-01-28 04:25:27 +0000529 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000530 self.write(obj and TRUE or FALSE)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000531 dispatch[bool] = save_bool
532
Guido van Rossum3a41c612003-01-28 15:10:22 +0000533 def save_int(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000534 if self.bin:
Tim Peters44714002001-04-10 05:02:52 +0000535 # If the int is small enough to fit in a signed 4-byte 2's-comp
536 # format, we can store it more efficiently than the general
537 # case.
Guido van Rossum5c938d02003-01-28 03:03:08 +0000538 # First one- and two-byte unsigned ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000539 if obj >= 0:
540 if obj <= 0xff:
541 self.write(BININT1 + chr(obj))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000542 return
Guido van Rossum3a41c612003-01-28 15:10:22 +0000543 if obj <= 0xffff:
Guido van Rossumba884f32003-01-29 20:14:23 +0000544 self.write("%c%c%c" % (BININT2, obj&0xff, obj>>8))
Guido van Rossum5c938d02003-01-28 03:03:08 +0000545 return
546 # Next check for 4-byte signed ints:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000547 high_bits = obj >> 31 # note that Python shift sign-extends
Tim Petersd95c2df2003-01-28 03:41:54 +0000548 if high_bits == 0 or high_bits == -1:
Tim Peters44714002001-04-10 05:02:52 +0000549 # All high bits are copies of bit 2**31, so the value
550 # fits in a 4-byte signed int.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000551 self.write(BININT + pack("<i", obj))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000552 return
Tim Peters44714002001-04-10 05:02:52 +0000553 # Text pickle, or int too big to fit in signed 4-byte format.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000554 self.write(INT + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000555 dispatch[IntType] = save_int
556
Guido van Rossum3a41c612003-01-28 15:10:22 +0000557 def save_long(self, obj, pack=struct.pack):
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000558 if self.proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000559 bytes = encode_long(obj)
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000560 n = len(bytes)
561 if n < 256:
562 self.write(LONG1 + chr(n) + bytes)
563 else:
564 self.write(LONG4 + pack("<i", n) + bytes)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000565 self.write(LONG + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000566 dispatch[LongType] = save_long
567
Guido van Rossum3a41c612003-01-28 15:10:22 +0000568 def save_float(self, obj, pack=struct.pack):
Guido van Rossumd3703791998-10-22 20:15:36 +0000569 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000570 self.write(BINFLOAT + pack('>d', obj))
Guido van Rossumd3703791998-10-22 20:15:36 +0000571 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000572 self.write(FLOAT + `obj` + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000573 dispatch[FloatType] = save_float
574
Guido van Rossum3a41c612003-01-28 15:10:22 +0000575 def save_string(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000576 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000577 n = len(obj)
Tim Petersbbf63cd2003-01-27 21:15:36 +0000578 if n < 256:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000579 self.write(SHORT_BINSTRING + chr(n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000580 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000581 self.write(BINSTRING + pack("<i", n) + obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000582 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000583 self.write(STRING + `obj` + '\n')
584 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000585 dispatch[StringType] = save_string
586
Guido van Rossum3a41c612003-01-28 15:10:22 +0000587 def save_unicode(self, obj, pack=struct.pack):
Tim Petersc32d8242001-04-10 02:48:53 +0000588 if self.bin:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000589 encoding = obj.encode('utf-8')
Tim Petersbbf63cd2003-01-27 21:15:36 +0000590 n = len(encoding)
Guido van Rossum5c938d02003-01-28 03:03:08 +0000591 self.write(BINUNICODE + pack("<i", n) + encoding)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000592 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000593 obj = obj.replace("\\", "\\u005c")
594 obj = obj.replace("\n", "\\u000a")
595 self.write(UNICODE + obj.encode('raw-unicode-escape') + '\n')
596 self.memoize(obj)
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +0000597 dispatch[UnicodeType] = save_unicode
598
Guido van Rossum31584cb2001-01-22 14:53:29 +0000599 if StringType == UnicodeType:
600 # This is true for Jython
Guido van Rossum3a41c612003-01-28 15:10:22 +0000601 def save_string(self, obj, pack=struct.pack):
602 unicode = obj.isunicode()
Guido van Rossum31584cb2001-01-22 14:53:29 +0000603
Tim Petersc32d8242001-04-10 02:48:53 +0000604 if self.bin:
Guido van Rossum31584cb2001-01-22 14:53:29 +0000605 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000606 obj = obj.encode("utf-8")
607 l = len(obj)
Tim Petersc32d8242001-04-10 02:48:53 +0000608 if l < 256 and not unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000609 self.write(SHORT_BINSTRING + chr(l) + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000610 else:
Guido van Rossum5c938d02003-01-28 03:03:08 +0000611 s = pack("<i", l)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000612 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000613 self.write(BINUNICODE + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000614 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000615 self.write(BINSTRING + s + obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000616 else:
Tim Peters658cba62001-02-09 20:06:00 +0000617 if unicode:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000618 obj = obj.replace("\\", "\\u005c")
619 obj = obj.replace("\n", "\\u000a")
620 obj = obj.encode('raw-unicode-escape')
621 self.write(UNICODE + obj + '\n')
Guido van Rossum31584cb2001-01-22 14:53:29 +0000622 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000623 self.write(STRING + `obj` + '\n')
624 self.memoize(obj)
Guido van Rossum31584cb2001-01-22 14:53:29 +0000625 dispatch[StringType] = save_string
Tim Peters658cba62001-02-09 20:06:00 +0000626
Guido van Rossum3a41c612003-01-28 15:10:22 +0000627 def save_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000628 write = self.write
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000629 proto = self.proto
630
Guido van Rossum3a41c612003-01-28 15:10:22 +0000631 n = len(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000632 if n == 0 and proto:
633 write(EMPTY_TUPLE)
634 return
635
636 save = self.save
637 memo = self.memo
638 if n <= 3 and proto >= 2:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000639 for element in obj:
Tim Petersd97da802003-01-28 05:48:29 +0000640 save(element)
641 # Subtle. Same as in the big comment below.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000642 if id(obj) in memo:
643 get = self.get(memo[id(obj)][0])
Tim Petersd97da802003-01-28 05:48:29 +0000644 write(POP * n + get)
645 else:
646 write(_tuplesize2code[n])
Guido van Rossum3a41c612003-01-28 15:10:22 +0000647 self.memoize(obj)
Tim Petersd97da802003-01-28 05:48:29 +0000648 return
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000649
Tim Petersff57bff2003-01-28 05:34:53 +0000650 # proto 0, or proto 1 and tuple isn't empty, or proto > 1 and tuple
651 # has more than 3 elements.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000652 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000653 for element in obj:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000654 save(element)
655
Guido van Rossum3a41c612003-01-28 15:10:22 +0000656 if n and id(obj) in memo:
Tim Petersf558da02003-01-28 02:09:55 +0000657 # Subtle. d was not in memo when we entered save_tuple(), so
658 # the process of saving the tuple's elements must have saved
659 # the tuple itself: the tuple is recursive. The proper action
660 # now is to throw away everything we put on the stack, and
661 # simply GET the tuple (it's already constructed). This check
662 # could have been done in the "for element" loop instead, but
663 # recursive tuples are a rare thing.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000664 get = self.get(memo[id(obj)][0])
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000665 if proto:
Tim Petersf558da02003-01-28 02:09:55 +0000666 write(POP_MARK + get)
667 else: # proto 0 -- POP_MARK not available
Tim Petersd97da802003-01-28 05:48:29 +0000668 write(POP * (n+1) + get)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000669 return
670
Guido van Rossum44f0ea52003-01-28 04:14:51 +0000671 # No recursion (including the empty-tuple case for protocol 0).
Tim Peters518df0d2003-01-28 01:00:38 +0000672 self.write(TUPLE)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000673 if obj: # No need to memoize empty tuple
674 self.memoize(obj)
Jeremy Hylton3422c992003-01-24 19:29:52 +0000675
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000676 dispatch[TupleType] = save_tuple
677
Tim Petersa6ae9a22003-01-28 16:58:41 +0000678 # save_empty_tuple() isn't used by anything in Python 2.3. However, I
679 # found a Pickler subclass in Zope3 that calls it, so it's not harmless
680 # to remove it.
Guido van Rossum3a41c612003-01-28 15:10:22 +0000681 def save_empty_tuple(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000682 self.write(EMPTY_TUPLE)
683
Guido van Rossum3a41c612003-01-28 15:10:22 +0000684 def save_list(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000685 write = self.write
686 save = self.save
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000687
Tim Petersc32d8242001-04-10 02:48:53 +0000688 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000689 write(EMPTY_LIST)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000690 self.memoize(obj)
691 n = len(obj)
Tim Peters21c18f02003-01-28 01:15:46 +0000692 if n > 1:
693 write(MARK)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000694 for element in obj:
Tim Peters21c18f02003-01-28 01:15:46 +0000695 save(element)
696 write(APPENDS)
697 elif n:
698 assert n == 1
Guido van Rossum3a41c612003-01-28 15:10:22 +0000699 save(obj[0])
Tim Peters21c18f02003-01-28 01:15:46 +0000700 write(APPEND)
701 # else the list is empty, and we're already done
702
703 else: # proto 0 -- can't use EMPTY_LIST or APPENDS
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000704 write(MARK + LIST)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000705 self.memoize(obj)
706 for element in obj:
Tim Peters21c18f02003-01-28 01:15:46 +0000707 save(element)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000708 write(APPEND)
709
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000710 dispatch[ListType] = save_list
711
Guido van Rossum3a41c612003-01-28 15:10:22 +0000712 def save_dict(self, obj):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000713 write = self.write
714 save = self.save
Guido van Rossum3a41c612003-01-28 15:10:22 +0000715 items = obj.iteritems()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000716
Tim Petersc32d8242001-04-10 02:48:53 +0000717 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000718 write(EMPTY_DICT)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000719 self.memoize(obj)
720 if len(obj) > 1:
Tim Peters064567e2003-01-28 01:34:43 +0000721 write(MARK)
722 for key, value in items:
723 save(key)
724 save(value)
725 write(SETITEMS)
726 return
Tim Peters82ca59e2003-01-28 16:47:59 +0000727 # else (dict is empty or a singleton), fall through to the
728 # SETITEM code at the end
Tim Peters064567e2003-01-28 01:34:43 +0000729 else: # proto 0 -- can't use EMPTY_DICT or SETITEMS
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000730 write(MARK + DICT)
Guido van Rossum3a41c612003-01-28 15:10:22 +0000731 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000732
Guido van Rossum3a41c612003-01-28 15:10:22 +0000733 # proto 0 or len(obj) < 2
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000734 for key, value in items:
735 save(key)
736 save(value)
Tim Peters064567e2003-01-28 01:34:43 +0000737 write(SETITEM)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000738
739 dispatch[DictionaryType] = save_dict
Jeremy Hylton2b9d0291998-05-27 22:38:22 +0000740 if not PyStringMap is None:
741 dispatch[PyStringMap] = save_dict
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000742
Guido van Rossum3a41c612003-01-28 15:10:22 +0000743 def save_inst(self, obj):
744 cls = obj.__class__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000745
746 memo = self.memo
747 write = self.write
748 save = self.save
749
Guido van Rossum3a41c612003-01-28 15:10:22 +0000750 if hasattr(obj, '__getinitargs__'):
751 args = obj.__getinitargs__()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000752 len(args) # XXX Assert it's a sequence
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000753 _keep_alive(args, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000754 else:
755 args = ()
756
757 write(MARK)
758
Tim Petersc32d8242001-04-10 02:48:53 +0000759 if self.bin:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000760 save(cls)
Tim Peters3b769832003-01-28 03:51:36 +0000761 for arg in args:
762 save(arg)
763 write(OBJ)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000764 else:
Tim Peters3b769832003-01-28 03:51:36 +0000765 for arg in args:
766 save(arg)
767 write(INST + cls.__module__ + '\n' + cls.__name__ + '\n')
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000768
Guido van Rossum3a41c612003-01-28 15:10:22 +0000769 self.memoize(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000770
771 try:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000772 getstate = obj.__getstate__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000773 except AttributeError:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000774 stuff = obj.__dict__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000775 else:
776 stuff = getstate()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000777 _keep_alive(stuff, memo)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000778 save(stuff)
779 write(BUILD)
Tim Peters3b769832003-01-28 03:51:36 +0000780
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000781 dispatch[InstanceType] = save_inst
782
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000783 def save_global(self, obj, name=None, pack=struct.pack):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000784 write = self.write
785 memo = self.memo
786
Tim Petersc32d8242001-04-10 02:48:53 +0000787 if name is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000788 name = obj.__name__
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000789
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000790 module = getattr(obj, "__module__", None)
791 if module is None:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000792 module = whichmodule(obj, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000793
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000794 try:
795 __import__(module)
796 mod = sys.modules[module]
797 klass = getattr(mod, name)
798 except (ImportError, KeyError, AttributeError):
799 raise PicklingError(
800 "Can't pickle %r: it's not found as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000801 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000802 else:
Guido van Rossum3a41c612003-01-28 15:10:22 +0000803 if klass is not obj:
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000804 raise PicklingError(
805 "Can't pickle %r: it's not the same object as %s.%s" %
Guido van Rossum3a41c612003-01-28 15:10:22 +0000806 (obj, module, name))
Guido van Rossumb0a98e92001-08-17 18:49:52 +0000807
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000808 if self.proto >= 2:
809 code = extension_registry.get((module, name))
810 if code:
811 assert code > 0
812 if code <= 0xff:
813 write(EXT1 + chr(code))
814 elif code <= 0xffff:
Guido van Rossumba884f32003-01-29 20:14:23 +0000815 write("%c%c%c" % (EXT2, code&0xff, code>>8))
Guido van Rossum255f3ee2003-01-29 06:14:11 +0000816 else:
817 write(EXT4 + pack("<i", code))
818 return
819
Tim Peters518df0d2003-01-28 01:00:38 +0000820 write(GLOBAL + module + '\n' + name + '\n')
Guido van Rossum3a41c612003-01-28 15:10:22 +0000821 self.memoize(obj)
Tim Peters3b769832003-01-28 03:51:36 +0000822
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000823 dispatch[ClassType] = save_global
824 dispatch[FunctionType] = save_global
825 dispatch[BuiltinFunctionType] = save_global
Tim Peters6d6c1a32001-08-02 04:15:00 +0000826 dispatch[TypeType] = save_global
Guido van Rossum0c891ce1995-03-14 15:09:05 +0000827
Guido van Rossum1be31752003-01-28 15:19:53 +0000828# Pickling helpers
Guido van Rossuma48061a1995-01-10 00:31:14 +0000829
Guido van Rossumac5b5d22003-01-28 22:01:16 +0000830def _slotnames(cls):
831 """Return a list of slot names for a given class.
832
833 This needs to find slots defined by the class and its bases, so we
834 can't simply return the __slots__ attribute. We must walk down
835 the Method Resolution Order and concatenate the __slots__ of each
836 class found there. (This assumes classes don't modify their
837 __slots__ attribute to misrepresent their slots after the class is
838 defined.)
839 """
840 if not hasattr(cls, "__slots__"):
841 return []
842 names = []
843 for c in cls.__mro__:
844 if "__slots__" in c.__dict__:
845 names += list(c.__dict__["__slots__"])
846 return names
847
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000848def _keep_alive(x, memo):
849 """Keeps a reference to the object x in the memo.
850
851 Because we remember objects by their id, we have
852 to assure that possibly temporary objects are kept
853 alive by referencing them.
854 We store a reference at the id of the memo, which should
855 normally not be used unless someone tries to deepcopy
856 the memo itself...
857 """
858 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000859 memo[id(memo)].append(x)
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000860 except KeyError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000861 # aha, this is the first one :-)
862 memo[id(memo)]=[x]
Guido van Rossum5ed5c4c1997-09-03 00:23:54 +0000863
864
Tim Petersc0c12b52003-01-29 00:56:17 +0000865# A cache for whichmodule(), mapping a function object to the name of
866# the module in which the function was found.
867
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000868classmap = {} # called classmap for backwards compatibility
Guido van Rossuma48061a1995-01-10 00:31:14 +0000869
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000870def whichmodule(func, funcname):
871 """Figure out the module in which a function occurs.
Guido van Rossuma48061a1995-01-10 00:31:14 +0000872
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000873 Search sys.modules for the module.
874 Cache in classmap.
875 Return a module name.
Tim Petersc0c12b52003-01-29 00:56:17 +0000876 If the function cannot be found, return "__main__".
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000877 """
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +0000878 # Python functions should always get an __module__ from their globals.
879 mod = getattr(func, "__module__", None)
880 if mod is not None:
881 return mod
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000882 if func in classmap:
883 return classmap[func]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000884
885 for name, module in sys.modules.items():
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000886 if module is None:
Jeremy Hylton065a5ab2002-09-19 22:57:26 +0000887 continue # skip dummy package entries
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000888 if name != '__main__' and \
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000889 hasattr(module, funcname) and \
890 getattr(module, funcname) is func:
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000891 break
892 else:
893 name = '__main__'
Jeremy Hyltonf0cfdf72002-09-19 23:00:12 +0000894 classmap[func] = name
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000895 return name
Guido van Rossuma48061a1995-01-10 00:31:14 +0000896
897
Guido van Rossum1be31752003-01-28 15:19:53 +0000898# Unpickling machinery
899
Guido van Rossuma48061a1995-01-10 00:31:14 +0000900class Unpickler:
901
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000902 def __init__(self, file):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000903 """This takes a file-like object for reading a pickle data stream.
904
905 This class automatically determines whether the data stream was
906 written in binary mode or not, so it does not need a flag as in
907 the Pickler class factory.
908
909 The file-like object must have two methods, a read() method that
910 takes an integer argument, and a readline() method that requires no
911 arguments. Both methods should return a string. Thus file-like
912 object can be a file object opened for reading, a StringIO object,
913 or any other custom object that meets this interface.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000914 """
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000915 self.readline = file.readline
916 self.read = file.read
917 self.memo = {}
Guido van Rossuma48061a1995-01-10 00:31:14 +0000918
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000919 def load(self):
Guido van Rossum3a41c612003-01-28 15:10:22 +0000920 """Read a pickled object representation from the open file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000921
Guido van Rossum3a41c612003-01-28 15:10:22 +0000922 Return the reconstituted object hierarchy specified in the file.
Raymond Hettingeraef22fb2002-05-29 16:18:42 +0000923 """
Jeremy Hylton20747fa2001-11-09 16:15:04 +0000924 self.mark = object() # any new unique object
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000925 self.stack = []
926 self.append = self.stack.append
927 read = self.read
928 dispatch = self.dispatch
929 try:
930 while 1:
931 key = read(1)
932 dispatch[key](self)
Guido van Rossumff871742000-12-13 18:11:56 +0000933 except _Stop, stopinst:
934 return stopinst.value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000935
Tim Petersc23d18a2003-01-28 01:41:51 +0000936 # Return largest index k such that self.stack[k] is self.mark.
937 # If the stack doesn't contain a mark, eventually raises IndexError.
938 # This could be sped by maintaining another stack, of indices at which
939 # the mark appears. For that matter, the latter stack would suffice,
940 # and we wouldn't need to push mark objects on self.stack at all.
941 # Doing so is probably a good thing, though, since if the pickle is
942 # corrupt (or hostile) we may get a clue from finding self.mark embedded
943 # in unpickled objects.
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000944 def marker(self):
945 stack = self.stack
946 mark = self.mark
947 k = len(stack)-1
948 while stack[k] is not mark: k = k-1
949 return k
950
951 dispatch = {}
952
953 def load_eof(self):
954 raise EOFError
955 dispatch[''] = load_eof
956
Guido van Rossumd6c9e632003-01-28 03:49:52 +0000957 def load_proto(self):
958 proto = ord(self.read(1))
959 if not 0 <= proto <= 2:
960 raise ValueError, "unsupported pickle protocol: %d" % proto
961 dispatch[PROTO] = load_proto
962
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000963 def load_persid(self):
964 pid = self.readline()[:-1]
965 self.append(self.persistent_load(pid))
966 dispatch[PERSID] = load_persid
967
968 def load_binpersid(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000969 pid = self.stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000970 self.append(self.persistent_load(pid))
971 dispatch[BINPERSID] = load_binpersid
972
973 def load_none(self):
974 self.append(None)
975 dispatch[NONE] = load_none
976
Guido van Rossum7d97d312003-01-28 04:25:27 +0000977 def load_false(self):
978 self.append(False)
979 dispatch[NEWFALSE] = load_false
980
981 def load_true(self):
982 self.append(True)
983 dispatch[NEWTRUE] = load_true
984
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000985 def load_int(self):
Tim Peters19ef62d2001-08-28 22:21:18 +0000986 data = self.readline()
Guido van Rossume2763392002-04-05 19:30:08 +0000987 if data == FALSE[1:]:
988 val = False
989 elif data == TRUE[1:]:
990 val = True
991 else:
992 try:
993 val = int(data)
994 except ValueError:
995 val = long(data)
996 self.append(val)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +0000997 dispatch[INT] = load_int
998
999 def load_binint(self):
1000 self.append(mloads('i' + self.read(4)))
1001 dispatch[BININT] = load_binint
1002
1003 def load_binint1(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001004 self.append(ord(self.read(1)))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001005 dispatch[BININT1] = load_binint1
1006
1007 def load_binint2(self):
1008 self.append(mloads('i' + self.read(2) + '\000\000'))
1009 dispatch[BININT2] = load_binint2
Tim Peters2344fae2001-01-15 00:50:52 +00001010
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001011 def load_long(self):
Guido van Rossumff871742000-12-13 18:11:56 +00001012 self.append(long(self.readline()[:-1], 0))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001013 dispatch[LONG] = load_long
1014
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001015 def load_long1(self):
1016 n = ord(self.read(1))
1017 bytes = self.read(n)
1018 return decode_long(bytes)
1019 dispatch[LONG1] = load_long1
1020
1021 def load_long4(self):
1022 n = mloads('i' + self.read(4))
1023 bytes = self.read(n)
1024 return decode_long(bytes)
1025 dispatch[LONG4] = load_long4
1026
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001027 def load_float(self):
Guido van Rossumff871742000-12-13 18:11:56 +00001028 self.append(float(self.readline()[:-1]))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001029 dispatch[FLOAT] = load_float
1030
Guido van Rossumd3703791998-10-22 20:15:36 +00001031 def load_binfloat(self, unpack=struct.unpack):
1032 self.append(unpack('>d', self.read(8))[0])
1033 dispatch[BINFLOAT] = load_binfloat
1034
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001035 def load_string(self):
Jeremy Hyltonbe467e52000-09-15 15:14:51 +00001036 rep = self.readline()[:-1]
Tim Petersad5a7712003-01-28 16:23:33 +00001037 for q in "\"'": # double or single quote
Martin v. Löwis8a8da792002-08-14 07:46:28 +00001038 if rep.startswith(q):
1039 if not rep.endswith(q):
1040 raise ValueError, "insecure string pickle"
1041 rep = rep[len(q):-len(q)]
1042 break
1043 else:
Jeremy Hyltonbe467e52000-09-15 15:14:51 +00001044 raise ValueError, "insecure string pickle"
Martin v. Löwis8a8da792002-08-14 07:46:28 +00001045 self.append(rep.decode("string-escape"))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001046 dispatch[STRING] = load_string
1047
1048 def load_binstring(self):
1049 len = mloads('i' + self.read(4))
1050 self.append(self.read(len))
1051 dispatch[BINSTRING] = load_binstring
1052
Guido van Rossumb5f2f1b2000-03-10 23:20:09 +00001053 def load_unicode(self):
1054 self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
1055 dispatch[UNICODE] = load_unicode
1056
1057 def load_binunicode(self):
1058 len = mloads('i' + self.read(4))
1059 self.append(unicode(self.read(len),'utf-8'))
1060 dispatch[BINUNICODE] = load_binunicode
1061
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001062 def load_short_binstring(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001063 len = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001064 self.append(self.read(len))
1065 dispatch[SHORT_BINSTRING] = load_short_binstring
1066
1067 def load_tuple(self):
1068 k = self.marker()
1069 self.stack[k:] = [tuple(self.stack[k+1:])]
1070 dispatch[TUPLE] = load_tuple
1071
1072 def load_empty_tuple(self):
1073 self.stack.append(())
1074 dispatch[EMPTY_TUPLE] = load_empty_tuple
1075
Guido van Rossum44f0ea52003-01-28 04:14:51 +00001076 def load_tuple1(self):
1077 self.stack[-1] = (self.stack[-1],)
1078 dispatch[TUPLE1] = load_tuple1
1079
1080 def load_tuple2(self):
1081 self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
1082 dispatch[TUPLE2] = load_tuple2
1083
1084 def load_tuple3(self):
1085 self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
1086 dispatch[TUPLE3] = load_tuple3
1087
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001088 def load_empty_list(self):
1089 self.stack.append([])
1090 dispatch[EMPTY_LIST] = load_empty_list
1091
1092 def load_empty_dictionary(self):
1093 self.stack.append({})
1094 dispatch[EMPTY_DICT] = load_empty_dictionary
1095
1096 def load_list(self):
1097 k = self.marker()
1098 self.stack[k:] = [self.stack[k+1:]]
1099 dispatch[LIST] = load_list
1100
1101 def load_dict(self):
1102 k = self.marker()
1103 d = {}
1104 items = self.stack[k+1:]
1105 for i in range(0, len(items), 2):
1106 key = items[i]
1107 value = items[i+1]
1108 d[key] = value
1109 self.stack[k:] = [d]
1110 dispatch[DICT] = load_dict
1111
Tim Petersd01c1e92003-01-30 15:41:46 +00001112 # INST and OBJ differ only in how they get a class object. It's not
1113 # only sensible to do the rest in a common routine, the two routines
1114 # previously diverged and grew different bugs.
1115 # klass is the class to instantiate, and k points to the topmost mark
1116 # object, following which are the arguments for klass.__init__.
1117 def _instantiate(self, klass, k):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001118 args = tuple(self.stack[k+1:])
1119 del self.stack[k:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001120 instantiated = 0
Tim Petersd01c1e92003-01-30 15:41:46 +00001121 if (not args and
1122 type(klass) is ClassType and
1123 not hasattr(klass, "__getinitargs__")):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001124 try:
1125 value = _EmptyClass()
1126 value.__class__ = klass
Guido van Rossumb19e2a31998-04-13 18:08:45 +00001127 instantiated = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001128 except RuntimeError:
1129 # In restricted execution, assignment to inst.__class__ is
1130 # prohibited
1131 pass
1132 if not instantiated:
Guido van Rossum743d17e1998-09-15 20:25:57 +00001133 try:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001134 value = klass(*args)
Guido van Rossum743d17e1998-09-15 20:25:57 +00001135 except TypeError, err:
1136 raise TypeError, "in constructor for %s: %s" % (
1137 klass.__name__, str(err)), sys.exc_info()[2]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001138 self.append(value)
Tim Petersd01c1e92003-01-30 15:41:46 +00001139
1140 def load_inst(self):
1141 module = self.readline()[:-1]
1142 name = self.readline()[:-1]
1143 klass = self.find_class(module, name)
1144 self._instantiate(klass, self.marker())
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001145 dispatch[INST] = load_inst
1146
1147 def load_obj(self):
Tim Petersd01c1e92003-01-30 15:41:46 +00001148 # Stack is ... markobject classobject arg1 arg2 ...
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001149 k = self.marker()
Tim Petersd01c1e92003-01-30 15:41:46 +00001150 klass = self.stack.pop(k+1)
1151 self._instantiate(klass, k)
Tim Peters2344fae2001-01-15 00:50:52 +00001152 dispatch[OBJ] = load_obj
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001153
Guido van Rossum3a41c612003-01-28 15:10:22 +00001154 def load_newobj(self):
1155 args = self.stack.pop()
1156 cls = self.stack[-1]
1157 obj = cls.__new__(cls, *args)
Guido van Rossum533dbcf2003-01-28 17:55:05 +00001158 self.stack[-1] = obj
Guido van Rossum3a41c612003-01-28 15:10:22 +00001159 dispatch[NEWOBJ] = load_newobj
1160
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001161 def load_global(self):
1162 module = self.readline()[:-1]
1163 name = self.readline()[:-1]
1164 klass = self.find_class(module, name)
1165 self.append(klass)
1166 dispatch[GLOBAL] = load_global
1167
Guido van Rossum255f3ee2003-01-29 06:14:11 +00001168 def load_ext1(self):
1169 code = ord(self.read(1))
1170 self.get_extension(code)
1171 dispatch[EXT1] = load_ext1
1172
1173 def load_ext2(self):
1174 code = mloads('i' + self.read(2) + '\000\000')
1175 self.get_extension(code)
1176 dispatch[EXT2] = load_ext2
1177
1178 def load_ext4(self):
1179 code = mloads('i' + self.read(4))
1180 self.get_extension(code)
1181 dispatch[EXT4] = load_ext4
1182
1183 def get_extension(self, code):
1184 nil = []
1185 obj = extension_cache.get(code, nil)
1186 if obj is not nil:
1187 self.append(obj)
1188 return
1189 key = inverted_registry.get(code)
1190 if not key:
1191 raise ValueError("unregistered extension code %d" % code)
1192 obj = self.find_class(*key)
1193 extension_cache[code] = obj
1194 self.append(obj)
1195
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001196 def find_class(self, module, name):
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001197 # Subclasses may override this
Barry Warsawbf4d9592001-11-15 23:42:58 +00001198 __import__(module)
1199 mod = sys.modules[module]
1200 klass = getattr(mod, name)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001201 return klass
1202
1203 def load_reduce(self):
1204 stack = self.stack
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001205 args = stack.pop()
1206 func = stack[-1]
1207 if args is None:
Guido van Rossumbc64e222003-01-28 16:34:19 +00001208 # A hack for Jim Fulton's ExtensionClass, now deprecated
1209 warnings.warn("__basicnew__ special case is deprecated",
Tim Peters8ac14952002-05-23 15:15:30 +00001210 DeprecationWarning)
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001211 value = func.__basicnew__()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001212 else:
Guido van Rossumb26a97a2003-01-28 22:29:13 +00001213 value = func(*args)
1214 stack[-1] = value
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001215 dispatch[REDUCE] = load_reduce
Guido van Rossuma48061a1995-01-10 00:31:14 +00001216
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001217 def load_pop(self):
1218 del self.stack[-1]
1219 dispatch[POP] = load_pop
Guido van Rossum7b5430f1995-03-04 22:25:21 +00001220
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001221 def load_pop_mark(self):
1222 k = self.marker()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001223 del self.stack[k:]
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001224 dispatch[POP_MARK] = load_pop_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001225
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001226 def load_dup(self):
Guido van Rossumb1062fc1998-03-31 17:00:46 +00001227 self.append(self.stack[-1])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001228 dispatch[DUP] = load_dup
Guido van Rossuma48061a1995-01-10 00:31:14 +00001229
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001230 def load_get(self):
1231 self.append(self.memo[self.readline()[:-1]])
1232 dispatch[GET] = load_get
Guido van Rossum78536471996-04-12 13:36:27 +00001233
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001234 def load_binget(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001235 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001236 self.append(self.memo[`i`])
1237 dispatch[BINGET] = load_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001238
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001239 def load_long_binget(self):
1240 i = mloads('i' + self.read(4))
1241 self.append(self.memo[`i`])
1242 dispatch[LONG_BINGET] = load_long_binget
Guido van Rossum78536471996-04-12 13:36:27 +00001243
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001244 def load_put(self):
1245 self.memo[self.readline()[:-1]] = self.stack[-1]
1246 dispatch[PUT] = load_put
Guido van Rossuma48061a1995-01-10 00:31:14 +00001247
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001248 def load_binput(self):
Tim Petersbbf63cd2003-01-27 21:15:36 +00001249 i = ord(self.read(1))
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001250 self.memo[`i`] = self.stack[-1]
1251 dispatch[BINPUT] = load_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001252
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001253 def load_long_binput(self):
1254 i = mloads('i' + self.read(4))
1255 self.memo[`i`] = self.stack[-1]
1256 dispatch[LONG_BINPUT] = load_long_binput
Guido van Rossuma48061a1995-01-10 00:31:14 +00001257
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001258 def load_append(self):
1259 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001260 value = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001261 list = stack[-1]
1262 list.append(value)
1263 dispatch[APPEND] = load_append
Guido van Rossuma48061a1995-01-10 00:31:14 +00001264
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001265 def load_appends(self):
1266 stack = self.stack
1267 mark = self.marker()
1268 list = stack[mark - 1]
Tim Peters209ad952003-01-28 01:44:45 +00001269 list.extend(stack[mark + 1:])
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001270 del stack[mark:]
1271 dispatch[APPENDS] = load_appends
Tim Peters2344fae2001-01-15 00:50:52 +00001272
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001273 def load_setitem(self):
1274 stack = self.stack
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001275 value = stack.pop()
1276 key = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001277 dict = stack[-1]
1278 dict[key] = value
1279 dispatch[SETITEM] = load_setitem
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001280
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001281 def load_setitems(self):
1282 stack = self.stack
1283 mark = self.marker()
1284 dict = stack[mark - 1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001285 for i in range(mark + 1, len(stack), 2):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001286 dict[stack[i]] = stack[i + 1]
Guido van Rossuma48061a1995-01-10 00:31:14 +00001287
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001288 del stack[mark:]
1289 dispatch[SETITEMS] = load_setitems
Guido van Rossuma48061a1995-01-10 00:31:14 +00001290
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001291 def load_build(self):
1292 stack = self.stack
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001293 state = stack.pop()
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001294 inst = stack[-1]
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001295 setstate = getattr(inst, "__setstate__", None)
1296 if setstate:
1297 setstate(state)
1298 return
1299 slotstate = None
1300 if isinstance(state, tuple) and len(state) == 2:
1301 state, slotstate = state
1302 if state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001303 try:
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001304 inst.__dict__.update(state)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001305 except RuntimeError:
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001306 # XXX In restricted execution, the instance's __dict__
1307 # is not accessible. Use the old way of unpickling
1308 # the instance variables. This is a semantic
1309 # difference when unpickling in restricted
1310 # vs. unrestricted modes.
1311 for k, v in state.items():
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001312 setattr(inst, k, v)
Guido van Rossumac5b5d22003-01-28 22:01:16 +00001313 if slotstate:
1314 for k, v in slotstate.items():
1315 setattr(inst, k, v)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001316 dispatch[BUILD] = load_build
Guido van Rossuma48061a1995-01-10 00:31:14 +00001317
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001318 def load_mark(self):
1319 self.append(self.mark)
1320 dispatch[MARK] = load_mark
Guido van Rossuma48061a1995-01-10 00:31:14 +00001321
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001322 def load_stop(self):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +00001323 value = self.stack.pop()
Guido van Rossumff871742000-12-13 18:11:56 +00001324 raise _Stop(value)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001325 dispatch[STOP] = load_stop
Guido van Rossuma48061a1995-01-10 00:31:14 +00001326
Guido van Rossume467be61997-12-05 19:42:42 +00001327# Helper class for load_inst/load_obj
1328
1329class _EmptyClass:
1330 pass
Guido van Rossuma48061a1995-01-10 00:31:14 +00001331
Tim Peters91149822003-01-31 03:43:58 +00001332# Encode/decode longs in linear time.
1333
1334import binascii as _binascii
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001335
1336def encode_long(x):
Tim Peters91149822003-01-31 03:43:58 +00001337 r"""Encode a long to a two's complement little-endian binary string.
Tim Peters4b23f2b2003-01-31 16:43:39 +00001338 Note that 0L is a special case, returning an empty string, to save a
1339 byte in the LONG1 pickling context.
1340
1341 >>> encode_long(0L)
1342 ''
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001343 >>> encode_long(255L)
1344 '\xff\x00'
1345 >>> encode_long(32767L)
1346 '\xff\x7f'
1347 >>> encode_long(-256L)
1348 '\x00\xff'
1349 >>> encode_long(-32768L)
1350 '\x00\x80'
1351 >>> encode_long(-128L)
1352 '\x80'
1353 >>> encode_long(127L)
1354 '\x7f'
1355 >>>
1356 """
Tim Peters91149822003-01-31 03:43:58 +00001357
1358 if x == 0:
Tim Peters4b23f2b2003-01-31 16:43:39 +00001359 return ''
Tim Peters91149822003-01-31 03:43:58 +00001360 if x > 0:
1361 ashex = hex(x)
1362 assert ashex.startswith("0x")
1363 njunkchars = 2 + ashex.endswith('L')
1364 nibbles = len(ashex) - njunkchars
1365 if nibbles & 1:
1366 # need an even # of nibbles for unhexlify
1367 ashex = "0x0" + ashex[2:]
Tim Peters4b23f2b2003-01-31 16:43:39 +00001368 elif int(ashex[2], 16) >= 8:
Tim Peters91149822003-01-31 03:43:58 +00001369 # "looks negative", so need a byte of sign bits
1370 ashex = "0x00" + ashex[2:]
1371 else:
1372 # Build the 256's-complement: (1L << nbytes) + x. The trick is
1373 # to find the number of bytes in linear time (although that should
1374 # really be a constant-time task).
1375 ashex = hex(-x)
1376 assert ashex.startswith("0x")
1377 njunkchars = 2 + ashex.endswith('L')
1378 nibbles = len(ashex) - njunkchars
1379 if nibbles & 1:
1380 # need an even # of nibbles for unhexlify
1381 nibbles += 1
Tim Peters4b23f2b2003-01-31 16:43:39 +00001382 nbits = nibbles * 4
1383 x += 1L << nbits
Tim Peters91149822003-01-31 03:43:58 +00001384 assert x > 0
1385 ashex = hex(x)
Tim Peters4b23f2b2003-01-31 16:43:39 +00001386 if x >> (nbits - 1) == 0:
Tim Peters91149822003-01-31 03:43:58 +00001387 # "looks positive", so need a byte of sign bits
1388 ashex = "0xff" + x[2:]
1389
1390 if ashex.endswith('L'):
1391 ashex = ashex[2:-1]
1392 else:
1393 ashex = ashex[2:]
1394 assert len(ashex) & 1 == 0
1395 binary = _binascii.unhexlify(ashex)
1396 return binary[::-1]
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001397
1398def decode_long(data):
1399 r"""Decode a long from a two's complement little-endian binary string.
Tim Peters4b23f2b2003-01-31 16:43:39 +00001400
1401 >>> decode_long('')
1402 0L
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001403 >>> decode_long("\xff\x00")
1404 255L
1405 >>> decode_long("\xff\x7f")
1406 32767L
1407 >>> decode_long("\x00\xff")
1408 -256L
1409 >>> decode_long("\x00\x80")
1410 -32768L
1411 >>> decode_long("\x80")
1412 -128L
1413 >>> decode_long("\x7f")
1414 127L
1415 """
Tim Peters91149822003-01-31 03:43:58 +00001416
Tim Peters4b23f2b2003-01-31 16:43:39 +00001417 nbytes = len(data)
1418 if nbytes == 0:
1419 return 0L
Tim Peters91149822003-01-31 03:43:58 +00001420 ashex = _binascii.hexlify(data[::-1])
1421 n = long(ashex, 16)
1422 if data[-1] >= '\x80':
Tim Peters4b23f2b2003-01-31 16:43:39 +00001423 n -= 1L << (nbytes * 8)
Tim Peters91149822003-01-31 03:43:58 +00001424 return n
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001425
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001426# Shorthands
1427
Jeremy Hyltonabe2c622001-10-15 21:29:28 +00001428try:
1429 from cStringIO import StringIO
1430except ImportError:
1431 from StringIO import StringIO
Guido van Rossumc7c5e691996-07-22 22:26:07 +00001432
Guido van Rossum3a41c612003-01-28 15:10:22 +00001433def dump(obj, file, proto=1):
1434 Pickler(file, proto).dump(obj)
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001435
Guido van Rossum3a41c612003-01-28 15:10:22 +00001436def dumps(obj, proto=1):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001437 file = StringIO()
Guido van Rossum3a41c612003-01-28 15:10:22 +00001438 Pickler(file, proto).dump(obj)
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001439 return file.getvalue()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001440
1441def load(file):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001442 return Unpickler(file).load()
Guido van Rossum0c891ce1995-03-14 15:09:05 +00001443
1444def loads(str):
Guido van Rossumb72cf2d1997-04-09 17:32:51 +00001445 file = StringIO(str)
1446 return Unpickler(file).load()
Guido van Rossumd6c9e632003-01-28 03:49:52 +00001447
1448# Doctest
1449
1450def _test():
1451 import doctest
1452 return doctest.testmod()
1453
1454if __name__ == "__main__":
1455 _test()