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

Update Ruff in pre-commit and report panel comms in show_versions #5853

Merged
merged 8 commits into from
Aug 16, 2023
Merged
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
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ repos:
exclude: \.min\.js$
- id: trailing-whitespace
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.276
rev: v0.0.284
hooks:
- id: ruff
args: [holoviews]
Expand Down
2 changes: 1 addition & 1 deletion holoviews/core/data/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,7 @@ def closest(self, coords=[], **kwargs):
if len(kwargs) > 1:
raise NotImplementedError("Closest method currently only "
"supports 1D indexes")
samples = list(kwargs.values())[0]
samples = next(iter(kwargs.values()))
coords = samples if isinstance(samples, list) else [samples]

xs = self.dimension_values(0)
Expand Down
4 changes: 2 additions & 2 deletions holoviews/core/data/dictionary.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def unpack_scalar(cls, dataset, data):
"""
if len(data) != 1:
return data
key = list(data.keys())[0]
key = next(iter(data.keys()))

if len(data[key]) == 1 and key in dataset.vdims:
scalar = data[key][0]
Expand Down Expand Up @@ -331,7 +331,7 @@ def select(cls, dataset, selection_mask=None, **selection):
data[k] = v
else:
data[k] = v[selection_mask]
if indexed and len(list(data.values())[0]) == 1 and len(dataset.vdims) == 1:
if indexed and len(next(iter(data.values()))) == 1 and len(dataset.vdims) == 1:
value = data[dataset.vdims[0].name]
return value if isscalar(value) else value[0]
return data
Expand Down
14 changes: 7 additions & 7 deletions holoviews/core/data/grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,9 +132,9 @@ def init(cls, eltype, data, kdims, vdims):
'by the key dimensions. Expected %d-D array, '
'found %d-D array.' % (vdim, len(expected), len(shape)))
elif any((s!=e and (s+1)!=e) for s, e in zip(shape, valid_shape)):
raise error('Key dimension values and value array {} '
'shapes do not match. Expected shape {}, '
'actual shape: {}'.format(vdim, valid_shape, shape), cls)
raise error(f'Key dimension values and value array {vdim} '
f'shapes do not match. Expected shape {valid_shape}, '
f'actual shape: {shape}', cls)
return data, {'kdims':kdims, 'vdims':vdims}, {}


Expand Down Expand Up @@ -557,17 +557,17 @@ def select(cls, dataset, selection_mask=None, **selection):
if irregular:
if np.isscalar(ind) or isinstance(ind, (set, list)):
raise IndexError("Indexing not supported for irregularly "
"sampled data. {} value along {} dimension."
"must be a slice or 2D boolean mask.".format(ind, dim))
f"sampled data. {ind} value along {dim} dimension."
"must be a slice or 2D boolean mask.")
mask = mask.max(axis=i)
elif dataset._binned:
edges = cls.coords(dataset, dim, False, edges=True)
inds = np.argwhere(mask)
if np.isscalar(ind):
emin, emax = edges.min(), edges.max()
if ind < emin:
raise IndexError("Index {} less than lower bound "
"of {} for {} dimension.".format(ind, emin, dim))
raise IndexError(f"Index {ind} less than lower bound "
f"of {emin} for {dim} dimension.")
elif ind >= emax:
raise IndexError("Index {} more than or equal to upper bound "
"of {} for {} dimension.".format(ind, emax, dim))
Expand Down
8 changes: 4 additions & 4 deletions holoviews/core/data/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,9 @@ def init(cls, eltype, data, kdims, vdims):
shape = data.shape[:2]
error = DataError if len(shape) > 1 and not eltype._binned else ValueError
if shape != expected and not (not expected and shape == (1,)):
raise error('Key dimension values and value array {} '
'shapes do not match. Expected shape {}, '
'actual shape: {}'.format(vdims[0], expected, shape), cls)
raise error(f'Key dimension values and value array {vdims[0]} '
f'shapes do not match. Expected shape {expected}, '
f'actual shape: {shape}', cls)

if not isinstance(data, np.ndarray) or data.ndim not in [2, 3]:
raise ValueError('ImageInterface expects a 2D array.')
Expand Down Expand Up @@ -297,7 +297,7 @@ def unpack_scalar(cls, dataset, data):
"""
if np.isscalar(data) or len(data) != 1:
return data
key = list(data.keys())[0]
key = next(iter(data.keys()))

