Skip to content

Commit

Permalink
ENH: Improve handling of optional Cartopy map features
Browse files Browse the repository at this point in the history
Use the module-level __getattr__ support in Python 3.7 to dynamically
handle access to the CartoPy map features and only warn *upon use* if
CartoPy isn't installed.
  • Loading branch information
dopplershift committed Jun 22, 2021
1 parent acd279b commit 4b827af
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
21 changes: 16 additions & 5 deletions src/metpy/plots/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

# Trigger matplotlib wrappers
from . import _mpl # noqa: F401
from . import cartopy_utils
from ._util import (add_metpy_logo, add_timestamp, add_unidata_logo, # noqa: F401
convert_gempak_color)
from .ctables import * # noqa: F403
Expand All @@ -25,10 +26,20 @@
__all__.extend(wx_symbols.__all__) # pylint: disable=undefined-variable
__all__.extend(['add_metpy_logo', 'add_timestamp', 'add_unidata_logo',
'convert_gempak_color'])
try:
from .cartopy_utils import USCOUNTIES, USSTATES # noqa: F401
__all__.extend(['USCOUNTIES', 'USSTATES'])
except ImportError:
logger.warning('Cannot import USCOUNTIES and USSTATES without Cartopy installed.')

set_module(globals())


def __getattr__(name):
"""Handle warning if Cartopy map features are not available."""
if name in cartopy_utils.__all__:
try:
return getattr(cartopy_utils, name)
except AttributeError:
logger.warning(f'Cannot use {name} without Cartopy installed.')

raise AttributeError(f'module {__name__!r} has no attribute {name!r}')


def __dir__():
return sorted(__all__ + cartopy_utils.__all__)
2 changes: 2 additions & 0 deletions src/metpy/plots/cartopy_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ def with_scale(self, new_scale):
except ImportError:
pass

__all__ = ['USCOUNTIES', 'USSTATES']


def import_cartopy():
"""Import CartoPy; return a stub if unable.
Expand Down

0 comments on commit 4b827af

Please sign in to comment.