Skip to content

Commit 4e9b114

Browse files
committed
Add an optional_imports module.
This is a stand-alone module to do the following: * Don’t import optional things until we need them * Keep all the optional imports centralized
1 parent f47a593 commit 4e9b114

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

plotly/optional_imports.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
"""
2+
Stand-alone module to provide information about whether optional deps exist.
3+
4+
"""
5+
from __future__ import absolute_import
6+
7+
from importlib import import_module
8+
9+
_not_importable = set()
10+
11+
12+
def get_module(name):
13+
"""
14+
Return module or None. Absolute import is required.
15+
16+
:param (str) name: Dot-separated module path. E.g., 'scipy.stats'.
17+
:raise: (ImportError) Only when exc_msg is defined.
18+
:return: (module|None) If import succeeds, the module will be returned.
19+
20+
"""
21+
if name not in _not_importable:
22+
try:
23+
return import_module(name)
24+
except ImportError:
25+
_not_importable.add(name)

plotly/tests/test_core/test_optional_imports/__init__.py

Whitespace-only changes.
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from __future__ import absolute_import
2+
3+
from unittest import TestCase
4+
5+
from plotly.optional_imports import get_module
6+
7+
8+
class OptionalImportsTest(TestCase):
9+
10+
def test_get_module_exists(self):
11+
import math
12+
module = get_module('math')
13+
self.assertIsNotNone(module)
14+
self.assertEqual(math, module)
15+
16+
def test_get_module_exists_submodule(self):
17+
import requests.sessions
18+
module = get_module('requests.sessions')
19+
self.assertIsNotNone(module)
20+
self.assertEqual(requests.sessions, module)
21+
22+
def test_get_module_does_not_exist(self):
23+
module = get_module('hoopla')
24+
self.assertIsNone(module)

0 commit comments

Comments
 (0)