if len(data[key]) == 1 and key in dataset.vdims:
return data[key][0]
Expand Down
4 changes: 2 additions & 2 deletions holoviews/core/data/multipath.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ def init(cls, eltype, data, kdims, vdims):
if hasattr(Interface.interfaces.get(dt), 'has_holes')]
geom_type = d.get('geom_type')
if geom_type is not None and geom_type not in cls.geom_types:
raise DataError("Geometry type '{}' not recognized, "
"must be one of {}.".format(geom_type, cls.geom_types))
raise DataError(f"Geometry type '{geom_type}' not recognized, "
f"must be one of {cls.geom_types}.")
else:
datatype = [dt for dt in datatype
if hasattr(Interface.interfaces.get(dt), 'geom_type')]
Expand Down
6 changes: 3 additions & 3 deletions holoviews/core/data/xarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,13 +229,13 @@ def retrieve_unit_and_label(dim):
undeclared.append(c)
if undeclared and eltype.param.kdims.bounds[1] not in (0, None):
raise DataError(
'The coordinates on the {!r} DataArray do not match the '
f'The coordinates on the {vdim.name!r} DataArray do not match the '
'provided key dimensions (kdims). The following coords '
'were left unspecified: {!r}. If you are requesting a '
f'were left unspecified: {undeclared!r}. If you are requesting a '
'lower dimensional view such as a histogram cast '
'the xarray to a columnar format using the .to_dataframe '
'or .to_dask_dataframe methods before providing it to '
'HoloViews.'.format(vdim.name, undeclared))
'HoloViews.')
return data, {'kdims': kdims, 'vdims': vdims}, {}


Expand Down
2 changes: 1 addition & 1 deletion holoviews/core/dimension.py
Original file line number Diff line number Diff line change
Expand Up @@ -997,7 +997,7 @@ def get_dimension_index(self, dimension):
dim = dimension_name(dimension)
try:
dimensions = self.kdims+self.vdims
return [i for i, d in enumerate(dimensions) if d == dim][0]
return next(i for i, d in enumerate(dimensions) if d == dim)
except IndexError:
raise Exception(f"Dimension {dim} not found in {self.__class__.__name__}.")

Expand Down
4 changes: 2 additions & 2 deletions holoviews/core/ndmapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,8 +170,8 @@ def _add_item(self, dim_vals, data, sort=True, update=True):

for dim, val in valid_vals:
if dim.values and val is not None and val not in dim.values:
raise KeyError('{} dimension value {} not in'
' specified dimension values.'.format(dim, repr(val)))
raise KeyError(f'{dim} dimension value {val!r} not in'
' specified dimension values.')

