Skip to content

Commit

Permalink
new: optional imports
Browse files Browse the repository at this point in the history
  • Loading branch information
hagne committed Sep 10, 2024
1 parent e4663a3 commit 62868e9
Showing 1 changed file with 58 additions and 0 deletions.
58 changes: 58 additions & 0 deletions atmPy/opt_imports.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# optional_imports.py
class OptionalImport:
def __init__(self, name, submodules = None):
self.module_available = False
self.module = None
self.name = name

self.submodules = submodules

self._attempt_import()
self._attempt_import_submods()

def _attempt_import_submods(self):
if (not isinstance(self.submodules, type(None))) and self.module_available:
submodules = self.submodules

if not isinstance(submodules, list):
submodules = [submodules,]

for mod in submodules:
__import__(f'{self.name}.{mod}')


def _attempt_import(self):
try:
self.module = __import__(self.name)
self.module_available = True
except ImportError:
self.module_available = False

def __getattr__(self, item):
if not self.module_available:
raise ImportError(f"{self.name} is required for this feature. Please install it to use this functionality.")
return getattr(self.module, item)

# Creating the pandas facade
statsmodels = OptionalImport('statsmodels', submodules = ['api',])

#Todo: remove those and replace with the submodule kwarg
statsmodels_api = OptionalImport('statsmodels.api')
statsmodels_nonparametric_smoothers_lowess = OptionalImport('statsmodels.nonparametric.smoothers_lowess')
# statsmodels_robust = OptionalImport('statsmodels.robust')

timezonefinder = OptionalImport('timezonefinder')


mpl_toolkits_basemap = OptionalImport('mpl_toolkits.basemap')
metpy = OptionalImport('metpy')
pptx = OptionalImport('pptx')

ephem = OptionalImport('ephem')

pysolar = OptionalImport('pysolar')

geopy = OptionalImport('geopy', submodules = 'distance')

cartopy = OptionalImport('cartopy', submodules = 'io.img_tiles')
pygam = OptionalImport('pygam')

0 comments on commit 62868e9

Please sign in to comment.