-
-
Notifications
You must be signed in to change notification settings - Fork 386
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #89 from ColCarroll/optional_deps
Add optional dependency class
- Loading branch information
Showing
3 changed files
with
38 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
#pylint: disable=invalid-name | ||
from .optional_dep import OptionalDep | ||
pymc3 = OptionalDep('pymc3') | ||
altair = OptionalDep('altair') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import importlib | ||
import sys | ||
|
||
|
||
class OptionalDep(object): | ||
"""Wrapper for optional library dependencies. | ||
Note that since only __getattr__ is implemented, if this object implements | ||
methods, those will be used *before* the true library is called. | ||
For example | ||
class PyMC3(OptionalDep): | ||
def trace_to_dataframe(*args, **kwargs): | ||
... | ||
pm = PyMC3() | ||
pm.trace_to_dataframe(trace) # calls the OptionalDep method | ||
pm.Normal('x', 0, 1) # calls pymc3.Normal | ||
""" | ||
def __init__(self, name): | ||
self.__name = name | ||
self.__module = None | ||
|
||
def __getattr__(self, name): | ||
if self.__module is None: | ||
try: | ||
self.__module = importlib.import_module(self.__name) | ||
except ModuleNotFoundError: | ||
raise ModuleNotFoundError( | ||
'Failed to import optional module {}'.format(self.__name), sys.exc_info()[0]) | ||
return getattr(self.__module, name) |