Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/dill/session.py: 15%
259 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:35 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:35 +0000
1#!/usr/bin/env python
2#
3# Author: Mike McKerns (mmckerns @caltech and @uqfoundation)
4# Author: Leonardo Gama (@leogama)
5# Copyright (c) 2008-2015 California Institute of Technology.
6# Copyright (c) 2016-2022 The Uncertainty Quantification Foundation.
7# License: 3-clause BSD. The full license text is available at:
8# - https://github.com/uqfoundation/dill/blob/master/LICENSE
9"""
10Pickle and restore the intepreter session.
11"""
13__all__ = [
14 'dump_module', 'load_module', 'load_module_asdict',
15 'dump_session', 'load_session' # backward compatibility
16]
18import re
19import sys
20import warnings
22from dill import _dill, Pickler, Unpickler
23from ._dill import (
24 BuiltinMethodType, FunctionType, MethodType, ModuleType, TypeType,
25 _import_module, _is_builtin_module, _is_imported_module, _main_module,
26 _reverse_typemap, __builtin__,
27)
29# Type hints.
30from typing import Optional, Union
32import pathlib
33import tempfile
35TEMPDIR = pathlib.PurePath(tempfile.gettempdir())
37def _module_map():
38 """get map of imported modules"""
39 from collections import defaultdict
40 from types import SimpleNamespace
41 modmap = SimpleNamespace(
42 by_name=defaultdict(list),
43 by_id=defaultdict(list),
44 top_level={},
45 )
46 for modname, module in sys.modules.items():
47 if modname in ('__main__', '__mp_main__') or not isinstance(module, ModuleType):
48 continue
49 if '.' not in modname:
50 modmap.top_level[id(module)] = modname
51 for objname, modobj in module.__dict__.items():
52 modmap.by_name[objname].append((modobj, modname))
53 modmap.by_id[id(modobj)].append((modobj, objname, modname))
54 return modmap
56IMPORTED_AS_TYPES = (ModuleType, TypeType, FunctionType, MethodType, BuiltinMethodType)
57if 'PyCapsuleType' in _reverse_typemap:
58 IMPORTED_AS_TYPES += (_reverse_typemap['PyCapsuleType'],)
59IMPORTED_AS_MODULES = ('ctypes', 'typing', 'subprocess', 'threading',
60 r'concurrent\.futures(\.\w+)?', r'multiprocessing(\.\w+)?')
61IMPORTED_AS_MODULES = tuple(re.compile(x) for x in IMPORTED_AS_MODULES)
63def _lookup_module(modmap, name, obj, main_module):
64 """lookup name or id of obj if module is imported"""
65 for modobj, modname in modmap.by_name[name]:
66 if modobj is obj and sys.modules[modname] is not main_module:
67 return modname, name
68 __module__ = getattr(obj, '__module__', None)
69 if isinstance(obj, IMPORTED_AS_TYPES) or (__module__ is not None
70 and any(regex.fullmatch(__module__) for regex in IMPORTED_AS_MODULES)):
71 for modobj, objname, modname in modmap.by_id[id(obj)]:
72 if sys.modules[modname] is not main_module:
73 return modname, objname
74 return None, None
76def _stash_modules(main_module):
77 modmap = _module_map()
78 newmod = ModuleType(main_module.__name__)
80 imported = []
81 imported_as = []
82 imported_top_level = [] # keep separated for backward compatibility
83 original = {}
84 for name, obj in main_module.__dict__.items():
85 if obj is main_module:
86 original[name] = newmod # self-reference
87 elif obj is main_module.__dict__:
88 original[name] = newmod.__dict__
89 # Avoid incorrectly matching a singleton value in another package (ex.: __doc__).
90 elif any(obj is singleton for singleton in (None, False, True)) \
91 or isinstance(obj, ModuleType) and _is_builtin_module(obj): # always saved by ref
92 original[name] = obj
93 else:
94 source_module, objname = _lookup_module(modmap, name, obj, main_module)
95 if source_module is not None:
96 if objname == name:
97 imported.append((source_module, name))
98 else:
99 imported_as.append((source_module, objname, name))
100 else:
101 try:
102 imported_top_level.append((modmap.top_level[id(obj)], name))
103 except KeyError:
104 original[name] = obj
106 if len(original) < len(main_module.__dict__):
107 newmod.__dict__.update(original)
108 newmod.__dill_imported = imported
109 newmod.__dill_imported_as = imported_as
110 newmod.__dill_imported_top_level = imported_top_level
111 if getattr(newmod, '__loader__', None) is None and _is_imported_module(main_module):
112 # Trick _is_imported_module() to force saving as an imported module.
113 newmod.__loader__ = True # will be discarded by save_module()
114 return newmod
115 else:
116 return main_module
118def _restore_modules(unpickler, main_module):
119 try:
120 for modname, name in main_module.__dict__.pop('__dill_imported'):
121 main_module.__dict__[name] = unpickler.find_class(modname, name)
122 for modname, objname, name in main_module.__dict__.pop('__dill_imported_as'):
123 main_module.__dict__[name] = unpickler.find_class(modname, objname)
124 for modname, name in main_module.__dict__.pop('__dill_imported_top_level'):
125 main_module.__dict__[name] = __import__(modname)
126 except KeyError:
127 pass
129#NOTE: 06/03/15 renamed main_module to main
130def dump_module(
131 filename = str(TEMPDIR/'session.pkl'),
132 module: Optional[Union[ModuleType, str]] = None,
133 refimported: bool = False,
134 **kwds
135) -> None:
136 """Pickle the current state of :py:mod:`__main__` or another module to a file.
138 Save the contents of :py:mod:`__main__` (e.g. from an interactive
139 interpreter session), an imported module, or a module-type object (e.g.
140 built with :py:class:`~types.ModuleType`), to a file. The pickled
141 module can then be restored with the function :py:func:`load_module`.
143 Parameters:
144 filename: a path-like object or a writable stream.
145 module: a module object or the name of an importable module. If `None`
146 (the default), :py:mod:`__main__` is saved.
147 refimported: if `True`, all objects identified as having been imported
148 into the module's namespace are saved by reference. *Note:* this is
149 similar but independent from ``dill.settings[`byref`]``, as
150 ``refimported`` refers to virtually all imported objects, while
151 ``byref`` only affects select objects.
152 **kwds: extra keyword arguments passed to :py:class:`Pickler()`.
154 Raises:
155 :py:exc:`PicklingError`: if pickling fails.
157 Examples:
159 - Save current interpreter session state:
161 >>> import dill
162 >>> squared = lambda x: x*x
163 >>> dill.dump_module() # save state of __main__ to /tmp/session.pkl
165 - Save the state of an imported/importable module:
167 >>> import dill
168 >>> import pox
169 >>> pox.plus_one = lambda x: x+1
170 >>> dill.dump_module('pox_session.pkl', module=pox)
172 - Save the state of a non-importable, module-type object:
174 >>> import dill
175 >>> from types import ModuleType
176 >>> foo = ModuleType('foo')
177 >>> foo.values = [1,2,3]
178 >>> import math
179 >>> foo.sin = math.sin
180 >>> dill.dump_module('foo_session.pkl', module=foo, refimported=True)
182 - Restore the state of the saved modules:
184 >>> import dill
185 >>> dill.load_module()
186 >>> squared(2)
187 4
188 >>> pox = dill.load_module('pox_session.pkl')
189 >>> pox.plus_one(1)
190 2
191 >>> foo = dill.load_module('foo_session.pkl')
192 >>> [foo.sin(x) for x in foo.values]
193 [0.8414709848078965, 0.9092974268256817, 0.1411200080598672]
195 *Changed in version 0.3.6:* Function ``dump_session()`` was renamed to
196 ``dump_module()``. Parameters ``main`` and ``byref`` were renamed to
197 ``module`` and ``refimported``, respectively.
199 Note:
200 Currently, ``dill.settings['byref']`` and ``dill.settings['recurse']``
201 don't apply to this function.`
202 """
203 for old_par, par in [('main', 'module'), ('byref', 'refimported')]:
204 if old_par in kwds:
205 message = "The argument %r has been renamed %r" % (old_par, par)
206 if old_par == 'byref':
207 message += " to distinguish it from dill.settings['byref']"
208 warnings.warn(message + ".", PendingDeprecationWarning)
209 if locals()[par]: # the defaults are None and False
210 raise TypeError("both %r and %r arguments were used" % (par, old_par))
211 refimported = kwds.pop('byref', refimported)
212 module = kwds.pop('main', module)
214 from .settings import settings
215 protocol = settings['protocol']
216 main = module
217 if main is None:
218 main = _main_module
219 elif isinstance(main, str):
220 main = _import_module(main)
221 if not isinstance(main, ModuleType):
222 raise TypeError("%r is not a module" % main)
223 if hasattr(filename, 'write'):
224 file = filename
225 else:
226 file = open(filename, 'wb')
227 try:
228 pickler = Pickler(file, protocol, **kwds)
229 pickler._original_main = main
230 if refimported:
231 main = _stash_modules(main)
232 pickler._main = main #FIXME: dill.settings are disabled
233 pickler._byref = False # disable pickling by name reference
234 pickler._recurse = False # disable pickling recursion for globals
235 pickler._session = True # is best indicator of when pickling a session
236 pickler._first_pass = True
237 pickler._main_modified = main is not pickler._original_main
238 pickler.dump(main)
239 finally:
240 if file is not filename: # if newly opened file
241 file.close()
242 return
244# Backward compatibility.
245def dump_session(filename=str(TEMPDIR/'session.pkl'), main=None, byref=False, **kwds):
246 warnings.warn("dump_session() has been renamed dump_module()", PendingDeprecationWarning)
247 dump_module(filename, module=main, refimported=byref, **kwds)
248dump_session.__doc__ = dump_module.__doc__
250class _PeekableReader:
251 """lightweight stream wrapper that implements peek()"""
252 def __init__(self, stream):
253 self.stream = stream
254 def read(self, n):
255 return self.stream.read(n)
256 def readline(self):
257 return self.stream.readline()
258 def tell(self):
259 return self.stream.tell()
260 def close(self):
261 return self.stream.close()
262 def peek(self, n):
263 stream = self.stream
264 try:
265 if hasattr(stream, 'flush'): stream.flush()
266 position = stream.tell()
267 stream.seek(position) # assert seek() works before reading
268 chunk = stream.read(n)
269 stream.seek(position)
270 return chunk
271 except (AttributeError, OSError):
272 raise NotImplementedError("stream is not peekable: %r", stream) from None
274def _make_peekable(stream):
275 """return stream as an object with a peek() method"""
276 import io
277 if hasattr(stream, 'peek'):
278 return stream
279 if not (hasattr(stream, 'tell') and hasattr(stream, 'seek')):
280 try:
281 return io.BufferedReader(stream)
282 except Exception:
283 pass
284 return _PeekableReader(stream)
286def _identify_module(file, main=None):
287 """identify the name of the module stored in the given file-type object"""
288 from pickletools import genops
289 UNICODE = {'UNICODE', 'BINUNICODE', 'SHORT_BINUNICODE'}
290 found_import = False
291 try:
292 for opcode, arg, pos in genops(file.peek(256)):
293 if not found_import:
294 if opcode.name in ('GLOBAL', 'SHORT_BINUNICODE') and \
295 arg.endswith('_import_module'):
296 found_import = True
297 else:
298 if opcode.name in UNICODE:
299 return arg
300 else:
301 raise UnpicklingError("reached STOP without finding main module")
302 except (NotImplementedError, ValueError) as error:
303 # ValueError occours when the end of the chunk is reached (without a STOP).
304 if isinstance(error, NotImplementedError) and main is not None:
305 # file is not peekable, but we have main.
306 return None
307 raise UnpicklingError("unable to identify main module") from error
309def load_module(
310 filename = str(TEMPDIR/'session.pkl'),
311 module: Optional[Union[ModuleType, str]] = None,
312 **kwds
313) -> Optional[ModuleType]:
314 """Update the selected module (default is :py:mod:`__main__`) with
315 the state saved at ``filename``.
317 Restore a module to the state saved with :py:func:`dump_module`. The
318 saved module can be :py:mod:`__main__` (e.g. an interpreter session),
319 an imported module, or a module-type object (e.g. created with
320 :py:class:`~types.ModuleType`).
322 When restoring the state of a non-importable module-type object, the
323 current instance of this module may be passed as the argument ``main``.
324 Otherwise, a new instance is created with :py:class:`~types.ModuleType`
325 and returned.
327 Parameters:
328 filename: a path-like object or a readable stream.
329 module: a module object or the name of an importable module;
330 the module name and kind (i.e. imported or non-imported) must
331 match the name and kind of the module stored at ``filename``.
332 **kwds: extra keyword arguments passed to :py:class:`Unpickler()`.
334 Raises:
335 :py:exc:`UnpicklingError`: if unpickling fails.
336 :py:exc:`ValueError`: if the argument ``main`` and module saved
337 at ``filename`` are incompatible.
339 Returns:
340 A module object, if the saved module is not :py:mod:`__main__` or
341 a module instance wasn't provided with the argument ``main``.
343 Examples:
345 - Save the state of some modules:
347 >>> import dill
348 >>> squared = lambda x: x*x
349 >>> dill.dump_module() # save state of __main__ to /tmp/session.pkl
350 >>>
351 >>> import pox # an imported module
352 >>> pox.plus_one = lambda x: x+1
353 >>> dill.dump_module('pox_session.pkl', module=pox)
354 >>>
355 >>> from types import ModuleType
356 >>> foo = ModuleType('foo') # a module-type object
357 >>> foo.values = [1,2,3]
358 >>> import math
359 >>> foo.sin = math.sin
360 >>> dill.dump_module('foo_session.pkl', module=foo, refimported=True)
362 - Restore the state of the interpreter:
364 >>> import dill
365 >>> dill.load_module() # updates __main__ from /tmp/session.pkl
366 >>> squared(2)
367 4
369 - Load the saved state of an importable module:
371 >>> import dill
372 >>> pox = dill.load_module('pox_session.pkl')
373 >>> pox.plus_one(1)
374 2
375 >>> import sys
376 >>> pox in sys.modules.values()
377 True
379 - Load the saved state of a non-importable module-type object:
381 >>> import dill
382 >>> foo = dill.load_module('foo_session.pkl')
383 >>> [foo.sin(x) for x in foo.values]
384 [0.8414709848078965, 0.9092974268256817, 0.1411200080598672]
385 >>> import math
386 >>> foo.sin is math.sin # foo.sin was saved by reference
387 True
388 >>> import sys
389 >>> foo in sys.modules.values()
390 False
392 - Update the state of a non-importable module-type object:
394 >>> import dill
395 >>> from types import ModuleType
396 >>> foo = ModuleType('foo')
397 >>> foo.values = ['a','b']
398 >>> foo.sin = lambda x: x*x
399 >>> dill.load_module('foo_session.pkl', module=foo)
400 >>> [foo.sin(x) for x in foo.values]
401 [0.8414709848078965, 0.9092974268256817, 0.1411200080598672]
403 *Changed in version 0.3.6:* Function ``load_session()`` was renamed to
404 ``load_module()``. Parameter ``main`` was renamed to ``module``.
406 See also:
407 :py:func:`load_module_asdict` to load the contents of module saved
408 with :py:func:`dump_module` into a dictionary.
409 """
410 if 'main' in kwds:
411 warnings.warn(
412 "The argument 'main' has been renamed 'module'.",
413 PendingDeprecationWarning
414 )
415 if module is not None:
416 raise TypeError("both 'module' and 'main' arguments were used")
417 module = kwds.pop('main')
418 main = module
419 if hasattr(filename, 'read'):
420 file = filename
421 else:
422 file = open(filename, 'rb')
423 try:
424 file = _make_peekable(file)
425 #FIXME: dill.settings are disabled
426 unpickler = Unpickler(file, **kwds)
427 unpickler._session = True
429 # Resolve unpickler._main
430 pickle_main = _identify_module(file, main)
431 if main is None and pickle_main is not None:
432 main = pickle_main
433 if isinstance(main, str):
434 if main.startswith('__runtime__.'):
435 # Create runtime module to load the session into.
436 main = ModuleType(main.partition('.')[-1])
437 else:
438 main = _import_module(main)
439 if main is not None:
440 if not isinstance(main, ModuleType):
441 raise TypeError("%r is not a module" % main)
442 unpickler._main = main
443 else:
444 main = unpickler._main
446 # Check against the pickle's main.
447 is_main_imported = _is_imported_module(main)
448 if pickle_main is not None:
449 is_runtime_mod = pickle_main.startswith('__runtime__.')
450 if is_runtime_mod:
451 pickle_main = pickle_main.partition('.')[-1]
452 error_msg = "can't update{} module{} %r with the saved state of{} module{} %r"
453 if is_runtime_mod and is_main_imported:
454 raise ValueError(
455 error_msg.format(" imported", "", "", "-type object")
456 % (main.__name__, pickle_main)
457 )
458 if not is_runtime_mod and not is_main_imported:
459 raise ValueError(
460 error_msg.format("", "-type object", " imported", "")
461 % (pickle_main, main.__name__)
462 )
463 if main.__name__ != pickle_main:
464 raise ValueError(error_msg.format("", "", "", "") % (main.__name__, pickle_main))
466 # This is for find_class() to be able to locate it.
467 if not is_main_imported:
468 runtime_main = '__runtime__.%s' % main.__name__
469 sys.modules[runtime_main] = main
471 loaded = unpickler.load()
472 finally:
473 if not hasattr(filename, 'read'): # if newly opened file
474 file.close()
475 try:
476 del sys.modules[runtime_main]
477 except (KeyError, NameError):
478 pass
479 assert loaded is main
480 _restore_modules(unpickler, main)
481 if main is _main_module or main is module:
482 return None
483 else:
484 return main
486# Backward compatibility.
487def load_session(filename=str(TEMPDIR/'session.pkl'), main=None, **kwds):
488 warnings.warn("load_session() has been renamed load_module().", PendingDeprecationWarning)
489 load_module(filename, module=main, **kwds)
490load_session.__doc__ = load_module.__doc__
492def load_module_asdict(
493 filename = str(TEMPDIR/'session.pkl'),
494 update: bool = False,
495 **kwds
496) -> dict:
497 """
498 Load the contents of a saved module into a dictionary.
500 ``load_module_asdict()`` is the near-equivalent of::
502 lambda filename: vars(dill.load_module(filename)).copy()
504 however, does not alter the original module. Also, the path of
505 the loaded module is stored in the ``__session__`` attribute.
507 Parameters:
508 filename: a path-like object or a readable stream
509 update: if `True`, initialize the dictionary with the current state
510 of the module prior to loading the state stored at filename.
511 **kwds: extra keyword arguments passed to :py:class:`Unpickler()`
513 Raises:
514 :py:exc:`UnpicklingError`: if unpickling fails
516 Returns:
517 A copy of the restored module's dictionary.
519 Note:
520 If ``update`` is True, the corresponding module may first be imported
521 into the current namespace before the saved state is loaded from
522 filename to the dictionary. Note that any module that is imported into
523 the current namespace as a side-effect of using ``update`` will not be
524 modified by loading the saved module in filename to a dictionary.
526 Example:
527 >>> import dill
528 >>> alist = [1, 2, 3]
529 >>> anum = 42
530 >>> dill.dump_module()
531 >>> anum = 0
532 >>> new_var = 'spam'
533 >>> main = dill.load_module_asdict()
534 >>> main['__name__'], main['__session__']
535 ('__main__', '/tmp/session.pkl')
536 >>> main is globals() # loaded objects don't reference globals
537 False
538 >>> main['alist'] == alist
539 True
540 >>> main['alist'] is alist # was saved by value
541 False
542 >>> main['anum'] == anum # changed after the session was saved
543 False
544 >>> new_var in main # would be True if the option 'update' was set
545 False
546 """
547 if 'module' in kwds:
548 raise TypeError("'module' is an invalid keyword argument for load_module_asdict()")
549 if hasattr(filename, 'read'):
550 file = filename
551 else:
552 file = open(filename, 'rb')
553 try:
554 file = _make_peekable(file)
555 main_name = _identify_module(file)
556 old_main = sys.modules.get(main_name)
557 main = ModuleType(main_name)
558 if update:
559 if old_main is None:
560 old_main = _import_module(main_name)
561 main.__dict__.update(old_main.__dict__)
562 else:
563 main.__builtins__ = __builtin__
564 sys.modules[main_name] = main
565 load_module(file, **kwds)
566 finally:
567 if not hasattr(filename, 'read'): # if newly opened file
568 file.close()
569 try:
570 if old_main is None:
571 del sys.modules[main_name]
572 else:
573 sys.modules[main_name] = old_main
574 except NameError: # failed before setting old_main
575 pass
576 main.__session__ = str(filename)
577 return main.__dict__
580# Internal exports for backward compatibility with dill v0.3.5.1
581# Can't be placed in dill._dill because of circular import problems.
582for name in (
583 '_lookup_module', '_module_map', '_restore_modules', '_stash_modules',
584 'dump_session', 'load_session' # backward compatibility functions
585):
586 setattr(_dill, name, globals()[name])
587del name