pytorch
1import functools
2import importlib.util
3
4import torch
5
6
7def _check_module_exists(name: str) -> bool:
8r"""Returns if a top-level module with :attr:`name` exists *without**
9importing it. This is generally safer than try-catch block around a
10`import X`. It avoids third party libraries breaking assumptions of some of
11our tests, e.g., setting multiprocessing start method when imported
12(see librosa/#747, torchvision/#544).
13"""
14try:
15spec = importlib.util.find_spec(name)
16return spec is not None
17except ImportError:
18return False
19
20
21@functools.lru_cache
22def dill_available():
23return (
24_check_module_exists("dill")
25# dill fails to import under torchdeploy
26and not torch._running_with_deploy()
27)
28
29
30@functools.lru_cache
31def import_dill():
32if not dill_available():
33return None
34
35import dill
36
37# XXX: By default, dill writes the Pickler dispatch table to inject its
38# own logic there. This globally affects the behavior of the standard library
39# pickler for any user who transitively depends on this module!
40# Undo this extension to avoid altering the behavior of the pickler globally.
41dill.extend(use_dill=False)
42return dill
43