| 432 | # Pickling machinery |
| 433 | |
| 434 | class _Pickler: |
| 435 | |
| 436 | def __init__(self, file, protocol=None, *, fix_imports=True, |
| 437 | buffer_callback=None): |
| 438 | """This takes a binary file for writing a pickle data stream. |
| 439 | |
| 440 | The optional *protocol* argument tells the pickler to use the |
| 441 | given protocol; supported protocols are 0, 1, 2, 3, 4 and 5. |
| 442 | The default protocol is 5. It was introduced in Python 3.8, and |
| 443 | is incompatible with previous versions. |
| 444 | |
| 445 | Specifying a negative protocol version selects the highest |
| 446 | protocol version supported. The higher the protocol used, the |
| 447 | more recent the version of Python needed to read the pickle |
| 448 | produced. |
| 449 | |
| 450 | The *file* argument must have a write() method that accepts a |
| 451 | single bytes argument. It can thus be a file object opened for |
| 452 | binary writing, an io.BytesIO instance, or any other custom |
| 453 | object that meets this interface. |
| 454 | |
| 455 | If *fix_imports* is True and *protocol* is less than 3, pickle |
| 456 | will try to map the new Python 3 names to the old module names |
| 457 | used in Python 2, so that the pickle data stream is readable |
| 458 | with Python 2. |
| 459 | |
| 460 | If *buffer_callback* is None (the default), buffer views are |
| 461 | serialized into *file* as part of the pickle stream. |
| 462 | |
| 463 | If *buffer_callback* is not None, then it can be called any number |
| 464 | of times with a buffer view. If the callback returns a false value |
| 465 | (such as None), the given buffer is out-of-band; otherwise the |
| 466 | buffer is serialized in-band, i.e. inside the pickle stream. |
| 467 | |
| 468 | It is an error if *buffer_callback* is not None and *protocol* |
| 469 | is None or smaller than 5. |
| 470 | """ |
| 471 | if protocol is None: |
| 472 | protocol = DEFAULT_PROTOCOL |
| 473 | if protocol < 0: |
| 474 | protocol = HIGHEST_PROTOCOL |
| 475 | elif not 0 <= protocol <= HIGHEST_PROTOCOL: |
| 476 | raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL) |
| 477 | if buffer_callback is not None and protocol < 5: |
| 478 | raise ValueError("buffer_callback needs protocol >= 5") |
| 479 | self._buffer_callback = buffer_callback |
| 480 | try: |
| 481 | self._file_write = file.write |
| 482 | except AttributeError: |
| 483 | raise TypeError("file must have a 'write' attribute") |
| 484 | self.framer = _Framer(self._file_write) |
| 485 | self.write = self.framer.write |
| 486 | self._write_large_bytes = self.framer.write_large_bytes |
| 487 | self.memo = {} |
| 488 | self.proto = int(protocol) |
| 489 | self.bin = protocol >= 1 |
| 490 | self.fast = 0 |
| 491 | self.fix_imports = fix_imports and protocol < 3 |