Debian Codegraph @

traits/testing/optional_dependencies.py

raw
1 # (C) Copyright 2005-2023 Enthought, Inc., Austin, TX
2 # All rights reserved.
3 #
4 # This software is provided without warranty under the terms of the BSD
5 # license included in LICENSE.txt and may be redistributed only under
6 # the conditions described in the aforementioned license. The license
7 # is also available online at http://www.enthought.com/licenses/BSD.txt
8 #
9 # Thanks for using Enthought open source!
10
11 import importlib
12 import unittest
13
14
15 def optional_import(name):
16 """
17 Optionally import a module, returning None if that module is unavailable.
18
19 Parameters
20 ----------
21 name : Str
22 The name of the module being imported.
23
24 Returns
25 -------
26 None or module
27 None if the module is not available, and the module otherwise.
28
29 """
30 try:
31 module = importlib.import_module(name)
32 except ImportError:
33 return None
34 else:
35 return module
36
37
38 # Commonly-used unittest skip decorators.
39 cython = optional_import("cython")
40 requires_cython = unittest.skipIf(cython is None, "Cython not available")
41
42 mypy = optional_import("mypy")
43 requires_mypy = unittest.skipIf(mypy is None, "Mypy not available")
44
45 numpy = optional_import("numpy")
46 requires_numpy = unittest.skipIf(numpy is None, "NumPy not available")
47
48 numpy_typing = optional_import("numpy.typing")
49 requires_numpy_typing = unittest.skipIf(
50 numpy_typing is None, "numpy.typing not available")
51
52 pkg_resources = optional_import("pkg_resources")
53 requires_pkg_resources = unittest.skipIf(
54 pkg_resources is None, "pkg_resources not available"
55 )
56
57 pyface = optional_import("pyface")
58 requires_pyface = unittest.skipIf(pyface is None, "Pyface not available")
59
60 sphinx = optional_import("sphinx")
61 requires_sphinx = unittest.skipIf(sphinx is None, "Sphinx not available")
62
63 traitsui = optional_import("traitsui")
64 requires_traitsui = unittest.skipIf(traitsui is None, "TraitsUI not available")
65 # Import traitsui.api so that client code can use traitsui.api directly without
66 # an extra import.
67 if traitsui is not None:
68 import traitsui.api