Skip to content

Commit

Permalink
Add import error helper
Browse files Browse the repository at this point in the history
  • Loading branch information
mraspaud committed Nov 18, 2022
1 parent be65fb6 commit 284893a
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
6 changes: 5 additions & 1 deletion satpy/readers/insat3d_img_l1b_h5.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@
import dask.array as da
import numpy as np
import xarray as xr
from datatree import DataTree

from satpy.utils import import_error_helper

with import_error_helper("xarray-datatree"):
from datatree import DataTree

from satpy.readers.file_handlers import BaseFileHandler

Expand Down
19 changes: 18 additions & 1 deletion satpy/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,15 @@
import pytest
import xarray as xr

from satpy.utils import angle2xyz, get_satpos, lonlat2xyz, proj_units_to_meters, xyz2angle, xyz2lonlat
from satpy.utils import (
angle2xyz,
get_satpos,
import_error_helper,
lonlat2xyz,
proj_units_to_meters,
xyz2angle,
xyz2lonlat,
)


class TestUtils(unittest.TestCase):
Expand Down Expand Up @@ -569,3 +577,12 @@ def test_convert_remote_files_to_fsspec_storage_options(open_files):
_ = convert_remote_files_to_fsspec(filenames, storage_options=storage_options)

open_files.assert_called_once_with(filenames, **storage_options)


def test_import_error_helper():
"""Test the import error helper."""
module = "some_crazy_name_for_unknow_dependency_module"
with pytest.raises(ImportError) as err:
with import_error_helper(module):
import unknow_dependency_module # noqa
assert module in str(err)
10 changes: 10 additions & 0 deletions satpy/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import logging
import os
import warnings
from contextlib import contextmanager
from typing import Mapping, Optional
from urllib.parse import urlparse

Expand Down Expand Up @@ -680,3 +681,12 @@ def _merge_storage_options(storage_options, storage_opt_dict):
storage_options = storage_opt_dict

return storage_options


@contextmanager
def import_error_helper(dependency_name):
"""Give more info on an import error."""
try:
yield
except ImportError as err:
raise ImportError(err.msg + f" It can be installed with the {dependency_name} package.")

0 comments on commit 284893a

Please sign in to comment.