Guido van Rossum | 54f22ed | 2000-02-04 15:10:34 +0000 | [diff] [blame] | 1 | """Create portable serialized representations of Python objects. |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 2 | |
Alexandre Vassalotti | f7fa63d | 2008-05-11 08:55:36 +0000 | [diff] [blame] | 3 | See module copyreg for a mechanism for registering custom picklers. |
Tim Peters | 22a449a | 2003-01-27 20:16:36 +0000 | [diff] [blame] | 4 | See module pickletools source for extensive comments. |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 5 | |
Guido van Rossum | e467be6 | 1997-12-05 19:42:42 +0000 | [diff] [blame] | 6 | Classes: |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 7 | |
Guido van Rossum | e467be6 | 1997-12-05 19:42:42 +0000 | [diff] [blame] | 8 | Pickler |
| 9 | Unpickler |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 10 | |
Guido van Rossum | e467be6 | 1997-12-05 19:42:42 +0000 | [diff] [blame] | 11 | Functions: |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 12 | |
Guido van Rossum | e467be6 | 1997-12-05 19:42:42 +0000 | [diff] [blame] | 13 | dump(object, file) |
| 14 | dumps(object) -> string |
| 15 | load(file) -> object |
| 16 | loads(string) -> object |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 17 | |
Guido van Rossum | e467be6 | 1997-12-05 19:42:42 +0000 | [diff] [blame] | 18 | Misc variables: |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 19 | |
Fred Drake | fe82acc | 1998-02-13 03:24:48 +0000 | [diff] [blame] | 20 | __version__ |
Guido van Rossum | e467be6 | 1997-12-05 19:42:42 +0000 | [diff] [blame] | 21 | format_version |
| 22 | compatible_formats |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 23 | |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 24 | """ |
| 25 | |
Victor Stinner | 7fa767e | 2014-03-20 09:16:38 +0100 | [diff] [blame] | 26 | from types import FunctionType |
Alexandre Vassalotti | f7fa63d | 2008-05-11 08:55:36 +0000 | [diff] [blame] | 27 | from copyreg import dispatch_table |
| 28 | from copyreg import _extension_registry, _inverted_registry, _extension_cache |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 29 | from itertools import islice |
Guido van Rossum | d370379 | 1998-10-22 20:15:36 +0000 | [diff] [blame] | 30 | import sys |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 31 | from sys import maxsize |
| 32 | from struct import pack, unpack |
Skip Montanaro | 23bafc6 | 2001-02-18 03:10:09 +0000 | [diff] [blame] | 33 | import re |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 34 | import io |
Walter Dörwald | 42748a8 | 2007-06-12 16:40:17 +0000 | [diff] [blame] | 35 | import codecs |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 36 | import _compat_pickle |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 37 | |
Skip Montanaro | 352674d | 2001-02-07 23:14:30 +0000 | [diff] [blame] | 38 | __all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler", |
| 39 | "Unpickler", "dump", "dumps", "load", "loads"] |
| 40 | |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 41 | # Shortcut for use in isinstance testing |
Alexandre Vassalotti | 8cb02b6 | 2008-05-03 01:42:49 +0000 | [diff] [blame] | 42 | bytes_types = (bytes, bytearray) |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 43 | |
Tim Peters | c0c12b5 | 2003-01-29 00:56:17 +0000 | [diff] [blame] | 44 | # These are purely informational; no code uses these. |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 45 | format_version = "4.0" # File format version we write |
Guido van Rossum | f29d3d6 | 2003-01-27 22:47:53 +0000 | [diff] [blame] | 46 | compatible_formats = ["1.0", # Original protocol 0 |
Guido van Rossum | bc64e22 | 2003-01-28 16:34:19 +0000 | [diff] [blame] | 47 | "1.1", # Protocol 0 with INST added |
Guido van Rossum | f29d3d6 | 2003-01-27 22:47:53 +0000 | [diff] [blame] | 48 | "1.2", # Original protocol 1 |
| 49 | "1.3", # Protocol 1 with BINFLOAT added |
| 50 | "2.0", # Protocol 2 |
Guido van Rossum | f416981 | 2008-03-17 22:56:06 +0000 | [diff] [blame] | 51 | "3.0", # Protocol 3 |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 52 | "4.0", # Protocol 4 |
Guido van Rossum | f29d3d6 | 2003-01-27 22:47:53 +0000 | [diff] [blame] | 53 | ] # Old format versions we can read |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 54 | |
Guido van Rossum | 99603b0 | 2007-07-20 00:22:32 +0000 | [diff] [blame] | 55 | # This is the highest protocol number we know how to read. |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 56 | HIGHEST_PROTOCOL = 4 |
Tim Peters | 8587b3c | 2003-02-13 15:44:41 +0000 | [diff] [blame] | 57 | |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 58 | # The protocol we write by default. May be less than HIGHEST_PROTOCOL. |
Guido van Rossum | f416981 | 2008-03-17 22:56:06 +0000 | [diff] [blame] | 59 | # We intentionally write a protocol that Python 2.x cannot read; |
| 60 | # there are too many issues with that. |
| 61 | DEFAULT_PROTOCOL = 3 |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 62 | |
Raymond Hettinger | aef22fb | 2002-05-29 16:18:42 +0000 | [diff] [blame] | 63 | class PickleError(Exception): |
Neal Norwitz | efbb67b | 2002-05-30 12:12:04 +0000 | [diff] [blame] | 64 | """A common base class for the other pickling exceptions.""" |
Raymond Hettinger | aef22fb | 2002-05-29 16:18:42 +0000 | [diff] [blame] | 65 | pass |
| 66 | |
| 67 | class PicklingError(PickleError): |
| 68 | """This exception is raised when an unpicklable object is passed to the |
| 69 | dump() method. |
| 70 | |
| 71 | """ |
| 72 | pass |
| 73 | |
| 74 | class UnpicklingError(PickleError): |
| 75 | """This exception is raised when there is a problem unpickling an object, |
| 76 | such as a security violation. |
| 77 | |
| 78 | Note that other exceptions may also be raised during unpickling, including |
| 79 | (but not necessarily limited to) AttributeError, EOFError, ImportError, |
| 80 | and IndexError. |
| 81 | |
| 82 | """ |
| 83 | pass |
Guido van Rossum | 7849da8 | 1995-03-09 14:08:35 +0000 | [diff] [blame] | 84 | |
Tim Peters | c0c12b5 | 2003-01-29 00:56:17 +0000 | [diff] [blame] | 85 | # An instance of _Stop is raised by Unpickler.load_stop() in response to |
| 86 | # the STOP opcode, passing the object that is the result of unpickling. |
Guido van Rossum | ff87174 | 2000-12-13 18:11:56 +0000 | [diff] [blame] | 87 | class _Stop(Exception): |
| 88 | def __init__(self, value): |
| 89 | self.value = value |
| 90 | |
Guido van Rossum | 533dbcf | 2003-01-28 17:55:05 +0000 | [diff] [blame] | 91 | # Jython has PyStringMap; it's a dict subclass with string keys |
Jeremy Hylton | 2b9d029 | 1998-05-27 22:38:22 +0000 | [diff] [blame] | 92 | try: |
| 93 | from org.python.core import PyStringMap |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 94 | except ImportError: |
Jeremy Hylton | 2b9d029 | 1998-05-27 22:38:22 +0000 | [diff] [blame] | 95 | PyStringMap = None |
| 96 | |
Tim Peters | 22a449a | 2003-01-27 20:16:36 +0000 | [diff] [blame] | 97 | # Pickle opcodes. See pickletools.py for extensive docs. The listing |
| 98 | # here is in kind-of alphabetical order of 1-character pickle code. |
| 99 | # pickletools groups them by purpose. |
Guido van Rossum | dbb718f | 2001-09-21 19:22:34 +0000 | [diff] [blame] | 100 | |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 101 | MARK = b'(' # push special markobject on stack |
| 102 | STOP = b'.' # every pickle ends with STOP |
| 103 | POP = b'0' # discard topmost stack item |
| 104 | POP_MARK = b'1' # discard stack top through topmost markobject |
| 105 | DUP = b'2' # duplicate top stack item |
| 106 | FLOAT = b'F' # push float object; decimal string argument |
| 107 | INT = b'I' # push integer or bool; decimal string argument |
| 108 | BININT = b'J' # push four-byte signed int |
| 109 | BININT1 = b'K' # push 1-byte unsigned int |
| 110 | LONG = b'L' # push long; decimal string argument |
| 111 | BININT2 = b'M' # push 2-byte unsigned int |
| 112 | NONE = b'N' # push None |
| 113 | PERSID = b'P' # push persistent object; id is taken from string arg |
| 114 | BINPERSID = b'Q' # " " " ; " " " " stack |
| 115 | REDUCE = b'R' # apply callable to argtuple, both on stack |
| 116 | STRING = b'S' # push string; NL-terminated string argument |
| 117 | BINSTRING = b'T' # push string; counted binary string argument |
| 118 | SHORT_BINSTRING= b'U' # " " ; " " " " < 256 bytes |
| 119 | UNICODE = b'V' # push Unicode string; raw-unicode-escaped'd argument |
| 120 | BINUNICODE = b'X' # " " " ; counted UTF-8 string argument |
| 121 | APPEND = b'a' # append stack top to list below it |
| 122 | BUILD = b'b' # call __setstate__ or __dict__.update() |
| 123 | GLOBAL = b'c' # push self.find_class(modname, name); 2 string args |
| 124 | DICT = b'd' # build a dict from stack items |
| 125 | EMPTY_DICT = b'}' # push empty dict |
| 126 | APPENDS = b'e' # extend list on stack by topmost stack slice |
| 127 | GET = b'g' # push item from memo on stack; index is string arg |
| 128 | BINGET = b'h' # " " " " " " ; " " 1-byte arg |
| 129 | INST = b'i' # build & push class instance |
| 130 | LONG_BINGET = b'j' # push item from memo on stack; index is 4-byte arg |
| 131 | LIST = b'l' # build list from topmost stack items |
| 132 | EMPTY_LIST = b']' # push empty list |
| 133 | OBJ = b'o' # build & push class instance |
| 134 | PUT = b'p' # store stack top in memo; index is string arg |
| 135 | BINPUT = b'q' # " " " " " ; " " 1-byte arg |
| 136 | LONG_BINPUT = b'r' # " " " " " ; " " 4-byte arg |
| 137 | SETITEM = b's' # add key+value pair to dict |
| 138 | TUPLE = b't' # build tuple from topmost stack items |
| 139 | EMPTY_TUPLE = b')' # push empty tuple |
| 140 | SETITEMS = b'u' # modify dict by adding topmost key+value pairs |
| 141 | BINFLOAT = b'G' # push float; arg is 8-byte float encoding |
Tim Peters | 22a449a | 2003-01-27 20:16:36 +0000 | [diff] [blame] | 142 | |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 143 | TRUE = b'I01\n' # not an opcode; see INT docs in pickletools.py |
| 144 | FALSE = b'I00\n' # not an opcode; see INT docs in pickletools.py |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 145 | |
Guido van Rossum | 586c9e8 | 2003-01-29 06:16:12 +0000 | [diff] [blame] | 146 | # Protocol 2 |
Guido van Rossum | 5a2d8f5 | 2003-01-27 21:44:25 +0000 | [diff] [blame] | 147 | |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 148 | PROTO = b'\x80' # identify pickle protocol |
| 149 | NEWOBJ = b'\x81' # build object by applying cls.__new__ to argtuple |
| 150 | EXT1 = b'\x82' # push object from extension registry; 1-byte index |
| 151 | EXT2 = b'\x83' # ditto, but 2-byte index |
| 152 | EXT4 = b'\x84' # ditto, but 4-byte index |
| 153 | TUPLE1 = b'\x85' # build 1-tuple from stack top |
| 154 | TUPLE2 = b'\x86' # build 2-tuple from two topmost stack items |
| 155 | TUPLE3 = b'\x87' # build 3-tuple from three topmost stack items |
| 156 | NEWTRUE = b'\x88' # push True |
| 157 | NEWFALSE = b'\x89' # push False |
| 158 | LONG1 = b'\x8a' # push long from < 256 bytes |
| 159 | LONG4 = b'\x8b' # push really big long |
Guido van Rossum | 5a2d8f5 | 2003-01-27 21:44:25 +0000 | [diff] [blame] | 160 | |
Guido van Rossum | 44f0ea5 | 2003-01-28 04:14:51 +0000 | [diff] [blame] | 161 | _tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3] |
| 162 | |
Guido van Rossum | f416981 | 2008-03-17 22:56:06 +0000 | [diff] [blame] | 163 | # Protocol 3 (Python 3.x) |
| 164 | |
| 165 | BINBYTES = b'B' # push bytes; counted binary string argument |
| 166 | SHORT_BINBYTES = b'C' # " " ; " " " " < 256 bytes |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 167 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 168 | # Protocol 4 |
| 169 | SHORT_BINUNICODE = b'\x8c' # push short string; UTF-8 length < 256 bytes |
| 170 | BINUNICODE8 = b'\x8d' # push very long string |
| 171 | BINBYTES8 = b'\x8e' # push very long bytes string |
| 172 | EMPTY_SET = b'\x8f' # push empty set on the stack |
| 173 | ADDITEMS = b'\x90' # modify set by adding topmost stack items |
| 174 | FROZENSET = b'\x91' # build frozenset from topmost stack items |
| 175 | NEWOBJ_EX = b'\x92' # like NEWOBJ but work with keyword only arguments |
| 176 | STACK_GLOBAL = b'\x93' # same as GLOBAL but using names on the stacks |
| 177 | MEMOIZE = b'\x94' # store top of the stack in memo |
| 178 | FRAME = b'\x95' # indicate the beginning of a new frame |
| 179 | |
| 180 | __all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$", x)]) |
| 181 | |
| 182 | |
| 183 | class _Framer: |
| 184 | |
| 185 | _FRAME_SIZE_TARGET = 64 * 1024 |
| 186 | |
| 187 | def __init__(self, file_write): |
| 188 | self.file_write = file_write |
| 189 | self.current_frame = None |
| 190 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 191 | def start_framing(self): |
| 192 | self.current_frame = io.BytesIO() |
| 193 | |
| 194 | def end_framing(self): |
Alexandre Vassalotti | b6a2f2a | 2013-11-23 20:30:03 -0800 | [diff] [blame] | 195 | if self.current_frame and self.current_frame.tell() > 0: |
| 196 | self.commit_frame(force=True) |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 197 | self.current_frame = None |
| 198 | |
Alexandre Vassalotti | b6a2f2a | 2013-11-23 20:30:03 -0800 | [diff] [blame] | 199 | def commit_frame(self, force=False): |
| 200 | if self.current_frame: |
| 201 | f = self.current_frame |
| 202 | if f.tell() >= self._FRAME_SIZE_TARGET or force: |
| 203 | with f.getbuffer() as data: |
| 204 | n = len(data) |
| 205 | write = self.file_write |
| 206 | write(FRAME) |
| 207 | write(pack("<Q", n)) |
| 208 | write(data) |
| 209 | f.seek(0) |
| 210 | f.truncate() |
| 211 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 212 | def write(self, data): |
Alexandre Vassalotti | b6a2f2a | 2013-11-23 20:30:03 -0800 | [diff] [blame] | 213 | if self.current_frame: |
| 214 | return self.current_frame.write(data) |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 215 | else: |
Alexandre Vassalotti | b6a2f2a | 2013-11-23 20:30:03 -0800 | [diff] [blame] | 216 | return self.file_write(data) |
| 217 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 218 | |
| 219 | class _Unframer: |
| 220 | |
| 221 | def __init__(self, file_read, file_readline, file_tell=None): |
| 222 | self.file_read = file_read |
| 223 | self.file_readline = file_readline |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 224 | self.current_frame = None |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 225 | |
| 226 | def read(self, n): |
Alexandre Vassalotti | b6a2f2a | 2013-11-23 20:30:03 -0800 | [diff] [blame] | 227 | if self.current_frame: |
| 228 | data = self.current_frame.read(n) |
| 229 | if not data and n != 0: |
| 230 | self.current_frame = None |
| 231 | return self.file_read(n) |
| 232 | if len(data) < n: |
| 233 | raise UnpicklingError( |
| 234 | "pickle exhausted before end of frame") |
| 235 | return data |
| 236 | else: |
| 237 | return self.file_read(n) |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 238 | |
| 239 | def readline(self): |
Alexandre Vassalotti | b6a2f2a | 2013-11-23 20:30:03 -0800 | [diff] [blame] | 240 | if self.current_frame: |
| 241 | data = self.current_frame.readline() |
| 242 | if not data: |
| 243 | self.current_frame = None |
| 244 | return self.file_readline() |
Serhiy Storchaka | 21d7533 | 2015-01-26 10:37:01 +0200 | [diff] [blame] | 245 | if data[-1] != b'\n'[0]: |
Alexandre Vassalotti | b6a2f2a | 2013-11-23 20:30:03 -0800 | [diff] [blame] | 246 | raise UnpicklingError( |
| 247 | "pickle exhausted before end of frame") |
| 248 | return data |
| 249 | else: |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 250 | return self.file_readline() |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 251 | |
Alexandre Vassalotti | b6a2f2a | 2013-11-23 20:30:03 -0800 | [diff] [blame] | 252 | def load_frame(self, frame_size): |
| 253 | if self.current_frame and self.current_frame.read() != b'': |
| 254 | raise UnpicklingError( |
| 255 | "beginning of a new frame before end of current frame") |
| 256 | self.current_frame = io.BytesIO(self.file_read(frame_size)) |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 257 | |
| 258 | |
| 259 | # Tools used for pickling. |
| 260 | |
Serhiy Storchaka | 58e4134 | 2015-03-31 14:07:24 +0300 | [diff] [blame] | 261 | def _getattribute(obj, name): |
| 262 | for subpath in name.split('.'): |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 263 | if subpath == '<locals>': |
| 264 | raise AttributeError("Can't get local attribute {!r} on {!r}" |
| 265 | .format(name, obj)) |
| 266 | try: |
Serhiy Storchaka | 58e4134 | 2015-03-31 14:07:24 +0300 | [diff] [blame] | 267 | parent = obj |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 268 | obj = getattr(obj, subpath) |
| 269 | except AttributeError: |
| 270 | raise AttributeError("Can't get attribute {!r} on {!r}" |
| 271 | .format(name, obj)) |
Serhiy Storchaka | 58e4134 | 2015-03-31 14:07:24 +0300 | [diff] [blame] | 272 | return obj, parent |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 273 | |
Serhiy Storchaka | 58e4134 | 2015-03-31 14:07:24 +0300 | [diff] [blame] | 274 | def whichmodule(obj, name): |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 275 | """Find the module an object belong to.""" |
| 276 | module_name = getattr(obj, '__module__', None) |
| 277 | if module_name is not None: |
| 278 | return module_name |
Antoine Pitrou | e161849 | 2014-10-04 22:15:27 +0200 | [diff] [blame] | 279 | # Protect the iteration by using a list copy of sys.modules against dynamic |
| 280 | # modules that trigger imports of other modules upon calls to getattr. |
| 281 | for module_name, module in list(sys.modules.items()): |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 282 | if module_name == '__main__' or module is None: |
| 283 | continue |
| 284 | try: |
Serhiy Storchaka | 58e4134 | 2015-03-31 14:07:24 +0300 | [diff] [blame] | 285 | if _getattribute(module, name)[0] is obj: |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 286 | return module_name |
| 287 | except AttributeError: |
| 288 | pass |
| 289 | return '__main__' |
| 290 | |
| 291 | def encode_long(x): |
| 292 | r"""Encode a long to a two's complement little-endian binary string. |
| 293 | Note that 0 is a special case, returning an empty string, to save a |
| 294 | byte in the LONG1 pickling context. |
| 295 | |
| 296 | >>> encode_long(0) |
| 297 | b'' |
| 298 | >>> encode_long(255) |
| 299 | b'\xff\x00' |
| 300 | >>> encode_long(32767) |
| 301 | b'\xff\x7f' |
| 302 | >>> encode_long(-256) |
| 303 | b'\x00\xff' |
| 304 | >>> encode_long(-32768) |
| 305 | b'\x00\x80' |
| 306 | >>> encode_long(-128) |
| 307 | b'\x80' |
| 308 | >>> encode_long(127) |
| 309 | b'\x7f' |
| 310 | >>> |
| 311 | """ |
| 312 | if x == 0: |
| 313 | return b'' |
| 314 | nbytes = (x.bit_length() >> 3) + 1 |
| 315 | result = x.to_bytes(nbytes, byteorder='little', signed=True) |
| 316 | if x < 0 and nbytes > 1: |
| 317 | if result[-1] == 0xff and (result[-2] & 0x80) != 0: |
| 318 | result = result[:-1] |
| 319 | return result |
| 320 | |
| 321 | def decode_long(data): |
| 322 | r"""Decode a long from a two's complement little-endian binary string. |
| 323 | |
| 324 | >>> decode_long(b'') |
| 325 | 0 |
| 326 | >>> decode_long(b"\xff\x00") |
| 327 | 255 |
| 328 | >>> decode_long(b"\xff\x7f") |
| 329 | 32767 |
| 330 | >>> decode_long(b"\x00\xff") |
| 331 | -256 |
| 332 | >>> decode_long(b"\x00\x80") |
| 333 | -32768 |
| 334 | >>> decode_long(b"\x80") |
| 335 | -128 |
| 336 | >>> decode_long(b"\x7f") |
| 337 | 127 |
| 338 | """ |
| 339 | return int.from_bytes(data, byteorder='little', signed=True) |
| 340 | |
Skip Montanaro | 23bafc6 | 2001-02-18 03:10:09 +0000 | [diff] [blame] | 341 | |
Guido van Rossum | 1be3175 | 2003-01-28 15:19:53 +0000 | [diff] [blame] | 342 | # Pickling machinery |
| 343 | |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 344 | class _Pickler: |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 345 | |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 346 | def __init__(self, file, protocol=None, *, fix_imports=True): |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 347 | """This takes a binary file for writing a pickle data stream. |
| 348 | |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 349 | The optional *protocol* argument tells the pickler to use the |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 350 | given protocol; supported protocols are 0, 1, 2, 3 and 4. The |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 351 | default protocol is 3; a backward-incompatible protocol designed |
| 352 | for Python 3. |
Guido van Rossum | f29d3d6 | 2003-01-27 22:47:53 +0000 | [diff] [blame] | 353 | |
Guido van Rossum | 7eff63a | 2003-01-31 19:42:31 +0000 | [diff] [blame] | 354 | Specifying a negative protocol version selects the highest |
Tim Peters | 5bd2a79 | 2003-02-01 16:45:06 +0000 | [diff] [blame] | 355 | protocol version supported. The higher the protocol used, the |
| 356 | more recent the version of Python needed to read the pickle |
| 357 | produced. |
Raymond Hettinger | aef22fb | 2002-05-29 16:18:42 +0000 | [diff] [blame] | 358 | |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 359 | The *file* argument must have a write() method that accepts a |
| 360 | single bytes argument. It can thus be a file object opened for |
Martin Panter | 7462b649 | 2015-11-02 03:37:02 +0000 | [diff] [blame] | 361 | binary writing, an io.BytesIO instance, or any other custom |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 362 | object that meets this interface. |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 363 | |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 364 | If *fix_imports* is True and *protocol* is less than 3, pickle |
| 365 | will try to map the new Python 3 names to the old module names |
| 366 | used in Python 2, so that the pickle data stream is readable |
| 367 | with Python 2. |
Raymond Hettinger | aef22fb | 2002-05-29 16:18:42 +0000 | [diff] [blame] | 368 | """ |
Guido van Rossum | cf117b0 | 2003-02-09 17:19:41 +0000 | [diff] [blame] | 369 | if protocol is None: |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 370 | protocol = DEFAULT_PROTOCOL |
Guido van Rossum | cf117b0 | 2003-02-09 17:19:41 +0000 | [diff] [blame] | 371 | if protocol < 0: |
Tim Peters | 8587b3c | 2003-02-13 15:44:41 +0000 | [diff] [blame] | 372 | protocol = HIGHEST_PROTOCOL |
| 373 | elif not 0 <= protocol <= HIGHEST_PROTOCOL: |
| 374 | raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL) |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 375 | try: |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 376 | self._file_write = file.write |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 377 | except AttributeError: |
| 378 | raise TypeError("file must have a 'write' attribute") |
Alexandre Vassalotti | b6a2f2a | 2013-11-23 20:30:03 -0800 | [diff] [blame] | 379 | self.framer = _Framer(self._file_write) |
| 380 | self.write = self.framer.write |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 381 | self.memo = {} |
Guido van Rossum | cf117b0 | 2003-02-09 17:19:41 +0000 | [diff] [blame] | 382 | self.proto = int(protocol) |
| 383 | self.bin = protocol >= 1 |
Guido van Rossum | 5d9113d | 2003-01-29 17:58:45 +0000 | [diff] [blame] | 384 | self.fast = 0 |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 385 | self.fix_imports = fix_imports and protocol < 3 |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 386 | |
Fred Drake | 7f781c9 | 2002-05-01 20:33:53 +0000 | [diff] [blame] | 387 | def clear_memo(self): |
Raymond Hettinger | aef22fb | 2002-05-29 16:18:42 +0000 | [diff] [blame] | 388 | """Clears the pickler's "memo". |
| 389 | |
| 390 | The memo is the data structure that remembers which objects the |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 391 | pickler has already seen, so that shared or recursive objects |
| 392 | are pickled by reference and not by value. This method is |
| 393 | useful when re-using picklers. |
Raymond Hettinger | aef22fb | 2002-05-29 16:18:42 +0000 | [diff] [blame] | 394 | """ |
Fred Drake | 7f781c9 | 2002-05-01 20:33:53 +0000 | [diff] [blame] | 395 | self.memo.clear() |
| 396 | |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 397 | def dump(self, obj): |
Tim Peters | 5bd2a79 | 2003-02-01 16:45:06 +0000 | [diff] [blame] | 398 | """Write a pickled representation of obj to the open file.""" |
Alexandre Vassalotti | 3cfcab9 | 2008-12-27 09:30:39 +0000 | [diff] [blame] | 399 | # Check whether Pickler was initialized correctly. This is |
| 400 | # only needed to mimic the behavior of _pickle.Pickler.dump(). |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 401 | if not hasattr(self, "_file_write"): |
Alexandre Vassalotti | 3cfcab9 | 2008-12-27 09:30:39 +0000 | [diff] [blame] | 402 | raise PicklingError("Pickler.__init__() was not called by " |
| 403 | "%s.__init__()" % (self.__class__.__name__,)) |
Guido van Rossum | d6c9e63 | 2003-01-28 03:49:52 +0000 | [diff] [blame] | 404 | if self.proto >= 2: |
Alexandre Vassalotti | b6a2f2a | 2013-11-23 20:30:03 -0800 | [diff] [blame] | 405 | self.write(PROTO + pack("<B", self.proto)) |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 406 | if self.proto >= 4: |
Alexandre Vassalotti | b6a2f2a | 2013-11-23 20:30:03 -0800 | [diff] [blame] | 407 | self.framer.start_framing() |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 408 | self.save(obj) |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 409 | self.write(STOP) |
Alexandre Vassalotti | b6a2f2a | 2013-11-23 20:30:03 -0800 | [diff] [blame] | 410 | self.framer.end_framing() |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 411 | |
Jeremy Hylton | 3422c99 | 2003-01-24 19:29:52 +0000 | [diff] [blame] | 412 | def memoize(self, obj): |
| 413 | """Store an object in the memo.""" |
| 414 | |
Tim Peters | e46b73f | 2003-01-27 21:22:10 +0000 | [diff] [blame] | 415 | # The Pickler memo is a dictionary mapping object ids to 2-tuples |
| 416 | # that contain the Unpickler memo key and the object being memoized. |
| 417 | # The memo key is written to the pickle and will become |
Jeremy Hylton | 3422c99 | 2003-01-24 19:29:52 +0000 | [diff] [blame] | 418 | # the key in the Unpickler's memo. The object is stored in the |
Tim Peters | e46b73f | 2003-01-27 21:22:10 +0000 | [diff] [blame] | 419 | # Pickler memo so that transient objects are kept alive during |
| 420 | # pickling. |
Jeremy Hylton | 3422c99 | 2003-01-24 19:29:52 +0000 | [diff] [blame] | 421 | |
Tim Peters | e46b73f | 2003-01-27 21:22:10 +0000 | [diff] [blame] | 422 | # The use of the Unpickler memo length as the memo key is just a |
| 423 | # convention. The only requirement is that the memo values be unique. |
| 424 | # But there appears no advantage to any other scheme, and this |
Tim Peters | cbd0a32 | 2003-01-28 00:24:43 +0000 | [diff] [blame] | 425 | # scheme allows the Unpickler memo to be implemented as a plain (but |
Tim Peters | e46b73f | 2003-01-27 21:22:10 +0000 | [diff] [blame] | 426 | # growable) array, indexed by memo key. |
Guido van Rossum | 5d9113d | 2003-01-29 17:58:45 +0000 | [diff] [blame] | 427 | if self.fast: |
| 428 | return |
Guido van Rossum | 9b40e80 | 2003-01-30 06:37:41 +0000 | [diff] [blame] | 429 | assert id(obj) not in self.memo |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 430 | idx = len(self.memo) |
| 431 | self.write(self.put(idx)) |
| 432 | self.memo[id(obj)] = idx, obj |
Jeremy Hylton | 3422c99 | 2003-01-24 19:29:52 +0000 | [diff] [blame] | 433 | |
Tim Peters | bb38e30 | 2003-01-27 21:25:41 +0000 | [diff] [blame] | 434 | # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i. |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 435 | def put(self, idx): |
| 436 | if self.proto >= 4: |
| 437 | return MEMOIZE |
| 438 | elif self.bin: |
| 439 | if idx < 256: |
| 440 | return BINPUT + pack("<B", idx) |
Guido van Rossum | 5c938d0 | 2003-01-28 03:03:08 +0000 | [diff] [blame] | 441 | else: |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 442 | return LONG_BINPUT + pack("<I", idx) |
| 443 | else: |
| 444 | return PUT + repr(idx).encode("ascii") + b'\n' |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 445 | |
Tim Peters | bb38e30 | 2003-01-27 21:25:41 +0000 | [diff] [blame] | 446 | # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i. |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 447 | def get(self, i): |
Tim Peters | c32d824 | 2001-04-10 02:48:53 +0000 | [diff] [blame] | 448 | if self.bin: |
Tim Peters | c32d824 | 2001-04-10 02:48:53 +0000 | [diff] [blame] | 449 | if i < 256: |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 450 | return BINGET + pack("<B", i) |
Guido van Rossum | 5c938d0 | 2003-01-28 03:03:08 +0000 | [diff] [blame] | 451 | else: |
Antoine Pitrou | bf6ecf9 | 2012-11-24 20:40:21 +0100 | [diff] [blame] | 452 | return LONG_BINGET + pack("<I", i) |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 453 | |
Guido van Rossum | 39478e8 | 2007-08-27 17:23:59 +0000 | [diff] [blame] | 454 | return GET + repr(i).encode("ascii") + b'\n' |
Tim Peters | 2344fae | 2001-01-15 00:50:52 +0000 | [diff] [blame] | 455 | |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 456 | def save(self, obj, save_persistent_id=True): |
Alexandre Vassalotti | b6a2f2a | 2013-11-23 20:30:03 -0800 | [diff] [blame] | 457 | self.framer.commit_frame() |
| 458 | |
Guido van Rossum | bc64e22 | 2003-01-28 16:34:19 +0000 | [diff] [blame] | 459 | # Check for persistent id (defined by a subclass) |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 460 | pid = self.persistent_id(obj) |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 461 | if pid is not None and save_persistent_id: |
Jeremy Hylton | 5e0f4e7 | 2002-11-13 22:01:27 +0000 | [diff] [blame] | 462 | self.save_pers(pid) |
| 463 | return |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 464 | |
Guido van Rossum | bc64e22 | 2003-01-28 16:34:19 +0000 | [diff] [blame] | 465 | # Check the memo |
| 466 | x = self.memo.get(id(obj)) |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 467 | if x is not None: |
Guido van Rossum | bc64e22 | 2003-01-28 16:34:19 +0000 | [diff] [blame] | 468 | self.write(self.get(x[0])) |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 469 | return |
| 470 | |
Guido van Rossum | bc64e22 | 2003-01-28 16:34:19 +0000 | [diff] [blame] | 471 | # Check the type dispatch table |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 472 | t = type(obj) |
Guido van Rossum | bc64e22 | 2003-01-28 16:34:19 +0000 | [diff] [blame] | 473 | f = self.dispatch.get(t) |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 474 | if f is not None: |
Guido van Rossum | bc64e22 | 2003-01-28 16:34:19 +0000 | [diff] [blame] | 475 | f(self, obj) # Call unbound method with explicit self |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 476 | return |
| 477 | |
Antoine Pitrou | 8d3c290 | 2012-03-04 18:31:48 +0100 | [diff] [blame] | 478 | # Check private dispatch table if any, or else copyreg.dispatch_table |
| 479 | reduce = getattr(self, 'dispatch_table', dispatch_table).get(t) |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 480 | if reduce is not None: |
Guido van Rossum | c53f009 | 2003-02-18 22:05:12 +0000 | [diff] [blame] | 481 | rv = reduce(obj) |
| 482 | else: |
Antoine Pitrou | ffd41d9 | 2011-10-04 09:23:04 +0200 | [diff] [blame] | 483 | # Check for a class with a custom metaclass; treat as regular class |
| 484 | try: |
| 485 | issc = issubclass(t, type) |
| 486 | except TypeError: # t is not a class (old Boost; see SF #502085) |
| 487 | issc = False |
| 488 | if issc: |
| 489 | self.save_global(obj) |
| 490 | return |
| 491 | |
Guido van Rossum | c53f009 | 2003-02-18 22:05:12 +0000 | [diff] [blame] | 492 | # Check for a __reduce_ex__ method, fall back to __reduce__ |
| 493 | reduce = getattr(obj, "__reduce_ex__", None) |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 494 | if reduce is not None: |
Guido van Rossum | c53f009 | 2003-02-18 22:05:12 +0000 | [diff] [blame] | 495 | rv = reduce(self.proto) |
| 496 | else: |
| 497 | reduce = getattr(obj, "__reduce__", None) |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 498 | if reduce is not None: |
Guido van Rossum | c53f009 | 2003-02-18 22:05:12 +0000 | [diff] [blame] | 499 | rv = reduce() |
| 500 | else: |
| 501 | raise PicklingError("Can't pickle %r object: %r" % |
| 502 | (t.__name__, obj)) |
Tim Peters | b32a831 | 2003-01-28 00:48:09 +0000 | [diff] [blame] | 503 | |
Guido van Rossum | bc64e22 | 2003-01-28 16:34:19 +0000 | [diff] [blame] | 504 | # Check for string returned by reduce(), meaning "save as global" |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 505 | if isinstance(rv, str): |
Guido van Rossum | bc64e22 | 2003-01-28 16:34:19 +0000 | [diff] [blame] | 506 | self.save_global(obj, rv) |
Tim Peters | b32a831 | 2003-01-28 00:48:09 +0000 | [diff] [blame] | 507 | return |
| 508 | |
Guido van Rossum | bc64e22 | 2003-01-28 16:34:19 +0000 | [diff] [blame] | 509 | # Assert that reduce() returned a tuple |
Guido van Rossum | 1325790 | 2007-06-07 23:15:56 +0000 | [diff] [blame] | 510 | if not isinstance(rv, tuple): |
Guido van Rossum | bc64e22 | 2003-01-28 16:34:19 +0000 | [diff] [blame] | 511 | raise PicklingError("%s must return string or tuple" % reduce) |
Tim Peters | b32a831 | 2003-01-28 00:48:09 +0000 | [diff] [blame] | 512 | |
Guido van Rossum | 25cb7df | 2003-01-31 18:53:21 +0000 | [diff] [blame] | 513 | # Assert that it returned an appropriately sized tuple |
Guido van Rossum | bc64e22 | 2003-01-28 16:34:19 +0000 | [diff] [blame] | 514 | l = len(rv) |
Guido van Rossum | 25cb7df | 2003-01-31 18:53:21 +0000 | [diff] [blame] | 515 | if not (2 <= l <= 5): |
Guido van Rossum | bc64e22 | 2003-01-28 16:34:19 +0000 | [diff] [blame] | 516 | raise PicklingError("Tuple returned by %s must have " |
Guido van Rossum | 25cb7df | 2003-01-31 18:53:21 +0000 | [diff] [blame] | 517 | "two to five elements" % reduce) |
Tim Peters | b32a831 | 2003-01-28 00:48:09 +0000 | [diff] [blame] | 518 | |
Guido van Rossum | bc64e22 | 2003-01-28 16:34:19 +0000 | [diff] [blame] | 519 | # Save the reduce() output and finally memoize the object |
Guido van Rossum | 25cb7df | 2003-01-31 18:53:21 +0000 | [diff] [blame] | 520 | self.save_reduce(obj=obj, *rv) |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 521 | |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 522 | def persistent_id(self, obj): |
Guido van Rossum | bc64e22 | 2003-01-28 16:34:19 +0000 | [diff] [blame] | 523 | # This exists so a subclass can override it |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 524 | return None |
| 525 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 526 | def save_pers(self, pid): |
Guido van Rossum | bc64e22 | 2003-01-28 16:34:19 +0000 | [diff] [blame] | 527 | # Save a persistent id reference |
Tim Peters | bd1cdb9 | 2003-01-28 01:03:10 +0000 | [diff] [blame] | 528 | if self.bin: |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 529 | self.save(pid, save_persistent_id=False) |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 530 | self.write(BINPERSID) |
Tim Peters | bd1cdb9 | 2003-01-28 01:03:10 +0000 | [diff] [blame] | 531 | else: |
Guido van Rossum | 39478e8 | 2007-08-27 17:23:59 +0000 | [diff] [blame] | 532 | self.write(PERSID + str(pid).encode("ascii") + b'\n') |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 533 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 534 | def save_reduce(self, func, args, state=None, listitems=None, |
| 535 | dictitems=None, obj=None): |
Jeremy Hylton | e3a565e | 2003-06-29 16:59:59 +0000 | [diff] [blame] | 536 | # This API is called by some subclasses |
Guido van Rossum | bc64e22 | 2003-01-28 16:34:19 +0000 | [diff] [blame] | 537 | |
Guido van Rossum | 1325790 | 2007-06-07 23:15:56 +0000 | [diff] [blame] | 538 | if not isinstance(args, tuple): |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 539 | raise PicklingError("args from save_reduce() must be a tuple") |
Florent Xicluna | 5d1155c | 2011-10-28 14:45:05 +0200 | [diff] [blame] | 540 | if not callable(func): |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 541 | raise PicklingError("func from save_reduce() must be callable") |
Guido van Rossum | bc64e22 | 2003-01-28 16:34:19 +0000 | [diff] [blame] | 542 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 543 | save = self.save |
Guido van Rossum | bc64e22 | 2003-01-28 16:34:19 +0000 | [diff] [blame] | 544 | write = self.write |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 545 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 546 | func_name = getattr(func, "__name__", "") |
| 547 | if self.proto >= 4 and func_name == "__newobj_ex__": |
| 548 | cls, args, kwargs = args |
| 549 | if not hasattr(cls, "__new__"): |
| 550 | raise PicklingError("args[0] from {} args has no __new__" |
| 551 | .format(func_name)) |
| 552 | if obj is not None and cls is not obj.__class__: |
| 553 | raise PicklingError("args[0] from {} args has the wrong class" |
| 554 | .format(func_name)) |
| 555 | save(cls) |
| 556 | save(args) |
| 557 | save(kwargs) |
| 558 | write(NEWOBJ_EX) |
| 559 | elif self.proto >= 2 and func_name == "__newobj__": |
| 560 | # A __reduce__ implementation can direct protocol 2 or newer to |
Guido van Rossum | d053b4b | 2003-01-31 16:51:45 +0000 | [diff] [blame] | 561 | # use the more efficient NEWOBJ opcode, while still |
| 562 | # allowing protocol 0 and 1 to work normally. For this to |
| 563 | # work, the function returned by __reduce__ should be |
| 564 | # called __newobj__, and its first argument should be a |
Florent Xicluna | aa6c1d2 | 2011-12-12 18:54:29 +0100 | [diff] [blame] | 565 | # class. The implementation for __newobj__ |
Guido van Rossum | d053b4b | 2003-01-31 16:51:45 +0000 | [diff] [blame] | 566 | # should be as follows, although pickle has no way to |
| 567 | # verify this: |
| 568 | # |
| 569 | # def __newobj__(cls, *args): |
| 570 | # return cls.__new__(cls, *args) |
| 571 | # |
| 572 | # Protocols 0 and 1 will pickle a reference to __newobj__, |
| 573 | # while protocol 2 (and above) will pickle a reference to |
| 574 | # cls, the remaining args tuple, and the NEWOBJ code, |
| 575 | # which calls cls.__new__(cls, *args) at unpickling time |
| 576 | # (see load_newobj below). If __reduce__ returns a |
| 577 | # three-tuple, the state from the third tuple item will be |
| 578 | # pickled regardless of the protocol, calling __setstate__ |
| 579 | # at unpickling time (see load_build below). |
| 580 | # |
| 581 | # Note that no standard __newobj__ implementation exists; |
| 582 | # you have to provide your own. This is to enforce |
| 583 | # compatibility with Python 2.2 (pickles written using |
| 584 | # protocol 0 or 1 in Python 2.3 should be unpicklable by |
| 585 | # Python 2.2). |
| 586 | cls = args[0] |
| 587 | if not hasattr(cls, "__new__"): |
| 588 | raise PicklingError( |
| 589 | "args[0] from __newobj__ args has no __new__") |
Guido van Rossum | f7f4517 | 2003-01-31 17:17:49 +0000 | [diff] [blame] | 590 | if obj is not None and cls is not obj.__class__: |
| 591 | raise PicklingError( |
| 592 | "args[0] from __newobj__ args has the wrong class") |
Guido van Rossum | d053b4b | 2003-01-31 16:51:45 +0000 | [diff] [blame] | 593 | args = args[1:] |
| 594 | save(cls) |
| 595 | save(args) |
| 596 | write(NEWOBJ) |
| 597 | else: |
| 598 | save(func) |
| 599 | save(args) |
| 600 | write(REDUCE) |
Tim Peters | 2344fae | 2001-01-15 00:50:52 +0000 | [diff] [blame] | 601 | |
Guido van Rossum | f7f4517 | 2003-01-31 17:17:49 +0000 | [diff] [blame] | 602 | if obj is not None: |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 603 | # If the object is already in the memo, this means it is |
| 604 | # recursive. In this case, throw away everything we put on the |
| 605 | # stack, and fetch the object back from the memo. |
| 606 | if id(obj) in self.memo: |
| 607 | write(POP + self.get(self.memo[id(obj)][0])) |
| 608 | else: |
| 609 | self.memoize(obj) |
Guido van Rossum | f7f4517 | 2003-01-31 17:17:49 +0000 | [diff] [blame] | 610 | |
Guido van Rossum | 25cb7df | 2003-01-31 18:53:21 +0000 | [diff] [blame] | 611 | # More new special cases (that work with older protocols as |
| 612 | # well): when __reduce__ returns a tuple with 4 or 5 items, |
| 613 | # the 4th and 5th item should be iterators that provide list |
| 614 | # items and dict items (as (key, value) tuples), or None. |
| 615 | |
| 616 | if listitems is not None: |
| 617 | self._batch_appends(listitems) |
| 618 | |
| 619 | if dictitems is not None: |
| 620 | self._batch_setitems(dictitems) |
| 621 | |
Tim Peters | c32d824 | 2001-04-10 02:48:53 +0000 | [diff] [blame] | 622 | if state is not None: |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 623 | save(state) |
| 624 | write(BUILD) |
| 625 | |
Guido van Rossum | bc64e22 | 2003-01-28 16:34:19 +0000 | [diff] [blame] | 626 | # Methods below this point are dispatched through the dispatch table |
| 627 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 628 | dispatch = {} |
| 629 | |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 630 | def save_none(self, obj): |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 631 | self.write(NONE) |
Guido van Rossum | 1325790 | 2007-06-07 23:15:56 +0000 | [diff] [blame] | 632 | dispatch[type(None)] = save_none |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 633 | |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 634 | def save_bool(self, obj): |
Guido van Rossum | 7d97d31 | 2003-01-28 04:25:27 +0000 | [diff] [blame] | 635 | if self.proto >= 2: |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 636 | self.write(NEWTRUE if obj else NEWFALSE) |
Guido van Rossum | 7d97d31 | 2003-01-28 04:25:27 +0000 | [diff] [blame] | 637 | else: |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 638 | self.write(TRUE if obj else FALSE) |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 639 | dispatch[bool] = save_bool |
| 640 | |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 641 | def save_long(self, obj): |
Guido van Rossum | ddefaf3 | 2007-01-14 03:31:43 +0000 | [diff] [blame] | 642 | if self.bin: |
| 643 | # If the int is small enough to fit in a signed 4-byte 2's-comp |
| 644 | # format, we can store it more efficiently than the general |
| 645 | # case. |
| 646 | # First one- and two-byte unsigned ints: |
| 647 | if obj >= 0: |
| 648 | if obj <= 0xff: |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 649 | self.write(BININT1 + pack("<B", obj)) |
Guido van Rossum | ddefaf3 | 2007-01-14 03:31:43 +0000 | [diff] [blame] | 650 | return |
| 651 | if obj <= 0xffff: |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 652 | self.write(BININT2 + pack("<H", obj)) |
Guido van Rossum | ddefaf3 | 2007-01-14 03:31:43 +0000 | [diff] [blame] | 653 | return |
| 654 | # Next check for 4-byte signed ints: |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 655 | if -0x80000000 <= obj <= 0x7fffffff: |
Guido van Rossum | ddefaf3 | 2007-01-14 03:31:43 +0000 | [diff] [blame] | 656 | self.write(BININT + pack("<i", obj)) |
| 657 | return |
Guido van Rossum | d6c9e63 | 2003-01-28 03:49:52 +0000 | [diff] [blame] | 658 | if self.proto >= 2: |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 659 | encoded = encode_long(obj) |
| 660 | n = len(encoded) |
Guido van Rossum | d6c9e63 | 2003-01-28 03:49:52 +0000 | [diff] [blame] | 661 | if n < 256: |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 662 | self.write(LONG1 + pack("<B", n) + encoded) |
Guido van Rossum | d6c9e63 | 2003-01-28 03:49:52 +0000 | [diff] [blame] | 663 | else: |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 664 | self.write(LONG4 + pack("<i", n) + encoded) |
Tim Peters | ee1a53c | 2003-02-02 02:57:53 +0000 | [diff] [blame] | 665 | return |
Mark Dickinson | 8dd0514 | 2009-01-20 20:43:58 +0000 | [diff] [blame] | 666 | self.write(LONG + repr(obj).encode("ascii") + b'L\n') |
Guido van Rossum | 1325790 | 2007-06-07 23:15:56 +0000 | [diff] [blame] | 667 | dispatch[int] = save_long |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 668 | |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 669 | def save_float(self, obj): |
Guido van Rossum | d370379 | 1998-10-22 20:15:36 +0000 | [diff] [blame] | 670 | if self.bin: |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 671 | self.write(BINFLOAT + pack('>d', obj)) |
Guido van Rossum | d370379 | 1998-10-22 20:15:36 +0000 | [diff] [blame] | 672 | else: |
Guido van Rossum | 39478e8 | 2007-08-27 17:23:59 +0000 | [diff] [blame] | 673 | self.write(FLOAT + repr(obj).encode("ascii") + b'\n') |
Guido van Rossum | 1325790 | 2007-06-07 23:15:56 +0000 | [diff] [blame] | 674 | dispatch[float] = save_float |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 675 | |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 676 | def save_bytes(self, obj): |
Guido van Rossum | f416981 | 2008-03-17 22:56:06 +0000 | [diff] [blame] | 677 | if self.proto < 3: |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 678 | if not obj: # bytes object is empty |
Alexandre Vassalotti | 3bfc65a | 2011-12-13 13:08:09 -0500 | [diff] [blame] | 679 | self.save_reduce(bytes, (), obj=obj) |
| 680 | else: |
| 681 | self.save_reduce(codecs.encode, |
| 682 | (str(obj, 'latin1'), 'latin1'), obj=obj) |
Guido van Rossum | f416981 | 2008-03-17 22:56:06 +0000 | [diff] [blame] | 683 | return |
| 684 | n = len(obj) |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 685 | if n <= 0xff: |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 686 | self.write(SHORT_BINBYTES + pack("<B", n) + obj) |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 687 | elif n > 0xffffffff and self.proto >= 4: |
| 688 | self.write(BINBYTES8 + pack("<Q", n) + obj) |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 689 | else: |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 690 | self.write(BINBYTES + pack("<I", n) + obj) |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 691 | self.memoize(obj) |
Guido van Rossum | f416981 | 2008-03-17 22:56:06 +0000 | [diff] [blame] | 692 | dispatch[bytes] = save_bytes |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 693 | |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 694 | def save_str(self, obj): |
Tim Peters | c32d824 | 2001-04-10 02:48:53 +0000 | [diff] [blame] | 695 | if self.bin: |
Victor Stinner | 485fb56 | 2010-04-13 11:07:24 +0000 | [diff] [blame] | 696 | encoded = obj.encode('utf-8', 'surrogatepass') |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 697 | n = len(encoded) |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 698 | if n <= 0xff and self.proto >= 4: |
| 699 | self.write(SHORT_BINUNICODE + pack("<B", n) + encoded) |
| 700 | elif n > 0xffffffff and self.proto >= 4: |
| 701 | self.write(BINUNICODE8 + pack("<Q", n) + encoded) |
| 702 | else: |
| 703 | self.write(BINUNICODE + pack("<I", n) + encoded) |
Guido van Rossum | b5f2f1b | 2000-03-10 23:20:09 +0000 | [diff] [blame] | 704 | else: |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 705 | obj = obj.replace("\\", "\\u005c") |
| 706 | obj = obj.replace("\n", "\\u000a") |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 707 | self.write(UNICODE + obj.encode('raw-unicode-escape') + |
| 708 | b'\n') |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 709 | self.memoize(obj) |
Guido van Rossum | f416981 | 2008-03-17 22:56:06 +0000 | [diff] [blame] | 710 | dispatch[str] = save_str |
Tim Peters | 658cba6 | 2001-02-09 20:06:00 +0000 | [diff] [blame] | 711 | |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 712 | def save_tuple(self, obj): |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 713 | if not obj: # tuple is empty |
| 714 | if self.bin: |
| 715 | self.write(EMPTY_TUPLE) |
Tim Peters | 1d63c9f | 2003-02-02 20:29:39 +0000 | [diff] [blame] | 716 | else: |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 717 | self.write(MARK + TUPLE) |
Tim Peters | d97da80 | 2003-01-28 05:48:29 +0000 | [diff] [blame] | 718 | return |
| 719 | |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 720 | n = len(obj) |
Tim Peters | d97da80 | 2003-01-28 05:48:29 +0000 | [diff] [blame] | 721 | save = self.save |
| 722 | memo = self.memo |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 723 | if n <= 3 and self.proto >= 2: |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 724 | for element in obj: |
Tim Peters | d97da80 | 2003-01-28 05:48:29 +0000 | [diff] [blame] | 725 | save(element) |
| 726 | # Subtle. Same as in the big comment below. |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 727 | if id(obj) in memo: |
| 728 | get = self.get(memo[id(obj)][0]) |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 729 | self.write(POP * n + get) |
Tim Peters | d97da80 | 2003-01-28 05:48:29 +0000 | [diff] [blame] | 730 | else: |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 731 | self.write(_tuplesize2code[n]) |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 732 | self.memoize(obj) |
Tim Peters | d97da80 | 2003-01-28 05:48:29 +0000 | [diff] [blame] | 733 | return |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 734 | |
Tim Peters | 1d63c9f | 2003-02-02 20:29:39 +0000 | [diff] [blame] | 735 | # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple |
Tim Peters | ff57bff | 2003-01-28 05:34:53 +0000 | [diff] [blame] | 736 | # has more than 3 elements. |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 737 | write = self.write |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 738 | write(MARK) |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 739 | for element in obj: |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 740 | save(element) |
| 741 | |
Tim Peters | 1d63c9f | 2003-02-02 20:29:39 +0000 | [diff] [blame] | 742 | if id(obj) in memo: |
Tim Peters | f558da0 | 2003-01-28 02:09:55 +0000 | [diff] [blame] | 743 | # Subtle. d was not in memo when we entered save_tuple(), so |
| 744 | # the process of saving the tuple's elements must have saved |
| 745 | # the tuple itself: the tuple is recursive. The proper action |
| 746 | # now is to throw away everything we put on the stack, and |
| 747 | # simply GET the tuple (it's already constructed). This check |
| 748 | # could have been done in the "for element" loop instead, but |
| 749 | # recursive tuples are a rare thing. |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 750 | get = self.get(memo[id(obj)][0]) |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 751 | if self.bin: |
Tim Peters | f558da0 | 2003-01-28 02:09:55 +0000 | [diff] [blame] | 752 | write(POP_MARK + get) |
| 753 | else: # proto 0 -- POP_MARK not available |
Tim Peters | d97da80 | 2003-01-28 05:48:29 +0000 | [diff] [blame] | 754 | write(POP * (n+1) + get) |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 755 | return |
| 756 | |
Tim Peters | 1d63c9f | 2003-02-02 20:29:39 +0000 | [diff] [blame] | 757 | # No recursion. |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 758 | write(TUPLE) |
Tim Peters | 1d63c9f | 2003-02-02 20:29:39 +0000 | [diff] [blame] | 759 | self.memoize(obj) |
Jeremy Hylton | 3422c99 | 2003-01-24 19:29:52 +0000 | [diff] [blame] | 760 | |
Guido van Rossum | 1325790 | 2007-06-07 23:15:56 +0000 | [diff] [blame] | 761 | dispatch[tuple] = save_tuple |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 762 | |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 763 | def save_list(self, obj): |
Tim Peters | c32d824 | 2001-04-10 02:48:53 +0000 | [diff] [blame] | 764 | if self.bin: |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 765 | self.write(EMPTY_LIST) |
Guido van Rossum | 25cb7df | 2003-01-31 18:53:21 +0000 | [diff] [blame] | 766 | else: # proto 0 -- can't use EMPTY_LIST |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 767 | self.write(MARK + LIST) |
Guido van Rossum | 25cb7df | 2003-01-31 18:53:21 +0000 | [diff] [blame] | 768 | |
| 769 | self.memoize(obj) |
Alexandre Vassalotti | c7db1d6 | 2008-05-14 21:57:18 +0000 | [diff] [blame] | 770 | self._batch_appends(obj) |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 771 | |
Guido van Rossum | 1325790 | 2007-06-07 23:15:56 +0000 | [diff] [blame] | 772 | dispatch[list] = save_list |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 773 | |
Guido van Rossum | 25cb7df | 2003-01-31 18:53:21 +0000 | [diff] [blame] | 774 | _BATCHSIZE = 1000 |
| 775 | |
| 776 | def _batch_appends(self, items): |
| 777 | # Helper to batch up APPENDS sequences |
| 778 | save = self.save |
| 779 | write = self.write |
| 780 | |
| 781 | if not self.bin: |
| 782 | for x in items: |
| 783 | save(x) |
| 784 | write(APPEND) |
| 785 | return |
| 786 | |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 787 | it = iter(items) |
| 788 | while True: |
| 789 | tmp = list(islice(it, self._BATCHSIZE)) |
Guido van Rossum | 25cb7df | 2003-01-31 18:53:21 +0000 | [diff] [blame] | 790 | n = len(tmp) |
| 791 | if n > 1: |
| 792 | write(MARK) |
| 793 | for x in tmp: |
| 794 | save(x) |
| 795 | write(APPENDS) |
| 796 | elif n: |
| 797 | save(tmp[0]) |
| 798 | write(APPEND) |
| 799 | # else tmp is empty, and we're done |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 800 | if n < self._BATCHSIZE: |
| 801 | return |
Guido van Rossum | 25cb7df | 2003-01-31 18:53:21 +0000 | [diff] [blame] | 802 | |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 803 | def save_dict(self, obj): |
Tim Peters | c32d824 | 2001-04-10 02:48:53 +0000 | [diff] [blame] | 804 | if self.bin: |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 805 | self.write(EMPTY_DICT) |
Guido van Rossum | 25cb7df | 2003-01-31 18:53:21 +0000 | [diff] [blame] | 806 | else: # proto 0 -- can't use EMPTY_DICT |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 807 | self.write(MARK + DICT) |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 808 | |
Guido van Rossum | 25cb7df | 2003-01-31 18:53:21 +0000 | [diff] [blame] | 809 | self.memoize(obj) |
Alexandre Vassalotti | c7db1d6 | 2008-05-14 21:57:18 +0000 | [diff] [blame] | 810 | self._batch_setitems(obj.items()) |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 811 | |
Guido van Rossum | 1325790 | 2007-06-07 23:15:56 +0000 | [diff] [blame] | 812 | dispatch[dict] = save_dict |
| 813 | if PyStringMap is not None: |
Jeremy Hylton | 2b9d029 | 1998-05-27 22:38:22 +0000 | [diff] [blame] | 814 | dispatch[PyStringMap] = save_dict |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 815 | |
Guido van Rossum | 25cb7df | 2003-01-31 18:53:21 +0000 | [diff] [blame] | 816 | def _batch_setitems(self, items): |
| 817 | # Helper to batch up SETITEMS sequences; proto >= 1 only |
| 818 | save = self.save |
| 819 | write = self.write |
| 820 | |
| 821 | if not self.bin: |
| 822 | for k, v in items: |
| 823 | save(k) |
| 824 | save(v) |
| 825 | write(SETITEM) |
| 826 | return |
| 827 | |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 828 | it = iter(items) |
| 829 | while True: |
| 830 | tmp = list(islice(it, self._BATCHSIZE)) |
Guido van Rossum | 25cb7df | 2003-01-31 18:53:21 +0000 | [diff] [blame] | 831 | n = len(tmp) |
| 832 | if n > 1: |
| 833 | write(MARK) |
| 834 | for k, v in tmp: |
| 835 | save(k) |
| 836 | save(v) |
| 837 | write(SETITEMS) |
| 838 | elif n: |
| 839 | k, v = tmp[0] |
| 840 | save(k) |
| 841 | save(v) |
| 842 | write(SETITEM) |
| 843 | # else tmp is empty, and we're done |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 844 | if n < self._BATCHSIZE: |
| 845 | return |
Guido van Rossum | 25cb7df | 2003-01-31 18:53:21 +0000 | [diff] [blame] | 846 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 847 | def save_set(self, obj): |
| 848 | save = self.save |
| 849 | write = self.write |
| 850 | |
| 851 | if self.proto < 4: |
| 852 | self.save_reduce(set, (list(obj),), obj=obj) |
| 853 | return |
| 854 | |
| 855 | write(EMPTY_SET) |
| 856 | self.memoize(obj) |
| 857 | |
| 858 | it = iter(obj) |
| 859 | while True: |
| 860 | batch = list(islice(it, self._BATCHSIZE)) |
| 861 | n = len(batch) |
| 862 | if n > 0: |
| 863 | write(MARK) |
| 864 | for item in batch: |
| 865 | save(item) |
| 866 | write(ADDITEMS) |
| 867 | if n < self._BATCHSIZE: |
| 868 | return |
| 869 | dispatch[set] = save_set |
| 870 | |
| 871 | def save_frozenset(self, obj): |
| 872 | save = self.save |
| 873 | write = self.write |
| 874 | |
| 875 | if self.proto < 4: |
| 876 | self.save_reduce(frozenset, (list(obj),), obj=obj) |
| 877 | return |
| 878 | |
| 879 | write(MARK) |
| 880 | for item in obj: |
| 881 | save(item) |
| 882 | |
| 883 | if id(obj) in self.memo: |
| 884 | # If the object is already in the memo, this means it is |
| 885 | # recursive. In this case, throw away everything we put on the |
| 886 | # stack, and fetch the object back from the memo. |
| 887 | write(POP_MARK + self.get(self.memo[id(obj)][0])) |
| 888 | return |
| 889 | |
| 890 | write(FROZENSET) |
| 891 | self.memoize(obj) |
| 892 | dispatch[frozenset] = save_frozenset |
| 893 | |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 894 | def save_global(self, obj, name=None): |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 895 | write = self.write |
| 896 | memo = self.memo |
| 897 | |
Serhiy Storchaka | 58e4134 | 2015-03-31 14:07:24 +0300 | [diff] [blame] | 898 | if name is None: |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 899 | name = getattr(obj, '__qualname__', None) |
Tim Peters | c32d824 | 2001-04-10 02:48:53 +0000 | [diff] [blame] | 900 | if name is None: |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 901 | name = obj.__name__ |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 902 | |
Serhiy Storchaka | 58e4134 | 2015-03-31 14:07:24 +0300 | [diff] [blame] | 903 | module_name = whichmodule(obj, name) |
Guido van Rossum | b0a98e9 | 2001-08-17 18:49:52 +0000 | [diff] [blame] | 904 | try: |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 905 | __import__(module_name, level=0) |
| 906 | module = sys.modules[module_name] |
Serhiy Storchaka | 58e4134 | 2015-03-31 14:07:24 +0300 | [diff] [blame] | 907 | obj2, parent = _getattribute(module, name) |
Guido van Rossum | b0a98e9 | 2001-08-17 18:49:52 +0000 | [diff] [blame] | 908 | except (ImportError, KeyError, AttributeError): |
| 909 | raise PicklingError( |
| 910 | "Can't pickle %r: it's not found as %s.%s" % |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 911 | (obj, module_name, name)) |
Guido van Rossum | b0a98e9 | 2001-08-17 18:49:52 +0000 | [diff] [blame] | 912 | else: |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 913 | if obj2 is not obj: |
Guido van Rossum | b0a98e9 | 2001-08-17 18:49:52 +0000 | [diff] [blame] | 914 | raise PicklingError( |
| 915 | "Can't pickle %r: it's not the same object as %s.%s" % |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 916 | (obj, module_name, name)) |
Guido van Rossum | b0a98e9 | 2001-08-17 18:49:52 +0000 | [diff] [blame] | 917 | |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 918 | if self.proto >= 2: |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 919 | code = _extension_registry.get((module_name, name)) |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 920 | if code: |
| 921 | assert code > 0 |
| 922 | if code <= 0xff: |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 923 | write(EXT1 + pack("<B", code)) |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 924 | elif code <= 0xffff: |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 925 | write(EXT2 + pack("<H", code)) |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 926 | else: |
| 927 | write(EXT4 + pack("<i", code)) |
| 928 | return |
Serhiy Storchaka | 58e4134 | 2015-03-31 14:07:24 +0300 | [diff] [blame] | 929 | lastname = name.rpartition('.')[2] |
| 930 | if parent is module: |
| 931 | name = lastname |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 932 | # Non-ASCII identifiers are supported only with protocols >= 3. |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 933 | if self.proto >= 4: |
| 934 | self.save(module_name) |
| 935 | self.save(name) |
| 936 | write(STACK_GLOBAL) |
Serhiy Storchaka | 58e4134 | 2015-03-31 14:07:24 +0300 | [diff] [blame] | 937 | elif parent is not module: |
| 938 | self.save_reduce(getattr, (parent, lastname)) |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 939 | elif self.proto >= 3: |
| 940 | write(GLOBAL + bytes(module_name, "utf-8") + b'\n' + |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 941 | bytes(name, "utf-8") + b'\n') |
| 942 | else: |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 943 | if self.fix_imports: |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 944 | r_name_mapping = _compat_pickle.REVERSE_NAME_MAPPING |
| 945 | r_import_mapping = _compat_pickle.REVERSE_IMPORT_MAPPING |
| 946 | if (module_name, name) in r_name_mapping: |
| 947 | module_name, name = r_name_mapping[(module_name, name)] |
Serhiy Storchaka | bfe1824 | 2015-03-31 13:12:37 +0300 | [diff] [blame] | 948 | elif module_name in r_import_mapping: |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 949 | module_name = r_import_mapping[module_name] |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 950 | try: |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 951 | write(GLOBAL + bytes(module_name, "ascii") + b'\n' + |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 952 | bytes(name, "ascii") + b'\n') |
| 953 | except UnicodeEncodeError: |
| 954 | raise PicklingError( |
| 955 | "can't pickle global identifier '%s.%s' using " |
| 956 | "pickle protocol %i" % (module, name, self.proto)) |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 957 | |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 958 | self.memoize(obj) |
Tim Peters | 3b76983 | 2003-01-28 03:51:36 +0000 | [diff] [blame] | 959 | |
Alexandre Vassalotti | 19b6fa6 | 2013-11-30 16:06:39 -0800 | [diff] [blame] | 960 | def save_type(self, obj): |
| 961 | if obj is type(None): |
| 962 | return self.save_reduce(type, (None,), obj=obj) |
| 963 | elif obj is type(NotImplemented): |
| 964 | return self.save_reduce(type, (NotImplemented,), obj=obj) |
| 965 | elif obj is type(...): |
| 966 | return self.save_reduce(type, (...,), obj=obj) |
| 967 | return self.save_global(obj) |
| 968 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 969 | dispatch[FunctionType] = save_global |
Alexandre Vassalotti | 19b6fa6 | 2013-11-30 16:06:39 -0800 | [diff] [blame] | 970 | dispatch[type] = save_type |
Guido van Rossum | 0c891ce | 1995-03-14 15:09:05 +0000 | [diff] [blame] | 971 | |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 972 | |
Guido van Rossum | 1be3175 | 2003-01-28 15:19:53 +0000 | [diff] [blame] | 973 | # Unpickling machinery |
| 974 | |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 975 | class _Unpickler: |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 976 | |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 977 | def __init__(self, file, *, fix_imports=True, |
| 978 | encoding="ASCII", errors="strict"): |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 979 | """This takes a binary file for reading a pickle data stream. |
Raymond Hettinger | aef22fb | 2002-05-29 16:18:42 +0000 | [diff] [blame] | 980 | |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 981 | The protocol version of the pickle is detected automatically, so |
| 982 | no proto argument is needed. |
| 983 | |
| 984 | The argument *file* must have two methods, a read() method that |
| 985 | takes an integer argument, and a readline() method that requires |
| 986 | no arguments. Both methods should return bytes. Thus *file* |
Martin Panter | 7462b649 | 2015-11-02 03:37:02 +0000 | [diff] [blame] | 987 | can be a binary file object opened for reading, an io.BytesIO |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 988 | object, or any other custom object that meets this interface. |
Raymond Hettinger | aef22fb | 2002-05-29 16:18:42 +0000 | [diff] [blame] | 989 | |
Guido van Rossum | feea078 | 2007-10-10 18:00:50 +0000 | [diff] [blame] | 990 | The file-like object must have two methods, a read() method |
| 991 | that takes an integer argument, and a readline() method that |
| 992 | requires no arguments. Both methods should return bytes. |
| 993 | Thus file-like object can be a binary file object opened for |
| 994 | reading, a BytesIO object, or any other custom object that |
| 995 | meets this interface. |
Guido van Rossum | f416981 | 2008-03-17 22:56:06 +0000 | [diff] [blame] | 996 | |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 997 | Optional keyword arguments are *fix_imports*, *encoding* and |
Martin Panter | 46f5072 | 2016-05-26 05:35:26 +0000 | [diff] [blame] | 998 | *errors*, which are used to control compatibility support for |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 999 | pickle stream generated by Python 2. If *fix_imports* is True, |
| 1000 | pickle will try to map the old Python 2 names to the new names |
| 1001 | used in Python 3. The *encoding* and *errors* tell pickle how |
| 1002 | to decode 8-bit string instances pickled by Python 2; these |
| 1003 | default to 'ASCII' and 'strict', respectively. *encoding* can be |
| 1004 | 'bytes' to read theses 8-bit string instances as bytes objects. |
Raymond Hettinger | aef22fb | 2002-05-29 16:18:42 +0000 | [diff] [blame] | 1005 | """ |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1006 | self._file_readline = file.readline |
| 1007 | self._file_read = file.read |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1008 | self.memo = {} |
Guido van Rossum | f416981 | 2008-03-17 22:56:06 +0000 | [diff] [blame] | 1009 | self.encoding = encoding |
| 1010 | self.errors = errors |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 1011 | self.proto = 0 |
| 1012 | self.fix_imports = fix_imports |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 1013 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1014 | def load(self): |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 1015 | """Read a pickled object representation from the open file. |
Raymond Hettinger | aef22fb | 2002-05-29 16:18:42 +0000 | [diff] [blame] | 1016 | |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 1017 | Return the reconstituted object hierarchy specified in the file. |
Raymond Hettinger | aef22fb | 2002-05-29 16:18:42 +0000 | [diff] [blame] | 1018 | """ |
Alexandre Vassalotti | 3cfcab9 | 2008-12-27 09:30:39 +0000 | [diff] [blame] | 1019 | # Check whether Unpickler was initialized correctly. This is |
| 1020 | # only needed to mimic the behavior of _pickle.Unpickler.dump(). |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1021 | if not hasattr(self, "_file_read"): |
Alexandre Vassalotti | 3cfcab9 | 2008-12-27 09:30:39 +0000 | [diff] [blame] | 1022 | raise UnpicklingError("Unpickler.__init__() was not called by " |
| 1023 | "%s.__init__()" % (self.__class__.__name__,)) |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1024 | self._unframer = _Unframer(self._file_read, self._file_readline) |
| 1025 | self.read = self._unframer.read |
| 1026 | self.readline = self._unframer.readline |
Jeremy Hylton | 20747fa | 2001-11-09 16:15:04 +0000 | [diff] [blame] | 1027 | self.mark = object() # any new unique object |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1028 | self.stack = [] |
| 1029 | self.append = self.stack.append |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1030 | self.proto = 0 |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1031 | read = self.read |
| 1032 | dispatch = self.dispatch |
| 1033 | try: |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 1034 | while True: |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1035 | key = read(1) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1036 | if not key: |
| 1037 | raise EOFError |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 1038 | assert isinstance(key, bytes_types) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1039 | dispatch[key[0]](self) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 1040 | except _Stop as stopinst: |
Guido van Rossum | ff87174 | 2000-12-13 18:11:56 +0000 | [diff] [blame] | 1041 | return stopinst.value |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1042 | |
Tim Peters | c23d18a | 2003-01-28 01:41:51 +0000 | [diff] [blame] | 1043 | # Return largest index k such that self.stack[k] is self.mark. |
| 1044 | # If the stack doesn't contain a mark, eventually raises IndexError. |
| 1045 | # This could be sped by maintaining another stack, of indices at which |
| 1046 | # the mark appears. For that matter, the latter stack would suffice, |
| 1047 | # and we wouldn't need to push mark objects on self.stack at all. |
| 1048 | # Doing so is probably a good thing, though, since if the pickle is |
| 1049 | # corrupt (or hostile) we may get a clue from finding self.mark embedded |
| 1050 | # in unpickled objects. |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1051 | def marker(self): |
| 1052 | stack = self.stack |
| 1053 | mark = self.mark |
| 1054 | k = len(stack)-1 |
| 1055 | while stack[k] is not mark: k = k-1 |
| 1056 | return k |
| 1057 | |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 1058 | def persistent_load(self, pid): |
Benjamin Peterson | 49956b2 | 2009-01-10 17:05:44 +0000 | [diff] [blame] | 1059 | raise UnpicklingError("unsupported persistent id encountered") |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 1060 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1061 | dispatch = {} |
| 1062 | |
Guido van Rossum | d6c9e63 | 2003-01-28 03:49:52 +0000 | [diff] [blame] | 1063 | def load_proto(self): |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 1064 | proto = self.read(1)[0] |
Guido van Rossum | f416981 | 2008-03-17 22:56:06 +0000 | [diff] [blame] | 1065 | if not 0 <= proto <= HIGHEST_PROTOCOL: |
Guido van Rossum | 26d95c3 | 2007-08-27 23:18:54 +0000 | [diff] [blame] | 1066 | raise ValueError("unsupported pickle protocol: %d" % proto) |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 1067 | self.proto = proto |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1068 | dispatch[PROTO[0]] = load_proto |
Guido van Rossum | d6c9e63 | 2003-01-28 03:49:52 +0000 | [diff] [blame] | 1069 | |
Alexandre Vassalotti | b6a2f2a | 2013-11-23 20:30:03 -0800 | [diff] [blame] | 1070 | def load_frame(self): |
| 1071 | frame_size, = unpack('<Q', self.read(8)) |
| 1072 | if frame_size > sys.maxsize: |
| 1073 | raise ValueError("frame size > sys.maxsize: %d" % frame_size) |
| 1074 | self._unframer.load_frame(frame_size) |
| 1075 | dispatch[FRAME[0]] = load_frame |
| 1076 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1077 | def load_persid(self): |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 1078 | pid = self.readline()[:-1].decode("ascii") |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1079 | self.append(self.persistent_load(pid)) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1080 | dispatch[PERSID[0]] = load_persid |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1081 | |
| 1082 | def load_binpersid(self): |
Raymond Hettinger | 46ac8eb | 2002-06-30 03:39:14 +0000 | [diff] [blame] | 1083 | pid = self.stack.pop() |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1084 | self.append(self.persistent_load(pid)) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1085 | dispatch[BINPERSID[0]] = load_binpersid |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1086 | |
| 1087 | def load_none(self): |
| 1088 | self.append(None) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1089 | dispatch[NONE[0]] = load_none |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1090 | |
Guido van Rossum | 7d97d31 | 2003-01-28 04:25:27 +0000 | [diff] [blame] | 1091 | def load_false(self): |
| 1092 | self.append(False) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1093 | dispatch[NEWFALSE[0]] = load_false |
Guido van Rossum | 7d97d31 | 2003-01-28 04:25:27 +0000 | [diff] [blame] | 1094 | |
| 1095 | def load_true(self): |
| 1096 | self.append(True) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1097 | dispatch[NEWTRUE[0]] = load_true |
Guido van Rossum | 7d97d31 | 2003-01-28 04:25:27 +0000 | [diff] [blame] | 1098 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1099 | def load_int(self): |
Tim Peters | 19ef62d | 2001-08-28 22:21:18 +0000 | [diff] [blame] | 1100 | data = self.readline() |
Guido van Rossum | e276339 | 2002-04-05 19:30:08 +0000 | [diff] [blame] | 1101 | if data == FALSE[1:]: |
| 1102 | val = False |
| 1103 | elif data == TRUE[1:]: |
| 1104 | val = True |
| 1105 | else: |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 1106 | val = int(data, 0) |
Guido van Rossum | e276339 | 2002-04-05 19:30:08 +0000 | [diff] [blame] | 1107 | self.append(val) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1108 | dispatch[INT[0]] = load_int |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1109 | |
| 1110 | def load_binint(self): |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 1111 | self.append(unpack('<i', self.read(4))[0]) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1112 | dispatch[BININT[0]] = load_binint |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1113 | |
| 1114 | def load_binint1(self): |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 1115 | self.append(self.read(1)[0]) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1116 | dispatch[BININT1[0]] = load_binint1 |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1117 | |
| 1118 | def load_binint2(self): |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 1119 | self.append(unpack('<H', self.read(2))[0]) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1120 | dispatch[BININT2[0]] = load_binint2 |
Tim Peters | 2344fae | 2001-01-15 00:50:52 +0000 | [diff] [blame] | 1121 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1122 | def load_long(self): |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 1123 | val = self.readline()[:-1] |
| 1124 | if val and val[-1] == b'L'[0]: |
Mark Dickinson | 8dd0514 | 2009-01-20 20:43:58 +0000 | [diff] [blame] | 1125 | val = val[:-1] |
Guido van Rossum | feea078 | 2007-10-10 18:00:50 +0000 | [diff] [blame] | 1126 | self.append(int(val, 0)) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1127 | dispatch[LONG[0]] = load_long |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1128 | |
Guido van Rossum | d6c9e63 | 2003-01-28 03:49:52 +0000 | [diff] [blame] | 1129 | def load_long1(self): |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 1130 | n = self.read(1)[0] |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1131 | data = self.read(n) |
| 1132 | self.append(decode_long(data)) |
| 1133 | dispatch[LONG1[0]] = load_long1 |
Guido van Rossum | d6c9e63 | 2003-01-28 03:49:52 +0000 | [diff] [blame] | 1134 | |
| 1135 | def load_long4(self): |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 1136 | n, = unpack('<i', self.read(4)) |
Antoine Pitrou | bf6ecf9 | 2012-11-24 20:40:21 +0100 | [diff] [blame] | 1137 | if n < 0: |
| 1138 | # Corrupt or hostile pickle -- we never write one like this |
Alexandre Vassalotti | cc75717 | 2013-04-14 02:25:10 -0700 | [diff] [blame] | 1139 | raise UnpicklingError("LONG pickle has negative byte count") |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1140 | data = self.read(n) |
| 1141 | self.append(decode_long(data)) |
| 1142 | dispatch[LONG4[0]] = load_long4 |
Guido van Rossum | d6c9e63 | 2003-01-28 03:49:52 +0000 | [diff] [blame] | 1143 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1144 | def load_float(self): |
Guido van Rossum | ff87174 | 2000-12-13 18:11:56 +0000 | [diff] [blame] | 1145 | self.append(float(self.readline()[:-1])) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1146 | dispatch[FLOAT[0]] = load_float |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1147 | |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 1148 | def load_binfloat(self): |
Guido van Rossum | d370379 | 1998-10-22 20:15:36 +0000 | [diff] [blame] | 1149 | self.append(unpack('>d', self.read(8))[0]) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1150 | dispatch[BINFLOAT[0]] = load_binfloat |
Guido van Rossum | d370379 | 1998-10-22 20:15:36 +0000 | [diff] [blame] | 1151 | |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 1152 | def _decode_string(self, value): |
| 1153 | # Used to allow strings from Python 2 to be decoded either as |
| 1154 | # bytes or Unicode strings. This should be used only with the |
| 1155 | # STRING, BINSTRING and SHORT_BINSTRING opcodes. |
| 1156 | if self.encoding == "bytes": |
| 1157 | return value |
| 1158 | else: |
| 1159 | return value.decode(self.encoding, self.errors) |
| 1160 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1161 | def load_string(self): |
Alexandre Vassalotti | 7c5e094 | 2013-04-15 23:14:55 -0700 | [diff] [blame] | 1162 | data = self.readline()[:-1] |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 1163 | # Strip outermost quotes |
Alexandre Vassalotti | 7c5e094 | 2013-04-15 23:14:55 -0700 | [diff] [blame] | 1164 | if len(data) >= 2 and data[0] == data[-1] and data[0] in b'"\'': |
| 1165 | data = data[1:-1] |
Martin v. Löwis | 8a8da79 | 2002-08-14 07:46:28 +0000 | [diff] [blame] | 1166 | else: |
Alexandre Vassalotti | 7c5e094 | 2013-04-15 23:14:55 -0700 | [diff] [blame] | 1167 | raise UnpicklingError("the STRING opcode argument must be quoted") |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 1168 | self.append(self._decode_string(codecs.escape_decode(data)[0])) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1169 | dispatch[STRING[0]] = load_string |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1170 | |
| 1171 | def load_binstring(self): |
Antoine Pitrou | bf6ecf9 | 2012-11-24 20:40:21 +0100 | [diff] [blame] | 1172 | # Deprecated BINSTRING uses signed 32-bit length |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 1173 | len, = unpack('<i', self.read(4)) |
Antoine Pitrou | bf6ecf9 | 2012-11-24 20:40:21 +0100 | [diff] [blame] | 1174 | if len < 0: |
Alexandre Vassalotti | cc75717 | 2013-04-14 02:25:10 -0700 | [diff] [blame] | 1175 | raise UnpicklingError("BINSTRING pickle has negative byte count") |
Guido van Rossum | f416981 | 2008-03-17 22:56:06 +0000 | [diff] [blame] | 1176 | data = self.read(len) |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 1177 | self.append(self._decode_string(data)) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1178 | dispatch[BINSTRING[0]] = load_binstring |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1179 | |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 1180 | def load_binbytes(self): |
Antoine Pitrou | bf6ecf9 | 2012-11-24 20:40:21 +0100 | [diff] [blame] | 1181 | len, = unpack('<I', self.read(4)) |
| 1182 | if len > maxsize: |
Alexandre Vassalotti | cc75717 | 2013-04-14 02:25:10 -0700 | [diff] [blame] | 1183 | raise UnpicklingError("BINBYTES exceeds system's maximum size " |
| 1184 | "of %d bytes" % maxsize) |
Guido van Rossum | f416981 | 2008-03-17 22:56:06 +0000 | [diff] [blame] | 1185 | self.append(self.read(len)) |
| 1186 | dispatch[BINBYTES[0]] = load_binbytes |
| 1187 | |
Guido van Rossum | b5f2f1b | 2000-03-10 23:20:09 +0000 | [diff] [blame] | 1188 | def load_unicode(self): |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1189 | self.append(str(self.readline()[:-1], 'raw-unicode-escape')) |
| 1190 | dispatch[UNICODE[0]] = load_unicode |
Guido van Rossum | b5f2f1b | 2000-03-10 23:20:09 +0000 | [diff] [blame] | 1191 | |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 1192 | def load_binunicode(self): |
Antoine Pitrou | bf6ecf9 | 2012-11-24 20:40:21 +0100 | [diff] [blame] | 1193 | len, = unpack('<I', self.read(4)) |
| 1194 | if len > maxsize: |
Alexandre Vassalotti | cc75717 | 2013-04-14 02:25:10 -0700 | [diff] [blame] | 1195 | raise UnpicklingError("BINUNICODE exceeds system's maximum size " |
| 1196 | "of %d bytes" % maxsize) |
Victor Stinner | 485fb56 | 2010-04-13 11:07:24 +0000 | [diff] [blame] | 1197 | self.append(str(self.read(len), 'utf-8', 'surrogatepass')) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1198 | dispatch[BINUNICODE[0]] = load_binunicode |
Guido van Rossum | b5f2f1b | 2000-03-10 23:20:09 +0000 | [diff] [blame] | 1199 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1200 | def load_binunicode8(self): |
| 1201 | len, = unpack('<Q', self.read(8)) |
| 1202 | if len > maxsize: |
| 1203 | raise UnpicklingError("BINUNICODE8 exceeds system's maximum size " |
| 1204 | "of %d bytes" % maxsize) |
| 1205 | self.append(str(self.read(len), 'utf-8', 'surrogatepass')) |
| 1206 | dispatch[BINUNICODE8[0]] = load_binunicode8 |
| 1207 | |
Serhiy Storchaka | e060619 | 2015-09-29 22:10:07 +0300 | [diff] [blame] | 1208 | def load_binbytes8(self): |
| 1209 | len, = unpack('<Q', self.read(8)) |
| 1210 | if len > maxsize: |
| 1211 | raise UnpicklingError("BINBYTES8 exceeds system's maximum size " |
| 1212 | "of %d bytes" % maxsize) |
| 1213 | self.append(self.read(len)) |
| 1214 | dispatch[BINBYTES8[0]] = load_binbytes8 |
| 1215 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1216 | def load_short_binstring(self): |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 1217 | len = self.read(1)[0] |
| 1218 | data = self.read(len) |
Alexandre Vassalotti | d05c9ff | 2013-12-07 01:09:27 -0800 | [diff] [blame] | 1219 | self.append(self._decode_string(data)) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1220 | dispatch[SHORT_BINSTRING[0]] = load_short_binstring |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1221 | |
Guido van Rossum | f416981 | 2008-03-17 22:56:06 +0000 | [diff] [blame] | 1222 | def load_short_binbytes(self): |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 1223 | len = self.read(1)[0] |
| 1224 | self.append(self.read(len)) |
Guido van Rossum | f416981 | 2008-03-17 22:56:06 +0000 | [diff] [blame] | 1225 | dispatch[SHORT_BINBYTES[0]] = load_short_binbytes |
| 1226 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1227 | def load_short_binunicode(self): |
| 1228 | len = self.read(1)[0] |
| 1229 | self.append(str(self.read(len), 'utf-8', 'surrogatepass')) |
| 1230 | dispatch[SHORT_BINUNICODE[0]] = load_short_binunicode |
| 1231 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1232 | def load_tuple(self): |
| 1233 | k = self.marker() |
| 1234 | self.stack[k:] = [tuple(self.stack[k+1:])] |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1235 | dispatch[TUPLE[0]] = load_tuple |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1236 | |
| 1237 | def load_empty_tuple(self): |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 1238 | self.append(()) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1239 | dispatch[EMPTY_TUPLE[0]] = load_empty_tuple |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1240 | |
Guido van Rossum | 44f0ea5 | 2003-01-28 04:14:51 +0000 | [diff] [blame] | 1241 | def load_tuple1(self): |
| 1242 | self.stack[-1] = (self.stack[-1],) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1243 | dispatch[TUPLE1[0]] = load_tuple1 |
Guido van Rossum | 44f0ea5 | 2003-01-28 04:14:51 +0000 | [diff] [blame] | 1244 | |
| 1245 | def load_tuple2(self): |
| 1246 | self.stack[-2:] = [(self.stack[-2], self.stack[-1])] |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1247 | dispatch[TUPLE2[0]] = load_tuple2 |
Guido van Rossum | 44f0ea5 | 2003-01-28 04:14:51 +0000 | [diff] [blame] | 1248 | |
| 1249 | def load_tuple3(self): |
| 1250 | self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])] |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1251 | dispatch[TUPLE3[0]] = load_tuple3 |
Guido van Rossum | 44f0ea5 | 2003-01-28 04:14:51 +0000 | [diff] [blame] | 1252 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1253 | def load_empty_list(self): |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 1254 | self.append([]) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1255 | dispatch[EMPTY_LIST[0]] = load_empty_list |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1256 | |
| 1257 | def load_empty_dictionary(self): |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 1258 | self.append({}) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1259 | dispatch[EMPTY_DICT[0]] = load_empty_dictionary |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1260 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1261 | def load_empty_set(self): |
| 1262 | self.append(set()) |
| 1263 | dispatch[EMPTY_SET[0]] = load_empty_set |
| 1264 | |
| 1265 | def load_frozenset(self): |
| 1266 | k = self.marker() |
| 1267 | self.stack[k:] = [frozenset(self.stack[k+1:])] |
| 1268 | dispatch[FROZENSET[0]] = load_frozenset |
| 1269 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1270 | def load_list(self): |
| 1271 | k = self.marker() |
| 1272 | self.stack[k:] = [self.stack[k+1:]] |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1273 | dispatch[LIST[0]] = load_list |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1274 | |
| 1275 | def load_dict(self): |
| 1276 | k = self.marker() |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1277 | items = self.stack[k+1:] |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 1278 | d = {items[i]: items[i+1] |
| 1279 | for i in range(0, len(items), 2)} |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1280 | self.stack[k:] = [d] |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1281 | dispatch[DICT[0]] = load_dict |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1282 | |
Tim Peters | d01c1e9 | 2003-01-30 15:41:46 +0000 | [diff] [blame] | 1283 | # INST and OBJ differ only in how they get a class object. It's not |
| 1284 | # only sensible to do the rest in a common routine, the two routines |
| 1285 | # previously diverged and grew different bugs. |
| 1286 | # klass is the class to instantiate, and k points to the topmost mark |
| 1287 | # object, following which are the arguments for klass.__init__. |
| 1288 | def _instantiate(self, klass, k): |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1289 | args = tuple(self.stack[k+1:]) |
| 1290 | del self.stack[k:] |
Alexander Belopolsky | d92f040 | 2010-07-17 22:50:45 +0000 | [diff] [blame] | 1291 | if (args or not isinstance(klass, type) or |
| 1292 | hasattr(klass, "__getinitargs__")): |
Guido van Rossum | 743d17e | 1998-09-15 20:25:57 +0000 | [diff] [blame] | 1293 | try: |
Guido van Rossum | b26a97a | 2003-01-28 22:29:13 +0000 | [diff] [blame] | 1294 | value = klass(*args) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 1295 | except TypeError as err: |
Guido van Rossum | 26d95c3 | 2007-08-27 23:18:54 +0000 | [diff] [blame] | 1296 | raise TypeError("in constructor for %s: %s" % |
| 1297 | (klass.__name__, str(err)), sys.exc_info()[2]) |
Alexander Belopolsky | d92f040 | 2010-07-17 22:50:45 +0000 | [diff] [blame] | 1298 | else: |
| 1299 | value = klass.__new__(klass) |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1300 | self.append(value) |
Tim Peters | d01c1e9 | 2003-01-30 15:41:46 +0000 | [diff] [blame] | 1301 | |
| 1302 | def load_inst(self): |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 1303 | module = self.readline()[:-1].decode("ascii") |
| 1304 | name = self.readline()[:-1].decode("ascii") |
Tim Peters | d01c1e9 | 2003-01-30 15:41:46 +0000 | [diff] [blame] | 1305 | klass = self.find_class(module, name) |
| 1306 | self._instantiate(klass, self.marker()) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1307 | dispatch[INST[0]] = load_inst |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1308 | |
| 1309 | def load_obj(self): |
Tim Peters | d01c1e9 | 2003-01-30 15:41:46 +0000 | [diff] [blame] | 1310 | # Stack is ... markobject classobject arg1 arg2 ... |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1311 | k = self.marker() |
Tim Peters | d01c1e9 | 2003-01-30 15:41:46 +0000 | [diff] [blame] | 1312 | klass = self.stack.pop(k+1) |
| 1313 | self._instantiate(klass, k) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1314 | dispatch[OBJ[0]] = load_obj |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1315 | |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 1316 | def load_newobj(self): |
| 1317 | args = self.stack.pop() |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1318 | cls = self.stack.pop() |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 1319 | obj = cls.__new__(cls, *args) |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1320 | self.append(obj) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1321 | dispatch[NEWOBJ[0]] = load_newobj |
Guido van Rossum | 3a41c61 | 2003-01-28 15:10:22 +0000 | [diff] [blame] | 1322 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1323 | def load_newobj_ex(self): |
| 1324 | kwargs = self.stack.pop() |
| 1325 | args = self.stack.pop() |
| 1326 | cls = self.stack.pop() |
| 1327 | obj = cls.__new__(cls, *args, **kwargs) |
| 1328 | self.append(obj) |
| 1329 | dispatch[NEWOBJ_EX[0]] = load_newobj_ex |
| 1330 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1331 | def load_global(self): |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 1332 | module = self.readline()[:-1].decode("utf-8") |
| 1333 | name = self.readline()[:-1].decode("utf-8") |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1334 | klass = self.find_class(module, name) |
| 1335 | self.append(klass) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1336 | dispatch[GLOBAL[0]] = load_global |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1337 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1338 | def load_stack_global(self): |
| 1339 | name = self.stack.pop() |
| 1340 | module = self.stack.pop() |
| 1341 | if type(name) is not str or type(module) is not str: |
| 1342 | raise UnpicklingError("STACK_GLOBAL requires str") |
| 1343 | self.append(self.find_class(module, name)) |
| 1344 | dispatch[STACK_GLOBAL[0]] = load_stack_global |
| 1345 | |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 1346 | def load_ext1(self): |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 1347 | code = self.read(1)[0] |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 1348 | self.get_extension(code) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1349 | dispatch[EXT1[0]] = load_ext1 |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 1350 | |
| 1351 | def load_ext2(self): |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 1352 | code, = unpack('<H', self.read(2)) |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 1353 | self.get_extension(code) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1354 | dispatch[EXT2[0]] = load_ext2 |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 1355 | |
| 1356 | def load_ext4(self): |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 1357 | code, = unpack('<i', self.read(4)) |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 1358 | self.get_extension(code) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1359 | dispatch[EXT4[0]] = load_ext4 |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 1360 | |
| 1361 | def get_extension(self, code): |
| 1362 | nil = [] |
Guido van Rossum | d4b920c | 2003-02-04 01:54:49 +0000 | [diff] [blame] | 1363 | obj = _extension_cache.get(code, nil) |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 1364 | if obj is not nil: |
| 1365 | self.append(obj) |
| 1366 | return |
Guido van Rossum | d4b920c | 2003-02-04 01:54:49 +0000 | [diff] [blame] | 1367 | key = _inverted_registry.get(code) |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 1368 | if not key: |
Antoine Pitrou | bf6ecf9 | 2012-11-24 20:40:21 +0100 | [diff] [blame] | 1369 | if code <= 0: # note that 0 is forbidden |
| 1370 | # Corrupt or hostile pickle. |
Alexandre Vassalotti | cc75717 | 2013-04-14 02:25:10 -0700 | [diff] [blame] | 1371 | raise UnpicklingError("EXT specifies code <= 0") |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 1372 | raise ValueError("unregistered extension code %d" % code) |
| 1373 | obj = self.find_class(*key) |
Guido van Rossum | d4b920c | 2003-02-04 01:54:49 +0000 | [diff] [blame] | 1374 | _extension_cache[code] = obj |
Guido van Rossum | 255f3ee | 2003-01-29 06:14:11 +0000 | [diff] [blame] | 1375 | self.append(obj) |
| 1376 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1377 | def find_class(self, module, name): |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 1378 | # Subclasses may override this. |
| 1379 | if self.proto < 3 and self.fix_imports: |
| 1380 | if (module, name) in _compat_pickle.NAME_MAPPING: |
| 1381 | module, name = _compat_pickle.NAME_MAPPING[(module, name)] |
Serhiy Storchaka | bfe1824 | 2015-03-31 13:12:37 +0300 | [diff] [blame] | 1382 | elif module in _compat_pickle.IMPORT_MAPPING: |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 1383 | module = _compat_pickle.IMPORT_MAPPING[module] |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 1384 | __import__(module, level=0) |
Serhiy Storchaka | 58e4134 | 2015-03-31 14:07:24 +0300 | [diff] [blame] | 1385 | if self.proto >= 4: |
| 1386 | return _getattribute(sys.modules[module], name)[0] |
| 1387 | else: |
| 1388 | return getattr(sys.modules[module], name) |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1389 | |
| 1390 | def load_reduce(self): |
| 1391 | stack = self.stack |
Guido van Rossum | b26a97a | 2003-01-28 22:29:13 +0000 | [diff] [blame] | 1392 | args = stack.pop() |
| 1393 | func = stack[-1] |
Serhiy Storchaka | a8d83f5 | 2015-12-01 00:39:25 +0200 | [diff] [blame] | 1394 | stack[-1] = func(*args) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1395 | dispatch[REDUCE[0]] = load_reduce |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 1396 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1397 | def load_pop(self): |
| 1398 | del self.stack[-1] |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1399 | dispatch[POP[0]] = load_pop |
Guido van Rossum | 7b5430f | 1995-03-04 22:25:21 +0000 | [diff] [blame] | 1400 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1401 | def load_pop_mark(self): |
| 1402 | k = self.marker() |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 1403 | del self.stack[k:] |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1404 | dispatch[POP_MARK[0]] = load_pop_mark |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 1405 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1406 | def load_dup(self): |
Guido van Rossum | b1062fc | 1998-03-31 17:00:46 +0000 | [diff] [blame] | 1407 | self.append(self.stack[-1]) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1408 | dispatch[DUP[0]] = load_dup |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 1409 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1410 | def load_get(self): |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 1411 | i = int(self.readline()[:-1]) |
| 1412 | self.append(self.memo[i]) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1413 | dispatch[GET[0]] = load_get |
Guido van Rossum | 7853647 | 1996-04-12 13:36:27 +0000 | [diff] [blame] | 1414 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1415 | def load_binget(self): |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 1416 | i = self.read(1)[0] |
| 1417 | self.append(self.memo[i]) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1418 | dispatch[BINGET[0]] = load_binget |
Guido van Rossum | 7853647 | 1996-04-12 13:36:27 +0000 | [diff] [blame] | 1419 | |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 1420 | def load_long_binget(self): |
Antoine Pitrou | bf6ecf9 | 2012-11-24 20:40:21 +0100 | [diff] [blame] | 1421 | i, = unpack('<I', self.read(4)) |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 1422 | self.append(self.memo[i]) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1423 | dispatch[LONG_BINGET[0]] = load_long_binget |
Guido van Rossum | 7853647 | 1996-04-12 13:36:27 +0000 | [diff] [blame] | 1424 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1425 | def load_put(self): |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 1426 | i = int(self.readline()[:-1]) |
Antoine Pitrou | 55549ec | 2011-08-30 00:27:10 +0200 | [diff] [blame] | 1427 | if i < 0: |
| 1428 | raise ValueError("negative PUT argument") |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 1429 | self.memo[i] = self.stack[-1] |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1430 | dispatch[PUT[0]] = load_put |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 1431 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1432 | def load_binput(self): |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 1433 | i = self.read(1)[0] |
Antoine Pitrou | 55549ec | 2011-08-30 00:27:10 +0200 | [diff] [blame] | 1434 | if i < 0: |
| 1435 | raise ValueError("negative BINPUT argument") |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 1436 | self.memo[i] = self.stack[-1] |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1437 | dispatch[BINPUT[0]] = load_binput |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 1438 | |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 1439 | def load_long_binput(self): |
Antoine Pitrou | bf6ecf9 | 2012-11-24 20:40:21 +0100 | [diff] [blame] | 1440 | i, = unpack('<I', self.read(4)) |
| 1441 | if i > maxsize: |
Antoine Pitrou | 55549ec | 2011-08-30 00:27:10 +0200 | [diff] [blame] | 1442 | raise ValueError("negative LONG_BINPUT argument") |
Alexandre Vassalotti | ca2d610 | 2008-06-12 18:26:05 +0000 | [diff] [blame] | 1443 | self.memo[i] = self.stack[-1] |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1444 | dispatch[LONG_BINPUT[0]] = load_long_binput |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 1445 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1446 | def load_memoize(self): |
| 1447 | memo = self.memo |
| 1448 | memo[len(memo)] = self.stack[-1] |
| 1449 | dispatch[MEMOIZE[0]] = load_memoize |
| 1450 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1451 | def load_append(self): |
| 1452 | stack = self.stack |
Raymond Hettinger | 46ac8eb | 2002-06-30 03:39:14 +0000 | [diff] [blame] | 1453 | value = stack.pop() |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1454 | list = stack[-1] |
| 1455 | list.append(value) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1456 | dispatch[APPEND[0]] = load_append |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 1457 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1458 | def load_appends(self): |
| 1459 | stack = self.stack |
| 1460 | mark = self.marker() |
Alexandre Vassalotti | 1f7492c | 2013-04-20 13:19:46 -0700 | [diff] [blame] | 1461 | list_obj = stack[mark - 1] |
| 1462 | items = stack[mark + 1:] |
| 1463 | if isinstance(list_obj, list): |
| 1464 | list_obj.extend(items) |
| 1465 | else: |
| 1466 | append = list_obj.append |
| 1467 | for item in items: |
| 1468 | append(item) |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1469 | del stack[mark:] |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1470 | dispatch[APPENDS[0]] = load_appends |
Tim Peters | 2344fae | 2001-01-15 00:50:52 +0000 | [diff] [blame] | 1471 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1472 | def load_setitem(self): |
| 1473 | stack = self.stack |
Raymond Hettinger | 46ac8eb | 2002-06-30 03:39:14 +0000 | [diff] [blame] | 1474 | value = stack.pop() |
| 1475 | key = stack.pop() |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1476 | dict = stack[-1] |
| 1477 | dict[key] = value |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1478 | dispatch[SETITEM[0]] = load_setitem |
Guido van Rossum | 0c891ce | 1995-03-14 15:09:05 +0000 | [diff] [blame] | 1479 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1480 | def load_setitems(self): |
| 1481 | stack = self.stack |
| 1482 | mark = self.marker() |
| 1483 | dict = stack[mark - 1] |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 1484 | for i in range(mark + 1, len(stack), 2): |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1485 | dict[stack[i]] = stack[i + 1] |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 1486 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1487 | del stack[mark:] |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1488 | dispatch[SETITEMS[0]] = load_setitems |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 1489 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1490 | def load_additems(self): |
| 1491 | stack = self.stack |
| 1492 | mark = self.marker() |
| 1493 | set_obj = stack[mark - 1] |
| 1494 | items = stack[mark + 1:] |
| 1495 | if isinstance(set_obj, set): |
| 1496 | set_obj.update(items) |
| 1497 | else: |
| 1498 | add = set_obj.add |
| 1499 | for item in items: |
| 1500 | add(item) |
| 1501 | del stack[mark:] |
| 1502 | dispatch[ADDITEMS[0]] = load_additems |
| 1503 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1504 | def load_build(self): |
| 1505 | stack = self.stack |
Guido van Rossum | ac5b5d2 | 2003-01-28 22:01:16 +0000 | [diff] [blame] | 1506 | state = stack.pop() |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1507 | inst = stack[-1] |
Guido van Rossum | ac5b5d2 | 2003-01-28 22:01:16 +0000 | [diff] [blame] | 1508 | setstate = getattr(inst, "__setstate__", None) |
Serhiy Storchaka | a3e32c9 | 2013-04-14 13:37:02 +0300 | [diff] [blame] | 1509 | if setstate is not None: |
Guido van Rossum | ac5b5d2 | 2003-01-28 22:01:16 +0000 | [diff] [blame] | 1510 | setstate(state) |
| 1511 | return |
| 1512 | slotstate = None |
| 1513 | if isinstance(state, tuple) and len(state) == 2: |
| 1514 | state, slotstate = state |
| 1515 | if state: |
Alexandre Vassalotti | ebfecfd | 2009-05-25 18:50:33 +0000 | [diff] [blame] | 1516 | inst_dict = inst.__dict__ |
Antoine Pitrou | a9f48a0 | 2009-05-02 21:41:14 +0000 | [diff] [blame] | 1517 | intern = sys.intern |
Alexandre Vassalotti | ebfecfd | 2009-05-25 18:50:33 +0000 | [diff] [blame] | 1518 | for k, v in state.items(): |
| 1519 | if type(k) is str: |
| 1520 | inst_dict[intern(k)] = v |
| 1521 | else: |
| 1522 | inst_dict[k] = v |
Guido van Rossum | ac5b5d2 | 2003-01-28 22:01:16 +0000 | [diff] [blame] | 1523 | if slotstate: |
| 1524 | for k, v in slotstate.items(): |
| 1525 | setattr(inst, k, v) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1526 | dispatch[BUILD[0]] = load_build |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 1527 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1528 | def load_mark(self): |
| 1529 | self.append(self.mark) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1530 | dispatch[MARK[0]] = load_mark |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 1531 | |
Guido van Rossum | b72cf2d | 1997-04-09 17:32:51 +0000 | [diff] [blame] | 1532 | def load_stop(self): |
Raymond Hettinger | 46ac8eb | 2002-06-30 03:39:14 +0000 | [diff] [blame] | 1533 | value = self.stack.pop() |
Guido van Rossum | ff87174 | 2000-12-13 18:11:56 +0000 | [diff] [blame] | 1534 | raise _Stop(value) |
Guido van Rossum | 2e6a4b3 | 2007-05-04 19:56:22 +0000 | [diff] [blame] | 1535 | dispatch[STOP[0]] = load_stop |
Guido van Rossum | a48061a | 1995-01-10 00:31:14 +0000 | [diff] [blame] | 1536 | |
Guido van Rossum | d6c9e63 | 2003-01-28 03:49:52 +0000 | [diff] [blame] | 1537 | |
Guido van Rossum | 0c891ce | 1995-03-14 15:09:05 +0000 | [diff] [blame] | 1538 | # Shorthands |
| 1539 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1540 | def _dump(obj, file, protocol=None, *, fix_imports=True): |
| 1541 | _Pickler(file, protocol, fix_imports=fix_imports).dump(obj) |
Guido van Rossum | 0c891ce | 1995-03-14 15:09:05 +0000 | [diff] [blame] | 1542 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1543 | def _dumps(obj, protocol=None, *, fix_imports=True): |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 1544 | f = io.BytesIO() |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1545 | _Pickler(f, protocol, fix_imports=fix_imports).dump(obj) |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 1546 | res = f.getvalue() |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 1547 | assert isinstance(res, bytes_types) |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 1548 | return res |
Guido van Rossum | 0c891ce | 1995-03-14 15:09:05 +0000 | [diff] [blame] | 1549 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1550 | def _load(file, *, fix_imports=True, encoding="ASCII", errors="strict"): |
| 1551 | return _Unpickler(file, fix_imports=fix_imports, |
Antoine Pitrou | d9dfaa9 | 2009-06-04 20:32:06 +0000 | [diff] [blame] | 1552 | encoding=encoding, errors=errors).load() |
Guido van Rossum | 0c891ce | 1995-03-14 15:09:05 +0000 | [diff] [blame] | 1553 | |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1554 | def _loads(s, *, fix_imports=True, encoding="ASCII", errors="strict"): |
Guido van Rossum | cfe5f20 | 2007-05-08 21:26:54 +0000 | [diff] [blame] | 1555 | if isinstance(s, str): |
| 1556 | raise TypeError("Can't load pickle from unicode string") |
| 1557 | file = io.BytesIO(s) |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1558 | return _Unpickler(file, fix_imports=fix_imports, |
| 1559 | encoding=encoding, errors=errors).load() |
Guido van Rossum | d6c9e63 | 2003-01-28 03:49:52 +0000 | [diff] [blame] | 1560 | |
Antoine Pitrou | ea99c5c | 2010-09-09 18:33:21 +0000 | [diff] [blame] | 1561 | # Use the faster _pickle if possible |
| 1562 | try: |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1563 | from _pickle import ( |
| 1564 | PickleError, |
| 1565 | PicklingError, |
| 1566 | UnpicklingError, |
| 1567 | Pickler, |
| 1568 | Unpickler, |
| 1569 | dump, |
| 1570 | dumps, |
| 1571 | load, |
| 1572 | loads |
| 1573 | ) |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 1574 | except ImportError: |
Antoine Pitrou | ea99c5c | 2010-09-09 18:33:21 +0000 | [diff] [blame] | 1575 | Pickler, Unpickler = _Pickler, _Unpickler |
Antoine Pitrou | c9dc4a2 | 2013-11-23 18:59:12 +0100 | [diff] [blame] | 1576 | dump, dumps, load, loads = _dump, _dumps, _load, _loads |
Antoine Pitrou | ea99c5c | 2010-09-09 18:33:21 +0000 | [diff] [blame] | 1577 | |
Guido van Rossum | d6c9e63 | 2003-01-28 03:49:52 +0000 | [diff] [blame] | 1578 | # Doctest |
Guido van Rossum | d6c9e63 | 2003-01-28 03:49:52 +0000 | [diff] [blame] | 1579 | def _test(): |
| 1580 | import doctest |
| 1581 | return doctest.testmod() |
| 1582 | |
| 1583 | if __name__ == "__main__": |
Florent Xicluna | 54540ec | 2011-11-04 08:29:17 +0100 | [diff] [blame] | 1584 | import argparse |
Alexander Belopolsky | 455f7bd | 2010-07-27 23:02:38 +0000 | [diff] [blame] | 1585 | parser = argparse.ArgumentParser( |
| 1586 | description='display contents of the pickle files') |
| 1587 | parser.add_argument( |
| 1588 | 'pickle_file', type=argparse.FileType('br'), |
| 1589 | nargs='*', help='the pickle file') |
| 1590 | parser.add_argument( |
| 1591 | '-t', '--test', action='store_true', |
| 1592 | help='run self-test suite') |
| 1593 | parser.add_argument( |
| 1594 | '-v', action='store_true', |
| 1595 | help='run verbosely; only affects self-test run') |
| 1596 | args = parser.parse_args() |
| 1597 | if args.test: |
| 1598 | _test() |
| 1599 | else: |
| 1600 | if not args.pickle_file: |
| 1601 | parser.print_help() |
| 1602 | else: |
| 1603 | import pprint |
| 1604 | for f in args.pickle_file: |
| 1605 | obj = load(f) |
| 1606 | pprint.pprint(obj) |