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