# Updates nested data structures rather than simply overriding them.
if (update and (dim_vals in self.data)
Expand Down
2 changes: 1 addition & 1 deletion holoviews/core/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -1292,7 +1292,7 @@ def lookup(cls, backend, obj):
idlist = ",".join([str(el) for el in sorted(ids)])
raise Exception("Object contains elements combined across "
"multiple custom trees (ids %s)" % idlist)
return cls._custom_options[backend][list(ids)[0]]
return cls._custom_options[backend][next(iter(ids))]

@classmethod
def transfer_options(cls, obj, new_obj, backend=None, names=None, level=3):
Expand Down
6 changes: 3 additions & 3 deletions holoviews/core/overlay.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,8 +239,8 @@ def group(self):
values = {el.group for el in elements}
types = {type(el) for el in elements}
if values:
group = list(values)[0]
vtype = list(types)[0].__name__
group = next(iter(values))
vtype = next(iter(types)).__name__
else:
group, vtype = [], ''
if len(values) == 1 and group != vtype:
Expand All @@ -262,7 +262,7 @@ def label(self):
labels = {el.label for el in self
if not el._auxiliary_component}
if len(labels) == 1:
return list(labels)[0]
return next(iter(labels))
else:
return ''

Expand Down
6 changes: 3 additions & 3 deletions holoviews/core/pprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ def info(cls, obj, ansi=False, backend='matplotlib', visualization=True,
plot_class = backend_registry.get(obj if isclass else type(obj), None)
# Special case to handle PlotSelectors
if hasattr(plot_class, 'plot_classes'):
plot_class = list(plot_class.plot_classes.values())[0]
plot_class = next(iter(plot_class.plot_classes.values()))


if visualization is False or plot_class is None:
Expand Down Expand Up @@ -189,13 +189,13 @@ def target_info(cls, obj, ansi=False):

element_info = None
if len(element_set) == 1:
element_info = f'Element: {list(element_set)[0]}'
element_info = f'Element: {next(iter(element_set))}'
elif len(element_set) > 1:
element_info = 'Elements:\n %s' % '\n '.join(sorted(element_set))

container_info = None
if len(container_set) == 1:
container_info = f'Container: {list(container_set)[0]}'
container_info = f'Container: {next(iter(container_set))}'
elif len(container_set) > 1:
container_info = 'Containers:\n %s' % '\n '.join(sorted(container_set))
heading = cls.heading('Target Specifications', ansi=ansi, char="-")
Expand Down
2 changes: 1 addition & 1 deletion holoviews/core/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -2024,7 +2024,7 @@ def bound_range(vals, density, time_unit='us'):
full_precision_density = compute_density(low, high, len(vals)-1)
with np.errstate(over='ignore'):
density = round(full_precision_density, sys.float_info.dig)
if density == 0 or density == np.inf:
if density in (0, np.inf):
density = full_precision_density
if density == 0:
raise ValueError('Could not determine Image density, ensure it has a non-zero range.')
Expand Down
2 changes: 1 addition & 1 deletion holoviews/element/chart.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from ..core import util
from ..core import Dimension, Dataset, Element2D, NdOverlay, Overlay
from ..core.dimension import process_dimensions
from .geom import Rectangles, Points, VectorField # noqa: backward compatible import
from .geom import Rectangles, Points, VectorField # noqa: F401 backward compatible import
from .selection import Selection1DExpr


Expand Down
2 changes: 1 addition & 1 deletion holoviews/element/raster.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ def sample(self, samples=[], bounds=None, **sample_values):
params['kdims'] = self.kdims
return Table(table_data, **params)
else:
dimension, sample_coord = list(sample_values.items())[0]
dimension, sample_coord = next(iter(sample_values.items()))
if isinstance(sample_coord, slice):
raise ValueError(
'Raster sampling requires coordinates not slices,'
Expand Down
8 changes: 4 additions & 4 deletions holoviews/operation/datashader.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,8 @@ def _get_aggregator(cls, element, agg, add_field=True):
if isinstance(agg, str):
if agg not in cls._agg_methods:
agg_methods = sorted(cls._agg_methods)
raise ValueError("Aggregation method '{!r}' is not known; "
"aggregator must be one of: {!r}".format(agg, agg_methods))
raise ValueError(f"Aggregation method '{agg!r}' is not known; "
f"aggregator must be one of: {agg_methods!r}")
if agg == 'count_cat':
agg = cls._agg_methods[agg]('__temp__')
else:
Expand Down Expand Up @@ -968,10 +968,10 @@ def _precompute(self, element, agg):
else:
p, n = 'vertices', 'simplexes'
self.param.warning(
"TriMesh {} were provided as dask DataFrame but {} "
f"TriMesh {p} were provided as dask DataFrame but {n} "
"were not. Datashader will not use dask to parallelize "
"rasterization unless both are provided as dask "
"DataFrames.".format(p, n))
"DataFrames.")
simplices = element.dframe(simplex_dims)
verts = element.nodes.dframe(vert_dims)
for c, dtype in zip(simplices.columns[:3], simplices.dtypes):
Expand Down
2 changes: 1 addition & 1 deletion holoviews/operation/element.py
Original file line number Diff line number Diff line change
Expand Up @@ -711,7 +711,7 @@ def _process(self, element, key=None):
if self.p.dimension:
selected_dim = self.p.dimension
else:
selected_dim = [d.name for d in element.vdims + element.kdims][0]
selected_dim = next(d.name for d in element.vdims + element.kdims)
dim = element.get_dimension(selected_dim)

if hasattr(element, 'interface'):
Expand Down
2 changes: 1 addition & 1 deletion holoviews/plotting/bokeh/callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -1023,7 +1023,7 @@ def _update_cds_vdims(self, data):
if dim in data:
continue
values = element.dimension_values(d)
if len(values) != len(list(data.values())[0]):
if len(values) != len(next(iter(data.values()))):
values = np.concatenate([values, [stream.empty_value]])
data[dim] = values

Expand Down
4 changes: 2 additions & 2 deletions holoviews/plotting/bokeh/chart.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def get_batched_data(self, element, ranges):
continue

# Apply static styles
nvals = len(list(eldata.values())[0])
nvals = len(next(iter(eldata.values())))
sdata, smapping = expand_batched_style(style, self._batched_style_opts,
elmapping, nvals)
if 'angle' in sdata and '__angle' not in data and 'marker' in data:
Expand Down Expand Up @@ -864,7 +864,7 @@ def _add_color_data(self, ds, ranges, style, cdim, data, mapping, factors, color
for k, cd in cdata.items():
if isinstance(cmapper, CategoricalColorMapper) and cd.dtype.kind in 'uif':
cd = categorize_array(cd, cdim)
if k not in data or len(data[k]) != [len(data[key]) for key in data if key != k][0]:
if k not in data or len(data[k]) != next(len(data[key]) for key in data if key != k):
data[k].append(cd)
else:
data[k][-1] = cd
Expand Down
12 changes: 6 additions & 6 deletions holoviews/plotting/bokeh/element.py
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ def _get_hover_data(self, data, element, dimensions=None):
for k, v in self.overlay_dims.items():
dim = util.dimension_sanitizer(k.name)
if dim not in data:
data[dim] = [v for _ in range(len(list(data.values())[0]))]
data[dim] = [v] * len(next(iter(data.values())))

def _shared_axis_range(self, plots, specs, range_type, axis_type, pos):
"""
Expand Down Expand Up @@ -1400,15 +1400,15 @@ def _apply_transforms(self, element, data, ranges, style, group=None):
elif isinstance(element, Graph) and v in element.nodes:
v = dim(element.nodes.get_dimension(v))
elif any(d==v for d in self.overlay_dims):
v = dim([d for d in self.overlay_dims if d==v][0])
v = dim(next(d for d in self.overlay_dims if d==v))

if (not isinstance(v, dim) or (group is not None and not k.startswith(group))):
continue
elif (not v.applies(element) and v.dimension not in self.overlay_dims):
new_style.pop(k)
self.param.warning(
'Specified {} dim transform {!r} could not be applied, '
'as not all dimensions could be resolved.'.format(k, v))
f'Specified {k} dim transform {v!r} could not be applied, '
'as not all dimensions could be resolved.')
continue

if v.dimension in self.overlay_dims:
Expand All @@ -1433,7 +1433,7 @@ def _apply_transforms(self, element, data, ranges, style, group=None):
'to overlay your data along the dimension.'.format(
style=k, dim=v.dimension, element=element,
backend=self.renderer.backend))
elif data and len(val) != len(list(data.values())[0]):
elif data and len(val) != len(next(iter(data.values()))):
if isinstance(element, VectorField):
val = np.tile(val, 3)
elif isinstance(element, Path) and not isinstance(element, Contours):
Expand Down Expand Up @@ -1638,7 +1638,7 @@ def _update_glyph(self, renderer, properties, mapping, glyph, source, data):
prop = 'value' if 'label' in lp else 'field'
label = {prop: legend}
elif isinstance(item.label, dict):
label = {list(item.label)[0]: legend}
label = {next(iter(item.label)): legend}
else:
label = {'value': legend}
item.label = label
Expand Down
6 changes: 3 additions & 3 deletions holoviews/plotting/bokeh/path.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def _get_hover_data(self, data, element):
for k, v in self.overlay_dims.items():
dim = util.dimension_sanitizer(k.name)
if dim not in data:
data[dim] = [v for _ in range(len(list(data.values())[0]))]
data[dim] = [v] * len(next(iter(data.values())))


def get_data(self, element, ranges, style):
Expand Down Expand Up @@ -159,7 +159,7 @@ def get_batched_data(self, element, ranges=None):
continue

# Apply static styles
nvals = len(list(eldata.values())[0])
nvals = len(next(iter(eldata.values())))
sdata, smapping = expand_batched_style(style, self._batched_style_opts,
elmapping, nvals)
elmapping.update({k: v for k, v in smapping.items() if k not in elmapping})
Expand Down Expand Up @@ -219,7 +219,7 @@ def _get_hover_data(self, data, element):
for k, v in self.overlay_dims.items():
dim = util.dimension_sanitizer(k.name)
if dim not in data:
data[dim] = [v for _ in range(len(list(data.values())[0]))]
data[dim] = [v] * len(next(iter(data.values())))

def get_data(self, element, ranges, style):
if self._has_holes is None:
Expand Down
10 changes: 4 additions & 6 deletions holoviews/plotting/mpl/chart.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,11 +335,9 @@ def initialize_plot(self, ranges=None):
if 'vmin' in style:
raise ValueError('Mapping a continuous dimension to a '
'color on a HistogramPlot is not '
'supported by the {backend} backend. '
f'supported by the {self.renderer.backend} backend. '
'To map a dimension to a color supply '
'an explicit list of rgba colors.'.format(
backend=self.renderer.backend
)
'an explicit list of rgba colors.'
)

# Plot bars and make any adjustments
Expand Down Expand Up @@ -631,8 +629,8 @@ def _compute_styles(self, element, ranges, style):
if sizes is None:
eltype = type(element).__name__
self.param.warning(
'{} dimension is not numeric, cannot use to '
'scale {} size.'.format(sdim.pprint_label, eltype))
f'{sdim.pprint_label} dimension is not numeric, cannot use to '
f'scale {eltype} size.')
else:
style['s'] = sizes
style['edgecolors'] = style.pop('edgecolors', 'none')
Expand Down
Loading