|
17 | 17 | """
|
18 | 18 | __all__ = [
|
19 | 19 | 'dump', 'dumps', 'load', 'loads', 'dump_module', 'load_module',
|
20 |
| - 'load_module_asdict', 'dump_session', 'load_session', 'Pickler', 'Unpickler', |
21 |
| - 'register', 'copy', 'pickle', 'pickles', 'check', 'HIGHEST_PROTOCOL', |
22 |
| - 'DEFAULT_PROTOCOL', 'PicklingError', 'UnpicklingError', 'HANDLE_FMODE', |
23 |
| - 'CONTENTS_FMODE', 'FILE_FMODE', 'PickleError', 'PickleWarning', |
24 |
| - 'PicklingWarning', 'UnpicklingWarning' |
| 20 | + 'load_module_asdict', 'dump_session', 'load_session', 'is_module_pickle', |
| 21 | + 'Pickler', 'Unpickler', 'register', 'copy', 'pickle', 'pickles', 'check', |
| 22 | + 'HIGHEST_PROTOCOL', 'DEFAULT_PROTOCOL', 'PicklingError', 'UnpicklingError', |
| 23 | + 'HANDLE_FMODE', 'CONTENTS_FMODE', 'FILE_FMODE', 'PickleError', |
| 24 | + 'PickleWarning', 'PicklingWarning', 'UnpicklingWarning', |
25 | 25 | ]
|
26 | 26 |
|
27 | 27 | __module__ = 'dill'
|
@@ -606,6 +606,28 @@ def _identify_module(file, main=None):
|
606 | 606 | return None
|
607 | 607 | raise UnpicklingError("unable to identify main module") from error
|
608 | 608 |
|
| 609 | +def is_module_pickle(filename, importable: bool = True) -> bool: |
| 610 | + """Check if a file is a module state pickle file. |
| 611 | +
|
| 612 | + Parameters: |
| 613 | + filename: a path-like object or a readable stream. |
| 614 | + importable: expected kind of the file's saved module. Use `True` for |
| 615 | + importable modules (the default) or `False` for module-type objects. |
| 616 | +
|
| 617 | + Returns: |
| 618 | + `True` if the pickle file at ``filename`` was generated with |
| 619 | + :py:func:`dump_module` **AND** the module whose state is saved in it is |
| 620 | + of the kind specified by the ``importable`` argument. `False` otherwise. |
| 621 | + """ |
| 622 | + with _open(filename, 'rb', peekable=True) as file: |
| 623 | + try: |
| 624 | + pickle_main = _identify_module(file) |
| 625 | + except UnpicklingError: |
| 626 | + return False |
| 627 | + else: |
| 628 | + is_runtime_mod = pickle_main.startswith('__runtime__.') |
| 629 | + return importable ^ is_runtime_mod |
| 630 | + |
609 | 631 | def load_module(
|
610 | 632 | filename = str(TEMPDIR/'session.pkl'),
|
611 | 633 | module: Union[ModuleType, str] = None,
|
|
0 commit comments