File: optional_imports.py

package info (click to toggle)
plotly 4.14.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 77,744 kB
  • sloc: javascript: 324,821; python: 319,618; sh: 49; makefile: 4
file content (36 lines) | stat: -rw-r--r-- 999 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
"""
Stand-alone module to provide information about whether optional deps exist.

"""
from __future__ import absolute_import

from importlib import import_module
import logging
import sys

logger = logging.getLogger(__name__)
_not_importable = set()


def get_module(name, should_load=True):
    """
    Return module or None. Absolute import is required.

    :param (str) name: Dot-separated module path. E.g., 'scipy.stats'.
    :raise: (ImportError) Only when exc_msg is defined.
    :return: (module|None) If import succeeds, the module will be returned.

    """
    if name in sys.modules:
        return sys.modules[name]
    if not should_load:
        return None
    if name not in _not_importable:
        try:
            return import_module(name)
        except ImportError:
            _not_importable.add(name)
        except Exception as e:
            _not_importable.add(name)
            msg = "Error importing optional module {}".format(name)
            logger.exception(msg)