Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix logic for no geoviews explorer #1451

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 5 additions & 11 deletions hvplot/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@
process_derived_datetime_pandas,
_convert_col_names_to_str,
import_datashader,
geoviews_is_available,
)
from .utilities import hvplot_extension

Expand Down Expand Up @@ -646,6 +647,10 @@ def __init__(

self.dynamic = dynamic
self.geo = any([geo, crs, global_extent, projection, project, coastline, features])
# Try importing geoviews if geo-features requested
if self.geo or self.datatype == 'geopandas':
geoviews_is_available(raise_error=True)

self.crs = self._process_crs(data, crs) if self.geo else None
self.output_projection = self.crs
self.project = project
Expand All @@ -655,17 +660,6 @@ def __init__(
self.tiles_opts = tiles_opts or {}
self.sort_date = sort_date

# Import geoviews if geo-features requested
if self.geo or self.datatype == 'geopandas':
try:
import geoviews # noqa
except ImportError:
raise ImportError(
'In order to use geo-related features '
'the geoviews library must be available. '
'It can be installed with:\n conda '
'install geoviews'
ahuang11 marked this conversation as resolved.
Show resolved Hide resolved
)
if self.geo:
if self.kind not in self._geo_types:
param.main.param.warning(
Expand Down
7 changes: 7 additions & 0 deletions hvplot/tests/testui.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import re
from textwrap import dedent
from unittest.mock import patch

import numpy as np
import holoviews as hv
Expand Down Expand Up @@ -415,3 +416,9 @@ def test_max_rows_sample():
ui = hvplot.explorer(df, x='x', y='y', by=['#'], kind='scatter')
assert len(ui._data) == MAX_ROWS
assert not ui._data.equals(df.head(MAX_ROWS))


def test_explorer_geo_no_import_error_when_false():
da = ds_air_temperature['air'].isel(time=0)
with patch('hvplot.util.geoviews_is_available', return_value=False):
assert hvplot.explorer(da, x='lon', y='lat', geo=False)
21 changes: 21 additions & 0 deletions hvplot/tests/testutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
Tests utilities to convert data and projections
"""

from unittest.mock import patch
import numpy as np
import pandas as pd
import panel as pn
Expand All @@ -18,6 +19,7 @@

from hvplot.util import (
check_crs,
geoviews_is_available,
is_list_like,
process_crs,
process_xarray,
Expand Down Expand Up @@ -383,3 +385,22 @@ def test_is_geodataframe_spatialpandas_dask():
def test_is_geodataframe_classic_dataframe():
df = pd.DataFrame({'geometry': [None, None], 'name': ['A', 'B']})
assert not is_geodataframe(df)


@pytest.mark.geo
def test_geoviews_is_available():
assert geoviews_is_available(raise_error=True)


def test_geoviews_is_available_no_raise():
with patch('hvplot.util.find_spec', return_value=None):
result = geoviews_is_available(raise_error=False)
assert result is False


def test_geoviews_is_available_with_raise():
with patch('hvplot.util.find_spec', return_value=None):
with pytest.raises(
ImportError, match='GeoViews must be installed to enable the geographic options.'
):
geoviews_is_available(raise_error=True)
14 changes: 3 additions & 11 deletions hvplot/ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

from .converter import HoloViewsConverter as _hvConverter
from .plotting import hvPlot as _hvPlot
from .util import is_geodataframe, is_xarray, instantiate_crs_str
from .util import is_geodataframe, is_xarray, instantiate_crs_str, geoviews_is_available

# Defaults
KINDS = {
Expand Down Expand Up @@ -361,17 +361,9 @@ class Geographic(Controls):
_widgets_kwargs = {'geo': {'type': pn.widgets.Toggle}}

def __init__(self, data, **params):
gv_available = False
try:
import geoviews # noqa

gv_available = True
except ImportError:
pass

geo_params = GEO_KEYS + ['geo']
if not gv_available and any(p in params for p in geo_params):
raise ImportError('GeoViews must be installed to enable the geographic options.')
gv_available = geoviews_is_available(raise_error=any(params.get(p) for p in geo_params))

super().__init__(data, **params)
if not gv_available:
for p in geo_params:
Expand Down
12 changes: 12 additions & 0 deletions hvplot/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
Provides utilities to convert data and projections
"""

from importlib.util import find_spec
import sys

from collections.abc import Hashable
Expand Down Expand Up @@ -750,3 +751,14 @@ def relabel_redim(hv_obj, relabel_kwargs, redim_kwargs):
if redim_kwargs:
hv_obj = hv_obj.redim(**redim_kwargs)
return hv_obj


def geoviews_is_available(raise_error: bool = False):
"""
Check if GeoViews is available and raise an ImportError if not.
"""
gv_available = find_spec('geoviews') is not None

if not gv_available and raise_error:
raise ImportError('GeoViews must be installed to enable the geographic options.')
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I got confused a minute here, does find_spec('geoviews') actually import GeoViews?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, but it checks if it is installed.

image

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes ok that's what I thought. I was confused as then an ImportError is raised. Since importing GeoViews comes with side effects (registering lots of stuff), I'd like to make sure we're not removing an important step there. @hoxbro did you suggest find_spec for performance reasons?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just as an alternative and also easier to patch in the test suite.

I think it is okay to use find_spec when we check if it is available. We should import geoviews in the code, where there previously was a try/except, to get those juicy side effects.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I also think the error message is wrong here. As it no longer only affects the UI code.

return gv_available
Loading