Skip to content

Commit

Permalink
Merge pull request #89 from ColCarroll/optional_deps
Browse files Browse the repository at this point in the history
Add optional dependency class
  • Loading branch information
ColCarroll committed May 21, 2018
2 parents b7b8a39 + 23fe554 commit 461d07f
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
3 changes: 2 additions & 1 deletion .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ disable=missing-docstring,
too-many-locals,
too-many-branches,
too-many-statements,
no-self-use
no-self-use,
too-few-public-methods

# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
Expand Down
4 changes: 4 additions & 0 deletions arviz/compat/__init__.py
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')
32 changes: 32 additions & 0 deletions arviz/compat/optional_dep.py
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)

0 comments on commit 461d07f

Please sign in to comment.