| 1 |
"""Create portable serialized representations of Python objects. |
| 2 |
|
| 3 |
See module copyreg for a mechanism for registering custom picklers. |
| 4 |
See module pickletools source for extensive comments. |
| 5 |
|
| 6 |
Classes: |
| 7 |
|
| 8 |
Pickler |
| 9 |
Unpickler |
| 10 |
|
| 11 |
Functions: |
| 12 |
|
| 13 |
dump(object, file) |
| 14 |
dumps(object) -> string |
| 15 |
load(file) -> object |
| 16 |
loads(bytes) -> object |
| 17 |
|
| 18 |
Misc variables: |
| 19 |
|
| 20 |
__version__ |
| 21 |
format_version |
| 22 |
compatible_formats |
| 23 |
|
| 24 |
""" |
| 25 |
|
| 26 |
from types import FunctionType |
| 27 |
from copyreg import dispatch_table |
| 28 |
from copyreg import _extension_registry, _inverted_registry, _extension_cache |
| 29 |
from itertools import islice |
| 30 |
from functools import partial |
| 31 |
import sys |
| 32 |
from sys import maxsize |
| 33 |
from struct import pack, unpack |
| 34 |
import re |
| 35 |
import io |
| 36 |
import codecs |
| 37 |
import _compat_pickle |
| 38 |
try: |
| 39 |
from __pypy__.builders import BytesBuilder |
| 40 |
from __pypy__ import identity_dict |
| 41 |
except ImportError: |
| 42 |
class BytesBuilder(): |
| 43 |
def __init__(self): |
| 44 |
self.builder = io.BytesIO() |
| 45 |
def __len__(self): |
| 46 |
return self.builder.tell() |
| 47 |
def build(self): |
| 48 |
return self.builder.getbuffer() |
| 49 |
def append(self, data): |
| 50 |
self.builder.write(data) |
| 51 |
|
| 52 |
__all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler", |
| 53 |
"Unpickler", "dump", "dumps", "load", "loads"] |
| 54 |
|
| 55 |
try: |
| 56 |
from __pypy__ import PickleBuffer |
| 57 |
__all__.append("PickleBuffer") |
| 58 |
_HAVE_PICKLE_BUFFER = True |
| 59 |
except ImportError: |
| 60 |
_HAVE_PICKLE_BUFFER = False |
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
bytes_types = (bytes, bytearray) |
| 65 |
|
| 66 |
|
| 67 |
format_version = "4.0" |
| 68 |
compatible_formats = ["1.0", |
| 69 |
"1.1", |
| 70 |
"1.2", |
| 71 |
"1.3", |
| 72 |
"2.0", |
| 73 |
"3.0", |
| 74 |
"4.0", |
| 75 |
"5.0", |
| 76 |
] |
| 77 |
|
| 78 |
|
| 79 |
HIGHEST_PROTOCOL = 5 |
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
DEFAULT_PROTOCOL = 4 |
| 85 |
|
| 86 |
class PickleError(Exception): |
| 87 |
"""A common base class for the other pickling exceptions.""" |
| 88 |
pass |
| 89 |
|
| 90 |
class PicklingError(PickleError): |
| 91 |
"""This exception is raised when an unpicklable object is passed to the |
| 92 |
dump() method. |
| 93 |
|
| 94 |
""" |
| 95 |
pass |
| 96 |
|
| 97 |
class UnpicklingError(PickleError): |
| 98 |
"""This exception is raised when there is a problem unpickling an object, |
| 99 |
such as a security violation. |
| 100 |
|
| 101 |
Note that other exceptions may also be raised during unpickling, including |
| 102 |
(but not necessarily limited to) AttributeError, EOFError, ImportError, |
| 103 |
and IndexError. |
| 104 |
|
| 105 |
""" |
| 106 |
pass |
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
class _Stop(Exception): |
| 111 |
def __init__(self, value): |
| 112 |
self.value = value |
| 113 |
|
| 114 |
|
| 115 |
try: |
| 116 |
from org.python.core import PyStringMap |
| 117 |
except ImportError: |
| 118 |
PyStringMap = None |
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
MARK = b'(' |
| 125 |
STOP = b'.' |
| 126 |
POP = b'0' |
| 127 |
POP_MARK = b'1' |
| 128 |
DUP = b'2' |
| 129 |
FLOAT = b'F' |
| 130 |
INT = b'I' |
| 131 |
BININT = b'J' |
| 132 |
BININT1 = b'K' |
| 133 |
LONG = b'L' |
| 134 |
BININT2 = b'M' |
| 135 |
NONE = b'N' |
| 136 |
PERSID = b'P' |
| 137 |
BINPERSID = b'Q' |
| 138 |
REDUCE = b'R' |
| 139 |
STRING = b'S' |
| 140 |
BINSTRING = b'T' |
| 141 |
SHORT_BINSTRING= b'U' |
| 142 |
UNICODE = b'V' |
| 143 |
BINUNICODE = b'X' |
| 144 |
APPEND = b'a' |
| 145 |
BUILD = b'b' |
| 146 |
GLOBAL = b'c' |
| 147 |
DICT = b'd' |
| 148 |
EMPTY_DICT = b'}' |
| 149 |
APPENDS = b'e' |
| 150 |
GET = b'g' |
| 151 |
BINGET = b'h' |
| 152 |
INST = b'i' |
| 153 |
LONG_BINGET = b'j' |
| 154 |
LIST = b'l' |
| 155 |
EMPTY_LIST = b']' |
| 156 |
OBJ = b'o' |
| 157 |
PUT = b'p' |
| 158 |
BINPUT = b'q' |
| 159 |
LONG_BINPUT = b'r' |
| 160 |
SETITEM = b's' |
| 161 |
TUPLE = b't' |
| 162 |
EMPTY_TUPLE = b')' |
| 163 |
SETITEMS = b'u' |
| 164 |
BINFLOAT = b'G' |
| 165 |
|
| 166 |
TRUE = b'I01\n' |
| 167 |
FALSE = b'I00\n' |
| 168 |
|
| 169 |
|
| 170 |
|
| 171 |
PROTO = b'\x80' |
| 172 |
NEWOBJ = b'\x81' |
| 173 |
EXT1 = b'\x82' |
| 174 |
EXT2 = b'\x83' |
| 175 |
EXT4 = b'\x84' |
| 176 |
TUPLE1 = b'\x85' |
| 177 |
TUPLE2 = b'\x86' |
| 178 |
TUPLE3 = b'\x87' |
| 179 |
NEWTRUE = b'\x88' |
| 180 |
NEWFALSE = b'\x89' |
| 181 |
LONG1 = b'\x8a' |
| 182 |
LONG4 = b'\x8b' |
| 183 |
|
| 184 |
_tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3] |
| 185 |
|
| 186 |
|
| 187 |
|
| 188 |
BINBYTES = b'B' |
| 189 |
SHORT_BINBYTES = b'C' |
| 190 |
|
| 191 |
|
| 192 |
|
| 193 |
SHORT_BINUNICODE = b'\x8c' |
| 194 |
BINUNICODE8 = b'\x8d' |
| 195 |
BINBYTES8 = b'\x8e' |
| 196 |
EMPTY_SET = b'\x8f' |
| 197 |
ADDITEMS = b'\x90' |
| 198 |
FROZENSET = b'\x91' |
| 199 |
NEWOBJ_EX = b'\x92' |
| 200 |
STACK_GLOBAL = b'\x93' |
| 201 |
MEMOIZE = b'\x94' |
| 202 |
FRAME = b'\x95' |
| 203 |
|
| 204 |
|
| 205 |
|
| 206 |
BYTEARRAY8 = b'\x96' |
| 207 |
NEXT_BUFFER = b'\x97' |
| 208 |
READONLY_BUFFER = b'\x98' |
| 209 |
|
| 210 |
__all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$", x)]) |
| 211 |
|
| 212 |
|
| 213 |
class _Framer: |
| 214 |
|
| 215 |
_FRAME_SIZE_MIN = 4 |
| 216 |
_FRAME_SIZE_TARGET = 64 * 1024 |
| 217 |
|
| 218 |
def __init__(self, file_write): |
| 219 |
self.file_write = file_write |
| 220 |
self.current_frame = None |
| 221 |
|
| 222 |
def start_framing(self): |
| 223 |
self.current_frame = BytesBuilder() |
| 224 |
|
| 225 |
def end_framing(self): |
| 226 |
if self.current_frame and len(self.current_frame) > 0: |
| 227 |
self.commit_frame(force=True) |
| 228 |
self.current_frame = None |
| 229 |
|
| 230 |
def commit_frame(self, force=False): |
| 231 |
if self.current_frame is not None: |
| 232 |
f = self.current_frame |
| 233 |
if len(f) >= self._FRAME_SIZE_TARGET or force: |
| 234 |
data = f.build() |
| 235 |
write = self.file_write |
| 236 |
if len(data) >= self._FRAME_SIZE_MIN: |
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
|
| 241 |
write(FRAME + pack("<Q", len(data))) |
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
write(data) |
| 247 |
|
| 248 |
|
| 249 |
|
| 250 |
|
| 251 |
|
| 252 |
self.current_frame = BytesBuilder() |
| 253 |
|
| 254 |
def write(self, data): |
| 255 |
if self.current_frame is not None: |
| 256 |
self.current_frame.append(data) |
| 257 |
return len(data) |
| 258 |
else: |
| 259 |
return self.file_write(data) |
| 260 |
|
| 261 |
def write_large_bytes(self, header, payload): |
| 262 |
write = self.file_write |
| 263 |
if self.current_frame: |
| 264 |
|
| 265 |
self.commit_frame(force=True) |
| 266 |
|
| 267 |
|
| 268 |
|
| 269 |
|
| 270 |
|
| 271 |
|
| 272 |
|
| 273 |
write(header) |
| 274 |
write(payload) |
| 275 |
|
| 276 |
|
| 277 |
class _Unframer: |
| 278 |
|
| 279 |
def __init__(self, file_read, file_readline, file_tell=None): |
| 280 |
self.file_read = file_read |
| 281 |
self.file_readline = file_readline |
| 282 |
self.current_frame = None |
| 283 |
|
| 284 |
def readinto(self, buf): |
| 285 |
if self.current_frame: |
| 286 |
n = self.current_frame.readinto(buf) |
| 287 |
if n == 0 and len(buf) != 0: |
| 288 |
self.current_frame = None |
| 289 |
n = len(buf) |
| 290 |
buf[:] = self.file_read(n) |
| 291 |
return n |
| 292 |
if n < len(buf): |
| 293 |
raise UnpicklingError( |
| 294 |
"pickle exhausted before end of frame") |
| 295 |
return n |
| 296 |
else: |
| 297 |
n = len(buf) |
| 298 |
buf[:] = self.file_read(n) |
| 299 |
return n |
| 300 |
|
| 301 |
def read(self, n): |
| 302 |
if self.current_frame: |
| 303 |
data = self.current_frame.read(n) |
| 304 |
if not data and n != 0: |
| 305 |
self.current_frame = None |
| 306 |
return self.file_read(n) |
| 307 |
if len(data) < n: |
| 308 |
raise UnpicklingError( |
| 309 |
"pickle exhausted before end of frame") |
| 310 |
return data |
| 311 |
else: |
| 312 |
return self.file_read(n) |
| 313 |
|
| 314 |
def readline(self): |
| 315 |
if self.current_frame: |
| 316 |
data = self.current_frame.readline() |
| 317 |
if not data: |
| 318 |
self.current_frame = None |
| 319 |
return self.file_readline() |
| 320 |
if data[-1] != b'\n'[0]: |
| 321 |
raise UnpicklingError( |
| 322 |
"pickle exhausted before end of frame") |
| 323 |
return data |
| 324 |
else: |
| 325 |
return self.file_readline() |
| 326 |
|
| 327 |
def load_frame(self, frame_size): |
| 328 |
if self.current_frame and self.current_frame.read() != b'': |
| 329 |
raise UnpicklingError( |
| 330 |
"beginning of a new frame before end of current frame") |
| 331 |
self.current_frame = io.BytesIO(self.file_read(frame_size)) |
| 332 |
|
| 333 |
|
| 334 |
|
| 335 |
|
| 336 |
def _getattribute(obj, name): |
| 337 |
for subpath in name.split('.'): |
| 338 |
if subpath == '<locals>': |
| 339 |
raise AttributeError("Can't get local attribute {!r} on {!r}" |
| 340 |
.format(name, obj)) |
| 341 |
try: |
| 342 |
parent = obj |
| 343 |
obj = getattr(obj, subpath) |
| 344 |
except AttributeError: |
| 345 |
raise AttributeError("Can't get attribute {!r} on {!r}" |
| 346 |
.format(name, obj)) from None |
| 347 |
return obj, parent |
| 348 |
|
| 349 |
def whichmodule(obj, name): |
| 350 |
"""Find the module an object belong to.""" |
| 351 |
module_name = getattr(obj, '__module__', None) |
| 352 |
if module_name is not None: |
| 353 |
return module_name |
| 354 |
|
| 355 |
|
| 356 |
for module_name, module in sys.modules.copy().items(): |
| 357 |
if (module_name == '__main__' |
| 358 |
or module_name == '__mp_main__' |
| 359 |
or module is None): |
| 360 |
continue |
| 361 |
try: |
| 362 |
if _getattribute(module, name)[0] is obj: |
| 363 |
return module_name |
| 364 |
except AttributeError: |
| 365 |
pass |
| 366 |
return '__main__' |
| 367 |
|
| 368 |
def encode_long(x): |
| 369 |
r"""Encode a long to a two's complement little-endian binary string. |
| 370 |
Note that 0 is a special case, returning an empty string, to save a |
| 371 |
byte in the LONG1 pickling context. |
| 372 |
|
| 373 |
>>> encode_long(0) |
| 374 |
b'' |
| 375 |
>>> encode_long(255) |
| 376 |
b'\xff\x00' |
| 377 |
>>> encode_long(32767) |
| 378 |
b'\xff\x7f' |
| 379 |
>>> encode_long(-256) |
| 380 |
b'\x00\xff' |
| 381 |
>>> encode_long(-32768) |
| 382 |
b'\x00\x80' |
| 383 |
>>> encode_long(-128) |
| 384 |
b'\x80' |
| 385 |
>>> encode_long(127) |
| 386 |
b'\x7f' |
| 387 |
>>> |
| 388 |
""" |
| 389 |
if x == 0: |
| 390 |
return b'' |
| 391 |
nbytes = (x.bit_length() >> 3) + 1 |
| 392 |
result = x.to_bytes(nbytes, byteorder='little', signed=True) |
| 393 |
if x < 0 and nbytes > 1: |
| 394 |
if result[-1] == 0xff and (result[-2] & 0x80) != 0: |
| 395 |
result = result[:-1] |
| 396 |
return result |
| 397 |
|
| 398 |
def decode_long(data): |
| 399 |
r"""Decode a long from a two's complement little-endian binary string. |
| 400 |
|
| 401 |
>>> decode_long(b'') |
| 402 |
0 |
| 403 |
>>> decode_long(b"\xff\x00") |
| 404 |
255 |
| 405 |
>>> decode_long(b"\xff\x7f") |
| 406 |
32767 |
| 407 |
>>> decode_long(b"\x00\xff") |
| 408 |
-256 |
| 409 |
>>> decode_long(b"\x00\x80") |
| 410 |
-32768 |
| 411 |
>>> decode_long(b"\x80") |
| 412 |
-128 |
| 413 |
>>> decode_long(b"\x7f") |
| 414 |
127 |
| 415 |
""" |
| 416 |
return int.from_bytes(data, byteorder='little', signed=True) |
| 417 |
|
| 418 |
|
| 419 |
|
| 420 |
|
| 421 |
class _Pickler: |
| 422 |
|
| 423 |
def __init__(self, file, protocol=None, *, fix_imports=True, |
| 424 |
buffer_callback=None): |
| 425 |
"""This takes a binary file for writing a pickle data stream. |
| 426 |
|
| 427 |
The optional *protocol* argument tells the pickler to use the |
| 428 |
given protocol; supported protocols are 0, 1, 2, 3, 4 and 5. |
| 429 |
The default protocol is 4. It was introduced in Python 3.4, and |
| 430 |
is incompatible with previous versions. |
| 431 |
|
| 432 |
Specifying a negative protocol version selects the highest |
| 433 |
protocol version supported. The higher the protocol used, the |
| 434 |
more recent the version of Python needed to read the pickle |
| 435 |
produced. |
| 436 |
|
| 437 |
The *file* argument must have a write() method that accepts a |
| 438 |
single bytes argument. It can thus be a file object opened for |
| 439 |
binary writing, an io.BytesIO instance, or any other custom |
| 440 |
object that meets this interface. |
| 441 |
|
| 442 |
If *fix_imports* is True and *protocol* is less than 3, pickle |
| 443 |
will try to map the new Python 3 names to the old module names |
| 444 |
used in Python 2, so that the pickle data stream is readable |
| 445 |
with Python 2. |
| 446 |
|
| 447 |
If *buffer_callback* is None (the default), buffer views are |
| 448 |
serialized into *file* as part of the pickle stream. |
| 449 |
|
| 450 |
If *buffer_callback* is not None, then it can be called any number |
| 451 |
of times with a buffer view. If the callback returns a false value |
| 452 |
(such as None), the given buffer is out-of-band; otherwise the |
| 453 |
buffer is serialized in-band, i.e. inside the pickle stream. |
| 454 |
|
| 455 |
It is an error if *buffer_callback* is not None and *protocol* |
| 456 |
is None or smaller than 5. |
| 457 |
""" |
| 458 |
if protocol is None: |
| 459 |
protocol = DEFAULT_PROTOCOL |
| 460 |
if protocol < 0: |
| 461 |
protocol = HIGHEST_PROTOCOL |
| 462 |
elif not 0 <= protocol <= HIGHEST_PROTOCOL: |
| 463 |
raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL) |
| 464 |
if buffer_callback is not None and protocol < 5: |
| 465 |
raise ValueError("buffer_callback needs protocol >= 5") |
| 466 |
self._buffer_callback = buffer_callback |
| 467 |
try: |
| 468 |
self._file_write = file.write |
| 469 |
except AttributeError: |
| 470 |
raise TypeError("file must have a 'write' attribute") |
| 471 |
self.framer = _Framer(self._file_write) |
| 472 |
self.memo = identity_dict() |
| 473 |
self.proto = int(protocol) |
| 474 |
self.bin = protocol >= 1 |
| 475 |
self.fast = 0 |
| 476 |
self.fix_imports = fix_imports and protocol < 3 |
| 477 |
|
| 478 |
def write(self, arg): |
| 479 |
return self.framer.write(arg) |
| 480 |
|
| 481 |
def _write_large_bytes(self, arg0, arg1): |
| 482 |
return self.framer.write_large_bytes(arg0, arg1) |
| 483 |
|
| 484 |
def clear_memo(self): |
| 485 |
"""Clears the pickler's "memo". |
| 486 |
|
| 487 |
The memo is the data structure that remembers which objects the |
| 488 |
pickler has already seen, so that shared or recursive objects |
| 489 |
are pickled by reference and not by value. This method is |
| 490 |
useful when re-using picklers. |
| 491 |
""" |
| 492 |
self.memo.clear() |
| 493 |
|
| 494 |
def dump(self, obj): |
| 495 |
"""Write a pickled representation of obj to the open file.""" |
| 496 |
|
| 497 |
|
| 498 |
if not hasattr(self, "_file_write"): |
| 499 |
raise PicklingError("Pickler.__init__() was not called by " |
| 500 |
"%s.__init__()" % (self.__class__.__name__,)) |
| 501 |
if self.proto >= 2: |
| 502 |
self.write(PROTO + pack("<B", self.proto)) |
| 503 |
if self.proto >= 4: |
| 504 |
self.framer.start_framing() |
| 505 |
self.save(obj) |
| 506 |
self.write(STOP) |
| 507 |
self.framer.end_framing() |
| 508 |
|
| 509 |
def memoize(self, obj): |
| 510 |
"""Store an object in the memo.""" |
| 511 |
|
| 512 |
|
| 513 |
|
| 514 |
|
| 515 |
|
| 516 |
|
| 517 |
|
| 518 |
|
| 519 |
|
| 520 |
|
| 521 |
|
| 522 |
|
| 523 |
|
| 524 |
if self.fast: |
| 525 |
return |
| 526 |
assert obj not in self.memo |
| 527 |
idx = len(self.memo) |
| 528 |
self.write(self.put(idx)) |
| 529 |
self.memo[obj] = idx, obj |
| 530 |
|
| 531 |
|
| 532 |
def put(self, idx): |
| 533 |
if self.proto >= 4: |
| 534 |
return MEMOIZE |
| 535 |
elif self.bin: |
| 536 |
if idx < 256: |
| 537 |
return BINPUT + pack("<B", idx) |
| 538 |
else: |
| 539 |
return LONG_BINPUT + pack("<I", idx) |
| 540 |
else: |
| 541 |
return PUT + repr(idx).encode("ascii") + b'\n' |
| 542 |
|
| 543 |
|
| 544 |
def get(self, i): |
| 545 |
if self.bin: |
| 546 |
if i < 256: |
| 547 |
return BINGET + pack("<B", i) |
| 548 |
else: |
| 549 |
return LONG_BINGET + pack("<I", i) |
| 550 |
|
| 551 |
return GET + repr(i).encode("ascii") + b'\n' |
| 552 |
|
| 553 |
def save(self, obj, save_persistent_id=True): |
| 554 |
self.framer.commit_frame() |
| 555 |
|
| 556 |
|
| 557 |
pid = self.persistent_id(obj) |
| 558 |
if pid is not None and save_persistent_id: |
| 559 |
self.save_pers(pid) |
| 560 |
return |
| 561 |
|
| 562 |
|
| 563 |
x = self.memo.get(obj) |
| 564 |
if x is not None: |
| 565 |
self.write(self.get(x[0])) |
| 566 |
return |
| 567 |
|
| 568 |
rv = NotImplemented |
| 569 |
reduce = getattr(self, "reducer_override", None) |
| 570 |
if reduce is not None: |
| 571 |
rv = reduce(obj) |
| 572 |
|
| 573 |
if rv is NotImplemented: |
| 574 |
|
| 575 |
t = type(obj) |
| 576 |
f = self.dispatch.get(t) |
| 577 |
if f is not None: |
| 578 |
f(self, obj) |
| 579 |
return |
| 580 |
|
| 581 |
|
| 582 |
|
| 583 |
reduce = getattr(self, 'dispatch_table', dispatch_table).get(t) |
| 584 |
if reduce is not None: |
| 585 |
rv = reduce(obj) |
| 586 |
else: |
| 587 |
|
| 588 |
|
| 589 |
if issubclass(t, type): |
| 590 |
self.save_global(obj) |
| 591 |
return |
| 592 |
|
| 593 |
|
| 594 |
reduce = getattr(obj, "__reduce_ex__", None) |
| 595 |
if reduce is not None: |
| 596 |
rv = reduce(self.proto) |
| 597 |
else: |
| 598 |
reduce = getattr(obj, "__reduce__", None) |
| 599 |
if reduce is not None: |
| 600 |
rv = reduce() |
| 601 |
else: |
| 602 |
raise PicklingError("Can't pickle %r object: %r" % |
| 603 |
(t.__name__, obj)) |
| 604 |
|
| 605 |
|
| 606 |
if isinstance(rv, str): |
| 607 |
self.save_global(obj, rv) |
| 608 |
return |
| 609 |
|
| 610 |
|
| 611 |
if not isinstance(rv, tuple): |
| 612 |
raise PicklingError("%s must return string or tuple" % reduce) |
| 613 |
|
| 614 |
|
| 615 |
l = len(rv) |
| 616 |
if not (2 <= l <= 6): |
| 617 |
raise PicklingError("Tuple returned by %s must have " |
| 618 |
"two to six elements" % reduce) |
| 619 |
|
| 620 |
|
| 621 |
self.save_reduce(obj=obj, *rv) |
| 622 |
|
| 623 |
def persistent_id(self, obj): |
| 624 |
|
| 625 |
return None |
| 626 |
|
| 627 |
def save_pers(self, pid): |
| 628 |
|
| 629 |
if self.bin: |
| 630 |
self.save(pid, save_persistent_id=False) |
| 631 |
self.write(BINPERSID) |
| 632 |
else: |
| 633 |
try: |
| 634 |
self.write(PERSID + str(pid).encode("ascii") + b'\n') |
| 635 |
except UnicodeEncodeError: |
| 636 |
raise PicklingError( |
| 637 |
"persistent IDs in protocol 0 must be ASCII strings") |
| 638 |
|
| 639 |
def save_reduce(self, func, args, state=None, listitems=None, |
| 640 |
dictitems=None, state_setter=None, *, obj=None): |
| 641 |
|
| 642 |
|
| 643 |
if not isinstance(args, tuple): |
| 644 |
raise PicklingError("args from save_reduce() must be a tuple") |
| 645 |
if not callable(func): |
| 646 |
raise PicklingError("func from save_reduce() must be callable") |
| 647 |
|
| 648 |
save = self.save |
| 649 |
write = self.write |
| 650 |
|
| 651 |
func_name = getattr(func, "__name__", "") |
| 652 |
if self.proto >= 2 and func_name == "__newobj_ex__": |
| 653 |
cls, args, kwargs = args |
| 654 |
if not hasattr(cls, "__new__"): |
| 655 |
raise PicklingError("args[0] from {} args has no __new__" |
| 656 |
.format(func_name)) |
| 657 |
if obj is not None and cls is not obj.__class__: |
| 658 |
raise PicklingError("args[0] from {} args has the wrong class" |
| 659 |
.format(func_name)) |
| 660 |
if self.proto >= 4: |
| 661 |
save(cls) |
| 662 |
save(args) |
| 663 |
save(kwargs) |
| 664 |
write(NEWOBJ_EX) |
| 665 |
else: |
| 666 |
func = partial(cls.__new__, cls, *args, **kwargs) |
| 667 |
save(func) |
| 668 |
save(()) |
| 669 |
write(REDUCE) |
| 670 |
elif self.proto >= 2 and func_name == "__newobj__": |
| 671 |
|
| 672 |
|
| 673 |
|
| 674 |
|
| 675 |
|
| 676 |
|
| 677 |
|
| 678 |
|
| 679 |
|
| 680 |
|
| 681 |
|
| 682 |
|
| 683 |
|
| 684 |
|
| 685 |
|
| 686 |
|
| 687 |
|
| 688 |
|
| 689 |
|
| 690 |
|
| 691 |
|
| 692 |
|
| 693 |
|
| 694 |
|
| 695 |
|
| 696 |
|
| 697 |
cls = args[0] |
| 698 |
if not hasattr(cls, "__new__"): |
| 699 |
raise PicklingError( |
| 700 |
"args[0] from __newobj__ args has no __new__") |
| 701 |
if obj is not None and cls is not obj.__class__: |
| 702 |
raise PicklingError( |
| 703 |
"args[0] from __newobj__ args has the wrong class") |
| 704 |
args = args[1:] |
| 705 |
save(cls) |
| 706 |
save(args) |
| 707 |
write(NEWOBJ) |
| 708 |
else: |
| 709 |
save(func) |
| 710 |
save(args) |
| 711 |
write(REDUCE) |
| 712 |
|
| 713 |
if obj is not None: |
| 714 |
|
| 715 |
|
| 716 |
|
| 717 |
if obj in self.memo: |
| 718 |
write(POP + self.get(self.memo[obj][0])) |
| 719 |
else: |
| 720 |
self.memoize(obj) |
| 721 |
|
| 722 |
|
| 723 |
|
| 724 |
|
| 725 |
|
| 726 |
|
| 727 |
if listitems is not None: |
| 728 |
self._batch_appends(listitems) |
| 729 |
|
| 730 |
if dictitems is not None: |
| 731 |
self._batch_setitems(dictitems) |
| 732 |
|
| 733 |
if state is not None: |
| 734 |
if state_setter is None: |
| 735 |
save(state) |
| 736 |
write(BUILD) |
| 737 |
else: |
| 738 |
|
| 739 |
|
| 740 |
|
| 741 |
|
| 742 |
save(state_setter) |
| 743 |
save(obj) |
| 744 |
save(state) |
| 745 |
write(TUPLE2) |
| 746 |
|
| 747 |
write(REDUCE) |
| 748 |
|
| 749 |
|
| 750 |
|
| 751 |
|
| 752 |
write(POP) |
| 753 |
|
| 754 |
|
| 755 |
|
| 756 |
dispatch = {} |
| 757 |
|
| 758 |
def save_none(self, obj): |
| 759 |
self.write(NONE) |
| 760 |
dispatch[type(None)] = save_none |
| 761 |
|
| 762 |
def save_bool(self, obj): |
| 763 |
if self.proto >= 2: |
| 764 |
self.write(NEWTRUE if obj else NEWFALSE) |
| 765 |
else: |
| 766 |
self.write(TRUE if obj else FALSE) |
| 767 |
dispatch[bool] = save_bool |
| 768 |
|
| 769 |
def save_long(self, obj): |
| 770 |
if self.bin: |
| 771 |
|
| 772 |
|
| 773 |
|
| 774 |
|
| 775 |
if obj >= 0: |
| 776 |
if obj <= 0xff: |
| 777 |
self.write(BININT1 + pack("<B", obj)) |
| 778 |
return |
| 779 |
if obj <= 0xffff: |
| 780 |
self.write(BININT2 + pack("<H", obj)) |
| 781 |
return |
| 782 |
|
| 783 |
if -0x80000000 <= obj <= 0x7fffffff: |
| 784 |
self.write(BININT + pack("<i", obj)) |
| 785 |
return |
| 786 |
if self.proto >= 2: |
| 787 |
encoded = encode_long(obj) |
| 788 |
n = len(encoded) |
| 789 |
if n < 256: |
| 790 |
self.write(LONG1 + pack("<B", n) + encoded) |
| 791 |
else: |
| 792 |
self.write(LONG4 + pack("<i", n) + encoded) |
| 793 |
return |
| 794 |
if -0x80000000 <= obj <= 0x7fffffff: |
| 795 |
self.write(INT + repr(obj).encode("ascii") + b'\n') |
| 796 |
else: |
| 797 |
self.write(LONG + repr(obj).encode("ascii") + b'L\n') |
| 798 |
dispatch[int] = save_long |
| 799 |
|
| 800 |
def save_float(self, obj): |
| 801 |
if self.bin: |
| 802 |
self.write(BINFLOAT + pack('>d', obj)) |
| 803 |
else: |
| 804 |
self.write(FLOAT + repr(obj).encode("ascii") + b'\n') |
| 805 |
dispatch[float] = save_float |
| 806 |
|
| 807 |
def save_bytes(self, obj): |
| 808 |
if self.proto < 3: |
| 809 |
if not obj: |
| 810 |
self.save_reduce(bytes, (), obj=obj) |
| 811 |
else: |
| 812 |
self.save_reduce(codecs.encode, |
| 813 |
(str(obj, 'latin1'), 'latin1'), obj=obj) |
| 814 |
return |
| 815 |
n = len(obj) |
| 816 |
if n <= 0xff: |
| 817 |
self.write(SHORT_BINBYTES + pack("<B", n) + obj) |
| 818 |
elif n > 0xffffffff and self.proto >= 4: |
| 819 |
self._write_large_bytes(BINBYTES8 + pack("<Q", n), obj) |
| 820 |
elif n >= self.framer._FRAME_SIZE_TARGET: |
| 821 |
self._write_large_bytes(BINBYTES + pack("<I", n), obj) |
| 822 |
else: |
| 823 |
self.write(BINBYTES + pack("<I", n) + obj) |
| 824 |
self.memoize(obj) |
| 825 |
dispatch[bytes] = save_bytes |
| 826 |
|
| 827 |
def save_bytearray(self, obj): |
| 828 |
if self.proto < 5: |
| 829 |
if not obj: |
| 830 |
self.save_reduce(bytearray, (), obj=obj) |
| 831 |
else: |
| 832 |
self.save_reduce(bytearray, (bytes(obj),), obj=obj) |
| 833 |
return |
| 834 |
n = len(obj) |
| 835 |
if n >= self.framer._FRAME_SIZE_TARGET: |
| 836 |
self._write_large_bytes(BYTEARRAY8 + pack("<Q", n), obj) |
| 837 |
else: |
| 838 |
self.write(BYTEARRAY8 + pack("<Q", n) + obj) |
| 839 |
self.memoize(obj) |
| 840 |
dispatch[bytearray] = save_bytearray |
| 841 |
|
| 842 |
if _HAVE_PICKLE_BUFFER: |
| 843 |
def save_picklebuffer(self, obj): |
| 844 |
if self.proto < 5: |
| 845 |
raise PicklingError("PickleBuffer can only pickled with " |
| 846 |
"protocol >= 5") |
| 847 |
with obj.raw() as m: |
| 848 |
if not m.contiguous: |
| 849 |
raise PicklingError("PickleBuffer can not be pickled when " |
| 850 |
"pointing to a non-contiguous buffer") |
| 851 |
in_band = True |
| 852 |
if self._buffer_callback is not None: |
| 853 |
in_band = bool(self._buffer_callback(obj)) |
| 854 |
if in_band: |
| 855 |
|
| 856 |
|
| 857 |
if m.readonly: |
| 858 |
self.save_bytes(m.tobytes()) |
| 859 |
else: |
| 860 |
self.save_bytearray(m.tobytes()) |
| 861 |
else: |
| 862 |
|
| 863 |
self.write(NEXT_BUFFER) |
| 864 |
if m.readonly: |
| 865 |
self.write(READONLY_BUFFER) |
| 866 |
|
| 867 |
dispatch[PickleBuffer] = save_picklebuffer |
| 868 |
|
| 869 |
def save_str(self, obj): |
| 870 |
if self.bin: |
| 871 |
encoded = obj.encode('utf-8', 'surrogatepass') |
| 872 |
n = len(encoded) |
| 873 |
if n <= 0xff and self.proto >= 4: |
| 874 |
self.write(SHORT_BINUNICODE + pack("<B", n) + encoded) |
| 875 |
elif n > 0xffffffff and self.proto >= 4: |
| 876 |
self._write_large_bytes(BINUNICODE8 + pack("<Q", n), encoded) |
| 877 |
elif n >= self.framer._FRAME_SIZE_TARGET: |
| 878 |
self._write_large_bytes(BINUNICODE + pack("<I", n), encoded) |
| 879 |
else: |
| 880 |
self.write(BINUNICODE + pack("<I", n) + encoded) |
| 881 |
else: |
| 882 |
|
| 883 |
tmp = obj.replace("\\", "\\u005c") |
| 884 |
tmp = tmp.replace("\0", "\\u0000") |
| 885 |
tmp = tmp.replace("\n", "\\u000a") |
| 886 |
tmp = tmp.replace("\r", "\\u000d") |
| 887 |
tmp = tmp.replace("\x1a", "\\u001a") |
| 888 |
self.write(UNICODE + tmp.encode('raw-unicode-escape') + b'\n') |
| 889 |
self.memoize(obj) |
| 890 |
dispatch[str] = save_str |
| 891 |
|
| 892 |
def save_tuple(self, obj): |
| 893 |
if not obj: |
| 894 |
if self.bin: |
| 895 |
self.write(EMPTY_TUPLE) |
| 896 |
else: |
| 897 |
self.write(MARK + TUPLE) |
| 898 |
return |
| 899 |
|
| 900 |
n = len(obj) |
| 901 |
save = self.save |
| 902 |
memo = self.memo |
| 903 |
if n <= 3 and self.proto >= 2: |
| 904 |
for element in obj: |
| 905 |
save(element) |
| 906 |
|
| 907 |
if obj in memo: |
| 908 |
get = self.get(memo[obj][0]) |
| 909 |
self.write(POP * n + get) |
| 910 |
else: |
| 911 |
self.write(_tuplesize2code[n]) |
| 912 |
self.memoize(obj) |
| 913 |
return |
| 914 |
|
| 915 |
|
| 916 |
|
| 917 |
write = self.write |
| 918 |
write(MARK) |
| 919 |
for element in obj: |
| 920 |
save(element) |
| 921 |
|
| 922 |
if obj in memo: |
| 923 |
|
| 924 |
|
| 925 |
|
| 926 |
|
| 927 |
|
| 928 |
|
| 929 |
|
| 930 |
get = self.get(memo[obj][0]) |
| 931 |
if self.bin: |
| 932 |
write(POP_MARK + get) |
| 933 |
else: |
| 934 |
write(POP * (n+1) + get) |
| 935 |
return |
| 936 |
|
| 937 |
|
| 938 |
write(TUPLE) |
| 939 |
self.memoize(obj) |
| 940 |
|
| 941 |
dispatch[tuple] = save_tuple |
| 942 |
|
| 943 |
def save_list(self, obj): |
| 944 |
if self.bin: |
| 945 |
self.write(EMPTY_LIST) |
| 946 |
else: |
| 947 |
self.write(MARK + LIST) |
| 948 |
|
| 949 |
self.memoize(obj) |
| 950 |
self._batch_appends(obj) |
| 951 |
|
| 952 |
dispatch[list] = save_list |
| 953 |
|
| 954 |
_BATCHSIZE = 1000 |
| 955 |
|
| 956 |
def _batch_appends(self, items): |
| 957 |
|
| 958 |
save = self.save |
| 959 |
write = self.write |
| 960 |
|
| 961 |
if not self.bin: |
| 962 |
for x in items: |
| 963 |
save(x) |
| 964 |
write(APPEND) |
| 965 |
return |
| 966 |
|
| 967 |
it = iter(items) |
| 968 |
while True: |
| 969 |
tmp = list(islice(it, self._BATCHSIZE)) |
| 970 |
n = len(tmp) |
| 971 |
if n > 1: |
| 972 |
write(MARK) |
| 973 |
for x in tmp: |
| 974 |
save(x) |
| 975 |
write(APPENDS) |
| 976 |
elif n: |
| 977 |
save(tmp[0]) |
| 978 |
write(APPEND) |
| 979 |
|
| 980 |
if n < self._BATCHSIZE: |
| 981 |
return |
| 982 |
|
| 983 |
def save_dict(self, obj): |
| 984 |
if self.bin: |
| 985 |
self.write(EMPTY_DICT) |
| 986 |
else: |
| 987 |
self.write(MARK + DICT) |
| 988 |
|
| 989 |
self.memoize(obj) |
| 990 |
self._batch_setitems(obj.items()) |
| 991 |
|
| 992 |
dispatch[dict] = save_dict |
| 993 |
if PyStringMap is not None: |
| 994 |
dispatch[PyStringMap] = save_dict |
| 995 |
|
| 996 |
def _batch_setitems(self, items): |
| 997 |
|
| 998 |
save = self.save |
| 999 |
write = self.write |
| 1000 |
|
| 1001 |
if not self.bin: |
| 1002 |
for k, v in items: |
| 1003 |
save(k) |
| 1004 |
save(v) |
| 1005 |
write(SETITEM) |
| 1006 |
return |
| 1007 |
|
| 1008 |
it = iter(items) |
| 1009 |
while True: |
| 1010 |
tmp = list(islice(it, self._BATCHSIZE)) |
| 1011 |
n = len(tmp) |
| 1012 |
if n > 1: |
| 1013 |
write(MARK) |
| 1014 |
for k, v in tmp: |
| 1015 |
save(k) |
| 1016 |
save(v) |
| 1017 |
write(SETITEMS) |
| 1018 |
elif n: |
| 1019 |
k, v = tmp[0] |
| 1020 |
save(k) |
| 1021 |
save(v) |
| 1022 |
write(SETITEM) |
| 1023 |
|
| 1024 |
if n < self._BATCHSIZE: |
| 1025 |
return |
| 1026 |
|
| 1027 |
def save_set(self, obj): |
| 1028 |
save = self.save |
| 1029 |
write = self.write |
| 1030 |
|
| 1031 |
if self.proto < 4: |
| 1032 |
self.save_reduce(set, (list(obj),), obj=obj) |
| 1033 |
return |
| 1034 |
|
| 1035 |
write(EMPTY_SET) |
| 1036 |
self.memoize(obj) |
| 1037 |
|
| 1038 |
it = iter(obj) |
| 1039 |
while True: |
| 1040 |
batch = list(islice(it, self._BATCHSIZE)) |
| 1041 |
n = len(batch) |
| 1042 |
if n > 0: |
| 1043 |
write(MARK) |
| 1044 |
for item in batch: |
| 1045 |
save(item) |
| 1046 |
write(ADDITEMS) |
| 1047 |
if n < self._BATCHSIZE: |
| 1048 |
return |
| 1049 |
dispatch[set] = save_set |
| 1050 |
|
| 1051 |
def save_frozenset(self, obj): |
| 1052 |
save = self.save |
| 1053 |
write = self.write |
| 1054 |
|
| 1055 |
if self.proto < 4: |
| 1056 |
self.save_reduce(frozenset, (list(obj),), obj=obj) |
| 1057 |
return |
| 1058 |
|
| 1059 |
write(MARK) |
| 1060 |
for item in obj: |
| 1061 |
save(item) |
| 1062 |
|
| 1063 |
if obj in self.memo: |
| 1064 |
|
| 1065 |
|
| 1066 |
|
| 1067 |
write(POP_MARK + self.get(self.memo[obj][0])) |
| 1068 |
return |
| 1069 |
|
| 1070 |
write(FROZENSET) |
| 1071 |
self.memoize(obj) |
| 1072 |
dispatch[frozenset] = save_frozenset |
| 1073 |
|
| 1074 |
def save_global(self, obj, name=None): |
| 1075 |
write = self.write |
| 1076 |
memo = self.memo |
| 1077 |
|
| 1078 |
if name is None: |
| 1079 |
name = getattr(obj, '__qualname__', None) |
| 1080 |
if name is None: |
| 1081 |
name = obj.__name__ |
| 1082 |
|
| 1083 |
module_name = whichmodule(obj, name) |
| 1084 |
try: |
| 1085 |
__import__(module_name, level=0) |
| 1086 |
module = sys.modules[module_name] |
| 1087 |
obj2, parent = _getattribute(module, name) |
| 1088 |
except (ImportError, KeyError, AttributeError): |
| 1089 |
raise PicklingError( |
| 1090 |
"Can't pickle %r: it's not found as %s.%s" % |
| 1091 |
(obj, module_name, name)) from None |
| 1092 |
else: |
| 1093 |
if obj2 is not obj: |
| 1094 |
raise PicklingError( |
| 1095 |
"Can't pickle %r: it's not the same object as %s.%s" % |
| 1096 |
(obj, module_name, name)) |
| 1097 |
|
| 1098 |
if self.proto >= 2: |
| 1099 |
code = _extension_registry.get((module_name, name)) |
| 1100 |
if code: |
| 1101 |
assert code > 0 |
| 1102 |
if code <= 0xff: |
| 1103 |
write(EXT1 + pack("<B", code)) |
| 1104 |
elif code <= 0xffff: |
| 1105 |
write(EXT2 + pack("<H", code)) |
| 1106 |
else: |
| 1107 |
write(EXT4 + pack("<i", code)) |
| 1108 |
return |
| 1109 |
lastname = name.rpartition('.')[2] |
| 1110 |
if parent is module: |
| 1111 |
name = lastname |
| 1112 |
|
| 1113 |
if self.proto >= 4: |
| 1114 |
self.save(module_name) |
| 1115 |
self.save(name) |
| 1116 |
write(STACK_GLOBAL) |
| 1117 |
elif parent is not module: |
| 1118 |
self.save_reduce(getattr, (parent, lastname)) |
| 1119 |
elif self.proto >= 3: |
| 1120 |
write(GLOBAL + bytes(module_name, "utf-8") + b'\n' + |
| 1121 |
bytes(name, "utf-8") + b'\n') |
| 1122 |
else: |
| 1123 |
if self.fix_imports: |
| 1124 |
r_name_mapping = _compat_pickle.REVERSE_NAME_MAPPING |
| 1125 |
r_import_mapping = _compat_pickle.REVERSE_IMPORT_MAPPING |
| 1126 |
if (module_name, name) in r_name_mapping: |
| 1127 |
module_name, name = r_name_mapping[(module_name, name)] |
| 1128 |
elif module_name in r_import_mapping: |
| 1129 |
module_name = r_import_mapping[module_name] |
| 1130 |
try: |
| 1131 |
write(GLOBAL + bytes(module_name, "ascii") + b'\n' + |
| 1132 |
bytes(name, "ascii") + b'\n') |
| 1133 |
except UnicodeEncodeError: |
| 1134 |
raise PicklingError( |
| 1135 |
"can't pickle global identifier '%s.%s' using " |
| 1136 |
"pickle protocol %i" % (module, name, self.proto)) from None |
| 1137 |
|
| 1138 |
self.memoize(obj) |
| 1139 |
|
| 1140 |
def save_type(self, obj): |
| 1141 |
if obj is type(None): |
| 1142 |
return self.save_reduce(type, (None,), obj=obj) |
| 1143 |
elif obj is type(NotImplemented): |
| 1144 |
return self.save_reduce(type, (NotImplemented,), obj=obj) |
| 1145 |
elif obj is type(...): |
| 1146 |
return self.save_reduce(type, (...,), obj=obj) |
| 1147 |
return self.save_global(obj) |
| 1148 |
|
| 1149 |
dispatch[FunctionType] = save_global |
| 1150 |
dispatch[type] = save_type |
| 1151 |
|
| 1152 |
|
| 1153 |
|
| 1154 |
|
| 1155 |
class _Unpickler: |
| 1156 |
|
| 1157 |
def __init__(self, file, *, fix_imports=True, |
| 1158 |
encoding="ASCII", errors="strict", buffers=None): |
| 1159 |
"""This takes a binary file for reading a pickle data stream. |
| 1160 |
|
| 1161 |
The protocol version of the pickle is detected automatically, so |
| 1162 |
no proto argument is needed. |
| 1163 |
|
| 1164 |
The argument *file* must have two methods, a read() method that |
| 1165 |
takes an integer argument, and a readline() method that requires |
| 1166 |
no arguments. Both methods should return bytes. Thus *file* |
| 1167 |
can be a binary file object opened for reading, an io.BytesIO |
| 1168 |
object, or any other custom object that meets this interface. |
| 1169 |
|
| 1170 |
The file-like object must have two methods, a read() method |
| 1171 |
that takes an integer argument, and a readline() method that |
| 1172 |
requires no arguments. Both methods should return bytes. |
| 1173 |
Thus file-like object can be a binary file object opened for |
| 1174 |
reading, a BytesIO object, or any other custom object that |
| 1175 |
meets this interface. |
| 1176 |
|
| 1177 |
If *buffers* is not None, it should be an iterable of buffer-enabled |
| 1178 |
objects that is consumed each time the pickle stream references |
| 1179 |
an out-of-band buffer view. Such buffers have been given in order |
| 1180 |
to the *buffer_callback* of a Pickler object. |
| 1181 |
|
| 1182 |
If *buffers* is None (the default), then the buffers are taken |
| 1183 |
from the pickle stream, assuming they are serialized there. |
| 1184 |
It is an error for *buffers* to be None if the pickle stream |
| 1185 |
was produced with a non-None *buffer_callback*. |
| 1186 |
|
| 1187 |
Other optional arguments are *fix_imports*, *encoding* and |
| 1188 |
*errors*, which are used to control compatibility support for |
| 1189 |
pickle stream generated by Python 2. If *fix_imports* is True, |
| 1190 |
pickle will try to map the old Python 2 names to the new names |
| 1191 |
used in Python 3. The *encoding* and *errors* tell pickle how |
| 1192 |
to decode 8-bit string instances pickled by Python 2; these |
| 1193 |
default to 'ASCII' and 'strict', respectively. *encoding* can be |
| 1194 |
'bytes' to read these 8-bit string instances as bytes objects. |
| 1195 |
""" |
| 1196 |
self._buffers = iter(buffers) if buffers is not None else None |
| 1197 |
self._file_readline = file.readline |
| 1198 |
self._file_read = file.read |
| 1199 |
self.memo = {} |
| 1200 |
self.encoding = encoding |
| 1201 |
self.errors = errors |
| 1202 |
self.proto = 0 |
| 1203 |
self.fix_imports = fix_imports |
| 1204 |
|
| 1205 |
def load(self): |
| 1206 |
"""Read a pickled object representation from the open file. |
| 1207 |
|
| 1208 |
Return the reconstituted object hierarchy specified in the file. |
| 1209 |
""" |
| 1210 |
|
| 1211 |
|
| 1212 |
if not hasattr(self, "_file_read"): |
| 1213 |
raise UnpicklingError("Unpickler.__init__() was not called by " |
| 1214 |
"%s.__init__()" % (self.__class__.__name__,)) |
| 1215 |
self._unframer = _Unframer(self._file_read, self._file_readline) |
| 1216 |
self.read = self._unframer.read |
| 1217 |
self.readinto = self._unframer.readinto |
| 1218 |
self.readline = self._unframer.readline |
| 1219 |
self.metastack = [] |
| 1220 |
self.stack = [] |
| 1221 |
self.append = self.stack.append |
| 1222 |
self.proto = 0 |
| 1223 |
read = self.read |
| 1224 |
dispatch = self.dispatch |
| 1225 |
try: |
| 1226 |
while True: |
| 1227 |
key = read(1) |
| 1228 |
if not key: |
| 1229 |
raise EOFError |
| 1230 |
assert isinstance(key, bytes_types) |
| 1231 |
dispatch[key[0]](self) |
| 1232 |
except _Stop as stopinst: |
| 1233 |
return stopinst.value |
| 1234 |
|
| 1235 |
|
| 1236 |
def pop_mark(self): |
| 1237 |
items = self.stack |
| 1238 |
self.stack = self.metastack.pop() |
| 1239 |
self.append = self.stack.append |
| 1240 |
return items |
| 1241 |
|
| 1242 |
def persistent_load(self, pid): |
| 1243 |
raise UnpicklingError("unsupported persistent id encountered") |
| 1244 |
|
| 1245 |
dispatch = {} |
| 1246 |
|
| 1247 |
def load_proto(self): |
| 1248 |
proto = self.read(1)[0] |
| 1249 |
if not 0 <= proto <= HIGHEST_PROTOCOL: |
| 1250 |
raise ValueError("unsupported pickle protocol: %d" % proto) |
| 1251 |
self.proto = proto |
| 1252 |
dispatch[PROTO[0]] = load_proto |
| 1253 |
|
| 1254 |
def load_frame(self): |
| 1255 |
frame_size, = unpack('<Q', self.read(8)) |
| 1256 |
if frame_size > sys.maxsize: |
| 1257 |
raise ValueError("frame size > sys.maxsize: %d" % frame_size) |
| 1258 |
self._unframer.load_frame(frame_size) |
| 1259 |
dispatch[FRAME[0]] = load_frame |
| 1260 |
|
| 1261 |
def load_persid(self): |
| 1262 |
try: |
| 1263 |
pid = self.readline()[:-1].decode("ascii") |
| 1264 |
except UnicodeDecodeError: |
| 1265 |
raise UnpicklingError( |
| 1266 |
"persistent IDs in protocol 0 must be ASCII strings") |
| 1267 |
self.append(self.persistent_load(pid)) |
| 1268 |
dispatch[PERSID[0]] = load_persid |
| 1269 |
|
| 1270 |
def load_binpersid(self): |
| 1271 |
pid = self.stack.pop() |
| 1272 |
self.append(self.persistent_load(pid)) |
| 1273 |
dispatch[BINPERSID[0]] = load_binpersid |
| 1274 |
|
| 1275 |
def load_none(self): |
| 1276 |
self.append(None) |
| 1277 |
dispatch[NONE[0]] = load_none |
| 1278 |
|
| 1279 |
def load_false(self): |
| 1280 |
self.append(False) |
| 1281 |
dispatch[NEWFALSE[0]] = load_false |
| 1282 |
|
| 1283 |
def load_true(self): |
| 1284 |
self.append(True) |
| 1285 |
dispatch[NEWTRUE[0]] = load_true |
| 1286 |
|
| 1287 |
def load_int(self): |
| 1288 |
data = self.readline() |
| 1289 |
if data == FALSE[1:]: |
| 1290 |
val = False |
| 1291 |
elif data == TRUE[1:]: |
| 1292 |
val = True |
| 1293 |
else: |
| 1294 |
val = int(data, 0) |
| 1295 |
self.append(val) |
| 1296 |
dispatch[INT[0]] = load_int |
| 1297 |
|
| 1298 |
def load_binint(self): |
| 1299 |
self.append(unpack('<i', self.read(4))[0]) |
| 1300 |
dispatch[BININT[0]] = load_binint |
| 1301 |
|
| 1302 |
def load_binint1(self): |
| 1303 |
self.append(self.read(1)[0]) |
| 1304 |
dispatch[BININT1[0]] = load_binint1 |
| 1305 |
|
| 1306 |
def load_binint2(self): |
| 1307 |
self.append(unpack('<H', self.read(2))[0]) |
| 1308 |
dispatch[BININT2[0]] = load_binint2 |
| 1309 |
|
| 1310 |
def load_long(self): |
| 1311 |
val = self.readline()[:-1] |
| 1312 |
if val and val[-1] == b'L'[0]: |
| 1313 |
val = val[:-1] |
| 1314 |
self.append(int(val, 0)) |
| 1315 |
dispatch[LONG[0]] = load_long |
| 1316 |
|
| 1317 |
def load_long1(self): |
| 1318 |
n = self.read(1)[0] |
| 1319 |
data = self.read(n) |
| 1320 |
self.append(decode_long(data)) |
| 1321 |
dispatch[LONG1[0]] = load_long1 |
| 1322 |
|
| 1323 |
def load_long4(self): |
| 1324 |
n, = unpack('<i', self.read(4)) |
| 1325 |
if n < 0: |
| 1326 |
|
| 1327 |
raise UnpicklingError("LONG pickle has negative byte count") |
| 1328 |
data = self.read(n) |
| 1329 |
self.append(decode_long(data)) |
| 1330 |
dispatch[LONG4[0]] = load_long4 |
| 1331 |
|
| 1332 |
def load_float(self): |
| 1333 |
self.append(float(self.readline()[:-1])) |
| 1334 |
dispatch[FLOAT[0]] = load_float |
| 1335 |
|
| 1336 |
def load_binfloat(self): |
| 1337 |
self.append(unpack('>d', self.read(8))[0]) |
| 1338 |
dispatch[BINFLOAT[0]] = load_binfloat |
| 1339 |
|
| 1340 |
def _decode_string(self, value): |
| 1341 |
|
| 1342 |
|
| 1343 |
|
| 1344 |
if self.encoding == "bytes": |
| 1345 |
return value |
| 1346 |
else: |
| 1347 |
return value.decode(self.encoding, self.errors) |
| 1348 |
|
| 1349 |
def load_string(self): |
| 1350 |
data = self.readline()[:-1] |
| 1351 |
|
| 1352 |
if len(data) >= 2 and data[0] == data[-1] and data[0] in b'"\'': |
| 1353 |
data = data[1:-1] |
| 1354 |
else: |
| 1355 |
raise UnpicklingError("the STRING opcode argument must be quoted") |
| 1356 |
self.append(self._decode_string(codecs.escape_decode(data)[0])) |
| 1357 |
dispatch[STRING[0]] = load_string |
| 1358 |
|
| 1359 |
def load_binstring(self): |
| 1360 |
|
| 1361 |
len, = unpack('<i', self.read(4)) |
| 1362 |
if len < 0: |
| 1363 |
raise UnpicklingError("BINSTRING pickle has negative byte count") |
| 1364 |
data = self.read(len) |
| 1365 |
self.append(self._decode_string(data)) |
| 1366 |
dispatch[BINSTRING[0]] = load_binstring |
| 1367 |
|
| 1368 |
def load_binbytes(self): |
| 1369 |
len, = unpack('<I', self.read(4)) |
| 1370 |
if len > maxsize: |
| 1371 |
raise UnpicklingError("BINBYTES exceeds system's maximum size " |
| 1372 |
"of %d bytes" % maxsize) |
| 1373 |
self.append(self.read(len)) |
| 1374 |
dispatch[BINBYTES[0]] = load_binbytes |
| 1375 |
|
| 1376 |
def load_unicode(self): |
| 1377 |
self.append(str(self.readline()[:-1], 'raw-unicode-escape')) |
| 1378 |
dispatch[UNICODE[0]] = load_unicode |
| 1379 |
|
| 1380 |
def load_binunicode(self): |
| 1381 |
len, = unpack('<I', self.read(4)) |
| 1382 |
if len > maxsize: |
| 1383 |
raise UnpicklingError("BINUNICODE exceeds system's maximum size " |
| 1384 |
"of %d bytes" % maxsize) |
| 1385 |
self.append(str(self.read(len), 'utf-8', 'surrogatepass')) |
| 1386 |
dispatch[BINUNICODE[0]] = load_binunicode |
| 1387 |
|
| 1388 |
def load_binunicode8(self): |
| 1389 |
len, = unpack('<Q', self.read(8)) |
| 1390 |
if len > maxsize: |
| 1391 |
raise UnpicklingError("BINUNICODE8 exceeds system's maximum size " |
| 1392 |
"of %d bytes" % maxsize) |
| 1393 |
self.append(str(self.read(len), 'utf-8', 'surrogatepass')) |
| 1394 |
dispatch[BINUNICODE8[0]] = load_binunicode8 |
| 1395 |
|
| 1396 |
def load_binbytes8(self): |
| 1397 |
len, = unpack('<Q', self.read(8)) |
| 1398 |
if len > maxsize: |
| 1399 |
raise UnpicklingError("BINBYTES8 exceeds system's maximum size " |
| 1400 |
"of %d bytes" % maxsize) |
| 1401 |
self.append(self.read(len)) |
| 1402 |
dispatch[BINBYTES8[0]] = load_binbytes8 |
| 1403 |
|
| 1404 |
def load_bytearray8(self): |
| 1405 |
len, = unpack('<Q', self.read(8)) |
| 1406 |
if len > maxsize: |
| 1407 |
raise UnpicklingError("BYTEARRAY8 exceeds system's maximum size " |
| 1408 |
"of %d bytes" % maxsize) |
| 1409 |
b = bytearray(len) |
| 1410 |
self.readinto(b) |
| 1411 |
self.append(b) |
| 1412 |
dispatch[BYTEARRAY8[0]] = load_bytearray8 |
| 1413 |
|
| 1414 |
def load_next_buffer(self): |
| 1415 |
if self._buffers is None: |
| 1416 |
raise UnpicklingError("pickle stream refers to out-of-band data " |
| 1417 |
"but no *buffers* argument was given") |
| 1418 |
try: |
| 1419 |
buf = next(self._buffers) |
| 1420 |
except StopIteration: |
| 1421 |
raise UnpicklingError("not enough out-of-band buffers") |
| 1422 |
self.append(buf) |
| 1423 |
dispatch[NEXT_BUFFER[0]] = load_next_buffer |
| 1424 |
|
| 1425 |
def load_readonly_buffer(self): |
| 1426 |
buf = self.stack[-1] |
| 1427 |
with memoryview(buf) as m: |
| 1428 |
if not m.readonly: |
| 1429 |
self.stack[-1] = m.toreadonly() |
| 1430 |
dispatch[READONLY_BUFFER[0]] = load_readonly_buffer |
| 1431 |
|
| 1432 |
def load_short_binstring(self): |
| 1433 |
len = self.read(1)[0] |
| 1434 |
data = self.read(len) |
| 1435 |
self.append(self._decode_string(data)) |
| 1436 |
dispatch[SHORT_BINSTRING[0]] = load_short_binstring |
| 1437 |
|
| 1438 |
def load_short_binbytes(self): |
| 1439 |
len = self.read(1)[0] |
| 1440 |
self.append(self.read(len)) |
| 1441 |
dispatch[SHORT_BINBYTES[0]] = load_short_binbytes |
| 1442 |
|
| 1443 |
def load_short_binunicode(self): |
| 1444 |
len = self.read(1)[0] |
| 1445 |
self.append(str(self.read(len), 'utf-8', 'surrogatepass')) |
| 1446 |
dispatch[SHORT_BINUNICODE[0]] = load_short_binunicode |
| 1447 |
|
| 1448 |
def load_tuple(self): |
| 1449 |
items = self.pop_mark() |
| 1450 |
self.append(tuple(items)) |
| 1451 |
dispatch[TUPLE[0]] = load_tuple |
| 1452 |
|
| 1453 |
def load_empty_tuple(self): |
| 1454 |
self.append(()) |
| 1455 |
dispatch[EMPTY_TUPLE[0]] = load_empty_tuple |
| 1456 |
|
| 1457 |
def load_tuple1(self): |
| 1458 |
self.stack[-1] = (self.stack[-1],) |
| 1459 |
dispatch[TUPLE1[0]] = load_tuple1 |
| 1460 |
|
| 1461 |
def load_tuple2(self): |
| 1462 |
self.stack[-2:] = [(self.stack[-2], self.stack[-1])] |
| 1463 |
dispatch[TUPLE2[0]] = load_tuple2 |
| 1464 |
|
| 1465 |
def load_tuple3(self): |
| 1466 |
self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])] |
| 1467 |
dispatch[TUPLE3[0]] = load_tuple3 |
| 1468 |
|
| 1469 |
def load_empty_list(self): |
| 1470 |
self.append([]) |
| 1471 |
dispatch[EMPTY_LIST[0]] = load_empty_list |
| 1472 |
|
| 1473 |
def load_empty_dictionary(self): |
| 1474 |
self.append({}) |
| 1475 |
dispatch[EMPTY_DICT[0]] = load_empty_dictionary |
| 1476 |
|
| 1477 |
def load_empty_set(self): |
| 1478 |
self.append(set()) |
| 1479 |
dispatch[EMPTY_SET[0]] = load_empty_set |
| 1480 |
|
| 1481 |
def load_frozenset(self): |
| 1482 |
items = self.pop_mark() |
| 1483 |
self.append(frozenset(items)) |
| 1484 |
dispatch[FROZENSET[0]] = load_frozenset |
| 1485 |
|
| 1486 |
def load_list(self): |
| 1487 |
items = self.pop_mark() |
| 1488 |
self.append(items) |
| 1489 |
dispatch[LIST[0]] = load_list |
| 1490 |
|
| 1491 |
def load_dict(self): |
| 1492 |
items = self.pop_mark() |
| 1493 |
d = {items[i]: items[i+1] |
| 1494 |
for i in range(0, len(items), 2)} |
| 1495 |
self.append(d) |
| 1496 |
dispatch[DICT[0]] = load_dict |
| 1497 |
|
| 1498 |
|
| 1499 |
|
| 1500 |
|
| 1501 |
|
| 1502 |
|
| 1503 |
def _instantiate(self, klass, args): |
| 1504 |
if (args or not isinstance(klass, type) or |
| 1505 |
hasattr(klass, "__getinitargs__")): |
| 1506 |
try: |
| 1507 |
value = klass(*args) |
| 1508 |
except TypeError as err: |
| 1509 |
raise TypeError("in constructor for %s: %s" % |
| 1510 |
(klass.__name__, str(err)), sys.exc_info()[2]) |
| 1511 |
else: |
| 1512 |
value = klass.__new__(klass) |
| 1513 |
self.append(value) |
| 1514 |
|
| 1515 |
def load_inst(self): |
| 1516 |
module = self.readline()[:-1].decode("ascii") |
| 1517 |
name = self.readline()[:-1].decode("ascii") |
| 1518 |
klass = self.find_class(module, name) |
| 1519 |
self._instantiate(klass, self.pop_mark()) |
| 1520 |
dispatch[INST[0]] = load_inst |
| 1521 |
|
| 1522 |
def load_obj(self): |
| 1523 |
|
| 1524 |
args = self.pop_mark() |
| 1525 |
cls = args.pop(0) |
| 1526 |
self._instantiate(cls, args) |
| 1527 |
dispatch[OBJ[0]] = load_obj |
| 1528 |
|
| 1529 |
def load_newobj(self): |
| 1530 |
args = self.stack.pop() |
| 1531 |
cls = self.stack.pop() |
| 1532 |
obj = cls.__new__(cls, *args) |
| 1533 |
self.append(obj) |
| 1534 |
dispatch[NEWOBJ[0]] = load_newobj |
| 1535 |
|
| 1536 |
def load_newobj_ex(self): |
| 1537 |
kwargs = self.stack.pop() |
| 1538 |
args = self.stack.pop() |
| 1539 |
cls = self.stack.pop() |
| 1540 |
obj = cls.__new__(cls, *args, **kwargs) |
| 1541 |
self.append(obj) |
| 1542 |
dispatch[NEWOBJ_EX[0]] = load_newobj_ex |
| 1543 |
|
| 1544 |
def load_global(self): |
| 1545 |
module = self.readline()[:-1].decode("utf-8") |
| 1546 |
name = self.readline()[:-1].decode("utf-8") |
| 1547 |
klass = self.find_class(module, name) |
| 1548 |
self.append(klass) |
| 1549 |
dispatch[GLOBAL[0]] = load_global |
| 1550 |
|
| 1551 |
def load_stack_global(self): |
| 1552 |
name = self.stack.pop() |
| 1553 |
module = self.stack.pop() |
| 1554 |
if type(name) is not str or type(module) is not str: |
| 1555 |
raise UnpicklingError("STACK_GLOBAL requires str") |
| 1556 |
self.append(self.find_class(module, name)) |
| 1557 |
dispatch[STACK_GLOBAL[0]] = load_stack_global |
| 1558 |
|
| 1559 |
def load_ext1(self): |
| 1560 |
code = self.read(1)[0] |
| 1561 |
self.get_extension(code) |
| 1562 |
dispatch[EXT1[0]] = load_ext1 |
| 1563 |
|
| 1564 |
def load_ext2(self): |
| 1565 |
code, = unpack('<H', self.read(2)) |
| 1566 |
self.get_extension(code) |
| 1567 |
dispatch[EXT2[0]] = load_ext2 |
| 1568 |
|
| 1569 |
def load_ext4(self): |
| 1570 |
code, = unpack('<i', self.read(4)) |
| 1571 |
self.get_extension(code) |
| 1572 |
dispatch[EXT4[0]] = load_ext4 |
| 1573 |
|
| 1574 |
def get_extension(self, code): |
| 1575 |
nil = [] |
| 1576 |
obj = _extension_cache.get(code, nil) |
| 1577 |
if obj is not nil: |
| 1578 |
self.append(obj) |
| 1579 |
return |
| 1580 |
key = _inverted_registry.get(code) |
| 1581 |
if not key: |
| 1582 |
if code <= 0: |
| 1583 |
|
| 1584 |
raise UnpicklingError("EXT specifies code <= 0") |
| 1585 |
raise ValueError("unregistered extension code %d" % code) |
| 1586 |
obj = self.find_class(*key) |
| 1587 |
_extension_cache[code] = obj |
| 1588 |
self.append(obj) |
| 1589 |
|
| 1590 |
def find_class(self, module, name): |
| 1591 |
|
| 1592 |
sys.audit('pickle.find_class', module, name) |
| 1593 |
if self.proto < 3 and self.fix_imports: |
| 1594 |
if (module, name) in _compat_pickle.NAME_MAPPING: |
| 1595 |
module, name = _compat_pickle.NAME_MAPPING[(module, name)] |
| 1596 |
elif module in _compat_pickle.IMPORT_MAPPING: |
| 1597 |
module = _compat_pickle.IMPORT_MAPPING[module] |
| 1598 |
__import__(module, level=0) |
| 1599 |
if self.proto >= 4: |
| 1600 |
return _getattribute(sys.modules[module], name)[0] |
| 1601 |
else: |
| 1602 |
return getattr(sys.modules[module], name) |
| 1603 |
|
| 1604 |
def load_reduce(self): |
| 1605 |
stack = self.stack |
| 1606 |
args = stack.pop() |
| 1607 |
func = stack[-1] |
| 1608 |
stack[-1] = func(*args) |
| 1609 |
dispatch[REDUCE[0]] = load_reduce |
| 1610 |
|
| 1611 |
def load_pop(self): |
| 1612 |
if self.stack: |
| 1613 |
del self.stack[-1] |
| 1614 |
else: |
| 1615 |
self.pop_mark() |
| 1616 |
dispatch[POP[0]] = load_pop |
| 1617 |
|
| 1618 |
def load_pop_mark(self): |
| 1619 |
self.pop_mark() |
| 1620 |
dispatch[POP_MARK[0]] = load_pop_mark |
| 1621 |
|
| 1622 |
def load_dup(self): |
| 1623 |
self.append(self.stack[-1]) |
| 1624 |
dispatch[DUP[0]] = load_dup |
| 1625 |
|
| 1626 |
def load_get(self): |
| 1627 |
i = int(self.readline()[:-1]) |
| 1628 |
try: |
| 1629 |
self.append(self.memo[i]) |
| 1630 |
except KeyError: |
| 1631 |
msg = f'Memo value not found at index {i}' |
| 1632 |
raise UnpicklingError(msg) from None |
| 1633 |
dispatch[GET[0]] = load_get |
| 1634 |
|
| 1635 |
def load_binget(self): |
| 1636 |
i = self.read(1)[0] |
| 1637 |
try: |
| 1638 |
self.append(self.memo[i]) |
| 1639 |
except KeyError as exc: |
| 1640 |
msg = f'Memo value not found at index {i}' |
| 1641 |
raise UnpicklingError(msg) from None |
| 1642 |
dispatch[BINGET[0]] = load_binget |
| 1643 |
|
| 1644 |
def load_long_binget(self): |
| 1645 |
i, = unpack('<I', self.read(4)) |
| 1646 |
try: |
| 1647 |
self.append(self.memo[i]) |
| 1648 |
except KeyError as exc: |
| 1649 |
msg = f'Memo value not found at index {i}' |
| 1650 |
raise UnpicklingError(msg) from None |
| 1651 |
dispatch[LONG_BINGET[0]] = load_long_binget |
| 1652 |
|
| 1653 |
def load_put(self): |
| 1654 |
i = int(self.readline()[:-1]) |
| 1655 |
if i < 0: |
| 1656 |
raise ValueError("negative PUT argument") |
| 1657 |
self.memo[i] = self.stack[-1] |
| 1658 |
dispatch[PUT[0]] = load_put |
| 1659 |
|
| 1660 |
def load_binput(self): |
| 1661 |
i = self.read(1)[0] |
| 1662 |
if i < 0: |
| 1663 |
raise ValueError("negative BINPUT argument") |
| 1664 |
self.memo[i] = self.stack[-1] |
| 1665 |
dispatch[BINPUT[0]] = load_binput |
| 1666 |
|
| 1667 |
def load_long_binput(self): |
| 1668 |
i, = unpack('<I', self.read(4)) |
| 1669 |
if i > maxsize: |
| 1670 |
raise ValueError("negative LONG_BINPUT argument") |
| 1671 |
self.memo[i] = self.stack[-1] |
| 1672 |
dispatch[LONG_BINPUT[0]] = load_long_binput |
| 1673 |
|
| 1674 |
def load_memoize(self): |
| 1675 |
memo = self.memo |
| 1676 |
memo[len(memo)] = self.stack[-1] |
| 1677 |
dispatch[MEMOIZE[0]] = load_memoize |
| 1678 |
|
| 1679 |
def load_append(self): |
| 1680 |
stack = self.stack |
| 1681 |
value = stack.pop() |
| 1682 |
list = stack[-1] |
| 1683 |
list.append(value) |
| 1684 |
dispatch[APPEND[0]] = load_append |
| 1685 |
|
| 1686 |
def load_appends(self): |
| 1687 |
items = self.pop_mark() |
| 1688 |
list_obj = self.stack[-1] |
| 1689 |
try: |
| 1690 |
extend = list_obj.extend |
| 1691 |
except AttributeError: |
| 1692 |
pass |
| 1693 |
else: |
| 1694 |
extend(items) |
| 1695 |
return |
| 1696 |
|
| 1697 |
|
| 1698 |
|
| 1699 |
append = list_obj.append |
| 1700 |
for item in items: |
| 1701 |
append(item) |
| 1702 |
dispatch[APPENDS[0]] = load_appends |
| 1703 |
|
| 1704 |
def load_setitem(self): |
| 1705 |
stack = self.stack |
| 1706 |
value = stack.pop() |
| 1707 |
key = stack.pop() |
| 1708 |
dict = stack[-1] |
| 1709 |
dict[key] = value |
| 1710 |
dispatch[SETITEM[0]] = load_setitem |
| 1711 |
|
| 1712 |
def load_setitems(self): |
| 1713 |
items = self.pop_mark() |
| 1714 |
dict = self.stack[-1] |
| 1715 |
for i in range(0, len(items), 2): |
| 1716 |
dict[items[i]] = items[i + 1] |
| 1717 |
dispatch[SETITEMS[0]] = load_setitems |
| 1718 |
|
| 1719 |
def load_additems(self): |
| 1720 |
items = self.pop_mark() |
| 1721 |
set_obj = self.stack[-1] |
| 1722 |
if isinstance(set_obj, set): |
| 1723 |
set_obj.update(items) |
| 1724 |
else: |
| 1725 |
add = set_obj.add |
| 1726 |
for item in items: |
| 1727 |
add(item) |
| 1728 |
dispatch[ADDITEMS[0]] = load_additems |
| 1729 |
|
| 1730 |
def load_build(self): |
| 1731 |
stack = self.stack |
| 1732 |
state = stack.pop() |
| 1733 |
inst = stack[-1] |
| 1734 |
setstate = getattr(inst, "__setstate__", None) |
| 1735 |
if setstate is not None: |
| 1736 |
setstate(state) |
| 1737 |
return |
| 1738 |
slotstate = None |
| 1739 |
if isinstance(state, tuple) and len(state) == 2: |
| 1740 |
state, slotstate = state |
| 1741 |
if state: |
| 1742 |
inst_dict = inst.__dict__ |
| 1743 |
intern = sys.intern |
| 1744 |
for k, v in state.items(): |
| 1745 |
if type(k) is str: |
| 1746 |
inst_dict[intern(k)] = v |
| 1747 |
else: |
| 1748 |
inst_dict[k] = v |
| 1749 |
if slotstate: |
| 1750 |
for k, v in slotstate.items(): |
| 1751 |
setattr(inst, k, v) |
| 1752 |
dispatch[BUILD[0]] = load_build |
| 1753 |
|
| 1754 |
def load_mark(self): |
| 1755 |
self.metastack.append(self.stack) |
| 1756 |
self.stack = [] |
| 1757 |
self.append = self.stack.append |
| 1758 |
dispatch[MARK[0]] = load_mark |
| 1759 |
|
| 1760 |
def load_stop(self): |
| 1761 |
value = self.stack.pop() |
| 1762 |
raise _Stop(value) |
| 1763 |
dispatch[STOP[0]] = load_stop |
| 1764 |
|
| 1765 |
|
| 1766 |
|
| 1767 |
|
| 1768 |
def _dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None): |
| 1769 |
_Pickler(file, protocol, fix_imports=fix_imports, |
| 1770 |
buffer_callback=buffer_callback).dump(obj) |
| 1771 |
|
| 1772 |
def _dumps(obj, protocol=None, *, fix_imports=True, buffer_callback=None): |
| 1773 |
f = io.BytesIO() |
| 1774 |
_Pickler(f, protocol, fix_imports=fix_imports, |
| 1775 |
buffer_callback=buffer_callback).dump(obj) |
| 1776 |
res = f.getvalue() |
| 1777 |
assert isinstance(res, bytes_types) |
| 1778 |
return res |
| 1779 |
|
| 1780 |
def _load(file, *, fix_imports=True, encoding="ASCII", errors="strict", |
| 1781 |
buffers=None): |
| 1782 |
return _Unpickler(file, fix_imports=fix_imports, buffers=buffers, |
| 1783 |
encoding=encoding, errors=errors).load() |
| 1784 |
|
| 1785 |
def _loads(s, /, *, fix_imports=True, encoding="ASCII", errors="strict", |
| 1786 |
buffers=None): |
| 1787 |
if isinstance(s, str): |
| 1788 |
raise TypeError("Can't load pickle from unicode string") |
| 1789 |
file = io.BytesIO(s) |
| 1790 |
return _Unpickler(file, fix_imports=fix_imports, buffers=buffers, |
| 1791 |
encoding=encoding, errors=errors).load() |
| 1792 |
|
| 1793 |
|
| 1794 |
try: |
| 1795 |
from _pickle import ( |
| 1796 |
PickleError, |
| 1797 |
PicklingError, |
| 1798 |
UnpicklingError, |
| 1799 |
Pickler, |
| 1800 |
Unpickler, |
| 1801 |
dump, |
| 1802 |
dumps, |
| 1803 |
load, |
| 1804 |
loads |
| 1805 |
) |
| 1806 |
except ImportError: |
| 1807 |
Pickler, Unpickler = _Pickler, _Unpickler |
| 1808 |
dump, dumps, load, loads = _dump, _dumps, _load, _loads |
| 1809 |
|
| 1810 |
|
| 1811 |
def _test(): |
| 1812 |
import doctest |
| 1813 |
return doctest.testmod() |
| 1814 |
|
| 1815 |
if __name__ == "__main__": |
| 1816 |
import argparse |
| 1817 |
parser = argparse.ArgumentParser( |
| 1818 |
description='display contents of the pickle files') |
| 1819 |
parser.add_argument( |
| 1820 |
'pickle_file', |
| 1821 |
nargs='*', help='the pickle file') |
| 1822 |
parser.add_argument( |
| 1823 |
'-t', '--test', action='store_true', |
| 1824 |
help='run self-test suite') |
| 1825 |
parser.add_argument( |
| 1826 |
'-v', action='store_true', |
| 1827 |
help='run verbosely; only affects self-test run') |
| 1828 |
args = parser.parse_args() |
| 1829 |
if args.test: |
| 1830 |
_test() |
| 1831 |
else: |
| 1832 |
if not args.pickle_file: |
| 1833 |
parser.print_help() |
| 1834 |
else: |
| 1835 |
import pprint |
| 1836 |
for fn in args.pickle_file: |
| 1837 |
if fn == '-': |
| 1838 |
obj = load(sys.stdin.buffer) |
| 1839 |
else: |
| 1840 |
with open(fn, 'rb') as f: |
| 1841 |
obj = load(f) |
| 1842 |
pprint.pprint(obj) |