Skip to content

Commit

Permalink
Update pre-commit (#5747)
Browse files Browse the repository at this point in the history
  • Loading branch information
hoxbro authored Jun 9, 2023
1 parent 5cb5ff7 commit dfb2a96
Show file tree
Hide file tree
Showing 50 changed files with 213 additions and 275 deletions.
6 changes: 3 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ exclude: (\.min\.js$|\.svg$|\.html$)
default_stages: [commit]
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.2.0
rev: v4.4.0
hooks:
- id: check-builtin-literals
- id: check-case-conflict
Expand All @@ -17,13 +17,13 @@ repos:
exclude: \.min\.js$
- id: trailing-whitespace
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.251
rev: v0.0.272
hooks:
- id: ruff
args: [holoviews]
files: holoviews/
- repo: https://github.com/hoxbro/clean_notebook
rev: v0.1.6
rev: v0.1.10
hooks:
- id: clean-notebook
- repo: https://github.com/codespell-project/codespell
Expand Down
1 change: 0 additions & 1 deletion examples/user_guide/Plotting_with_Bokeh.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
Expand Down
24 changes: 11 additions & 13 deletions holoviews/core/data/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,7 @@ def __call__(self, new_type, kdims=None, vdims=None, groupby=None,
min_d, max_d = element_params[dim_type].bounds
if ((min_d is not None and len(dims) < min_d) or
(max_d is not None and len(dims) > max_d)):
raise ValueError("%s %s must be between length %s and %s." %
(type_name, dim_type, min_d, max_d))
raise ValueError(f"{type_name} {dim_type} must be between length {min_d} and {max_d}.")

if groupby is None:
groupby = [d for d in self._element.kdims if d not in kdims+vdims]
Expand All @@ -123,16 +122,15 @@ def __call__(self, new_type, kdims=None, vdims=None, groupby=None,
selected = self._element.reindex(groupby+kdims, vdims)
else:
selected = self._element
elif issubclass(self._element.interface, PandasAPI):
ds_dims = self._element.dimensions()
ds_kdims = [self._element.get_dimension(d) if d in ds_dims else d
for d in groupby+kdims]
ds_vdims = [self._element.get_dimension(d) if d in ds_dims else d
for d in vdims]
selected = self._element.clone(kdims=ds_kdims, vdims=ds_vdims)
else:
if issubclass(self._element.interface, PandasAPI):
ds_dims = self._element.dimensions()
ds_kdims = [self._element.get_dimension(d) if d in ds_dims else d
for d in groupby+kdims]
ds_vdims = [self._element.get_dimension(d) if d in ds_dims else d
for d in vdims]
selected = self._element.clone(kdims=ds_kdims, vdims=ds_vdims)
else:
selected = self._element.reindex(groupby+kdims, vdims)
selected = self._element.reindex(groupby+kdims, vdims)
params = {'kdims': [selected.get_dimension(kd, strict=True) for kd in kdims],
'vdims': [selected.get_dimension(vd, strict=True) for vd in vdims],
'label': selected.label}
Expand Down Expand Up @@ -907,7 +905,7 @@ def aggregate(self, dimensions=None, function=None, spreadfn=None, **kwargs):
if not self:
if spreadfn:
spread_name = spreadfn.__name__
vdims = [d for vd in self.vdims for d in [vd, vd.clone('_'.join([vd.name, spread_name]))]]
vdims = [d for vd in self.vdims for d in [vd, vd.clone(f'{vd.name}_{spread_name}')]]
else:
vdims = self.vdims
if not kdims and len(vdims) == 1:
Expand All @@ -926,7 +924,7 @@ def aggregate(self, dimensions=None, function=None, spreadfn=None, **kwargs):
error = self.clone(error, kdims=kdims, new_type=Dataset)
combined = self.clone(aggregated, kdims=kdims, new_type=Dataset)
for i, d in enumerate(vdims):
dim = d.clone('_'.join([d.name, spread_name]))
dim = d.clone(f'{d.name}_{spread_name}')
dvals = error.dimension_values(d, flat=False)
idx = vdims.index(d)
combined = combined.add_dimension(dim, idx+1, dvals, True)
Expand Down
10 changes: 4 additions & 6 deletions holoviews/core/data/grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,9 +162,8 @@ def concat_dim(cls, datasets, dim, vdims):
shapes = {arr.shape for arr in arrays}
if len(shapes) > 1:
raise DataError('When concatenating gridded data the shape '
'of arrays must match. %s found that arrays '
'along the %s dimension do not match.' %
(cls.__name__, vdim.name))
'of arrays must match. {} found that arrays '
'along the {} dimension do not match.'.format(cls.__name__, vdim.name))
stack = dask_array_module().stack if any(is_dask(arr) for arr in arrays) else np.stack
new_data[vdim.name] = stack(arrays, -1)
return new_data
Expand Down Expand Up @@ -558,9 +557,8 @@ 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. %s value along %s dimension."
"must be a slice or 2D boolean mask."
% (ind, dim))
"sampled data. {} value along {} dimension."
"must be a slice or 2D boolean mask.".format(ind, dim))
mask = mask.max(axis=i)
elif dataset._binned:
edges = cls.coords(dataset, dim, False, edges=True)
Expand Down
7 changes: 3 additions & 4 deletions holoviews/core/data/ibis.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,11 +219,10 @@ def _index_ibis_table(cls, data):

if ibis4():
return data.mutate(hv_row_id__=ibis.row_number())
elif cls.is_rowid_zero_indexed(data):
return data.mutate(hv_row_id__=data.rowid())
else:
if cls.is_rowid_zero_indexed(data):
return data.mutate(hv_row_id__=data.rowid())
else:
return data.mutate(hv_row_id__=data.rowid() - 1)
return data.mutate(hv_row_id__=data.rowid() - 1)

@classmethod
def iloc(cls, dataset, index):
Expand Down
4 changes: 2 additions & 2 deletions holoviews/core/data/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class DataError(ValueError):

def __init__(self, msg, interface=None):
if interface is not None:
msg = '\n\n'.join([msg, interface.error()])
msg = f"{msg}\n\n{interface.error()}"
super().__init__(msg)


Expand Down Expand Up @@ -263,7 +263,7 @@ def initialize(cls, eltype, data, kdims, vdims, datatype=None):
if priority_errors:
intfc, e, _ = priority_errors[0]
priority_error = f"{intfc.__name__} raised following error:\n\n {e}"
error = ' '.join([error, priority_error])
error = f"{error} {priority_error}"
raise DataError(error, intfc).with_traceback(sys.exc_info()[2])
raise DataError(error)

Expand Down
2 changes: 1 addition & 1 deletion holoviews/core/data/xarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ def validate(cls, dataset, vdims=True):
nonmatching = [f'{kd}: {dims}' for kd, dims in irregular[1:]
if set(dims) != set(irregular[0][1])]
if nonmatching:
nonmatching = ['%s: %s' % irregular[0]] + nonmatching
nonmatching = ['{}: {}'.format(*irregular[0])] + nonmatching
raise DataError("The dimensions of coordinate arrays "
"on irregular data must match. The "
"following kdims were found to have "
Expand Down
5 changes: 2 additions & 3 deletions holoviews/core/decollate.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,9 @@ def to_expr_extract_streams(
expand_kwargs = False
if "kwargs" in hvobj.callback.operation_kwargs:
kwargs.append(hvobj.callback.operation_kwargs["kwargs"])
else:
elif hvobj.callback.operation_kwargs:
# Preserve custom operation kwargs
if hvobj.callback.operation_kwargs:
kwargs.append(hvobj.callback.operation_kwargs)
kwargs.append(hvobj.callback.operation_kwargs)
else:
fn = hvobj.callback.callable
args.extend(kdim_args)
Expand Down
13 changes: 5 additions & 8 deletions holoviews/core/dimension.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,13 +288,11 @@ def __init__(self, spec, **params):
super().__init__(**all_params)
if self.default is not None:
if self.values and self.default not in values:
raise ValueError('%r default %s not found in declared values: %s' %
(self, self.default, self.values))
raise ValueError(f'{self!r} default {self.default} not found in declared values: {self.values}')
elif (self.range != (None, None) and
((self.range[0] is not None and self.default < self.range[0]) or
(self.range[0] is not None and self.default > self.range[1]))):
raise ValueError('%r default %s not in declared range: %s' %
(self, self.default, self.range))
raise ValueError(f'{self!r} default {self.default} not in declared range: {self.range}')

@property
def spec(self):
Expand Down Expand Up @@ -379,15 +377,15 @@ def pprint_label(self):
def pprint(self):
changed = self.param.values(onlychanged=True)
if len({changed.get(k, k) for k in ['name','label']}) == 1:
return f'Dimension({repr(self.name)})'
return f'Dimension({self.name!r})'

params = self.param.objects('existing')
ordering = sorted(
sorted(changed.keys()), key=lambda k: (
-float('inf') if params[k].precedence is None
else params[k].precedence))
kws = ", ".join(f'{k}={changed[k]!r}' for k in ordering if k != 'name')
return f'Dimension({repr(self.name)}, {kws})'
return f'Dimension({self.name!r}, {kws})'


def pprint_value(self, value, print_unit=False):
Expand Down Expand Up @@ -1157,8 +1155,7 @@ def dimension_values(self, dimension, expanded=True, flat=True):
if val:
return np.array([val])
else:
raise Exception("Dimension %s not found in %s." %
(dimension, self.__class__.__name__))
raise Exception(f"Dimension {dimension} not found in {self.__class__.__name__}.")


def range(self, dimension, data_range=True, dimension_range=True):
Expand Down
2 changes: 1 addition & 1 deletion holoviews/core/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -862,7 +862,7 @@ def contents(self, maxlen=70):

def listing(self):
"Return a list of filename entries currently in the archive"
return ['.'.join([f,ext]) if ext else f for (f,ext) in self._files.keys()]
return [f'{f}.{ext}' if ext else f for (f,ext) in self._files.keys()]

def clear(self):
"Clears the file archive"
Expand Down
19 changes: 8 additions & 11 deletions holoviews/core/ndmapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,10 +342,9 @@ def add_dimension(self, dimension, dim_pos, dim_val, vdim=False, **kwargs):

if isinstance(dim_val, str) or not hasattr(dim_val, '__iter__'):
dim_val = cycle([dim_val])
else:
if not len(dim_val) == len(self):
raise ValueError("Added dimension values must be same length"
"as existing keys.")
elif not len(dim_val) == len(self):
raise ValueError("Added dimension values must be same length"
"as existing keys.")

items = OrderedDict()
for dval, (key, val) in zip(dim_val, self.data.items()):
Expand Down Expand Up @@ -942,12 +941,11 @@ def label(self):
"Label inherited from items"
if self._label:
return self._label
elif len(self):
label = get_ndmapping_label(self, 'label')
return '' if label is None else label
else:
if len(self):
label = get_ndmapping_label(self, 'label')
return '' if label is None else label
else:
return ''
return ''


@label.setter
Expand All @@ -974,8 +972,7 @@ def _item_check(self, dim_vals, data):
if not self._check_items:
return
elif self.type is not None and (type(data) != self.type):
raise AssertionError("%s must only contain one type of object, not both %s and %s." %
(self.__class__.__name__, type(data).__name__, self.type.__name__))
raise AssertionError(f"{self.__class__.__name__} must only contain one type of object, not both {type(data).__name__} and {self.type.__name__}.")
super()._item_check(dim_vals, data)


Expand Down
6 changes: 2 additions & 4 deletions holoviews/core/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -471,15 +471,13 @@ def __init__(self, key=None, allowed_keywords=[], merge_keywords=True,
raise OptionError(kwarg, allowed_keywords)

if key and key[0].islower() and key not in self._option_groups:
raise Exception('Key %s does not start with a capitalized element class name and is not a group in %s'
% (repr(key), ', '.join(repr(el) for el in self._option_groups)))
raise Exception('Key {} does not start with a capitalized element class name and is not a group in {}'.format(repr(key), ', '.join(repr(el) for el in self._option_groups)))

for invalid_kw in invalid_kws:
error = OptionError(invalid_kw, allowed_keywords, group_name=key)
StoreOptions.record_skipped_option(error)
if invalid_kws and self.warn_on_skip:
self.param.warning("Invalid options %s, valid options are: %s"
% (repr(invalid_kws), str(allowed_keywords)))
self.param.warning(f"Invalid options {invalid_kws!r}, valid options are: {allowed_keywords!s}")

self.kwargs = OrderedDict([(k,kwargs[k]) for k in sorted(kwargs.keys()) if k not in invalid_kws])
self._options = []
Expand Down
11 changes: 5 additions & 6 deletions holoviews/core/overlay.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,11 @@ def dynamic_mul(*args, **kwargs):
if isinstance(self, Overlay):
if not isinstance(other, ViewableElement):
return NotImplemented
else:
if isinstance(other, UniformNdMapping) and not isinstance(other, CompositeOverlay):
items = [(k, self * v) for (k, v) in other.items()]
return other.clone(items)
elif isinstance(other, (AdjointLayout, ViewableTree)) and not isinstance(other, Overlay):
return NotImplemented
elif isinstance(other, UniformNdMapping) and not isinstance(other, CompositeOverlay):
items = [(k, self * v) for (k, v) in other.items()]
return other.clone(items)
elif isinstance(other, (AdjointLayout, ViewableTree)) and not isinstance(other, Overlay):
return NotImplemented

try:
return Overlay([self, other])
Expand Down
8 changes: 3 additions & 5 deletions holoviews/core/pprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,7 @@ def info(cls, obj, ansi=False, backend='matplotlib', visualization=True,
if pattern is not None:
obj = ParamFilter(obj, ParamFilter.regexp_filter(pattern))
if len(list(obj.param)) <= 1:
return ('No %r parameters found matching specified pattern %r'
% (name, pattern))
return (f'No {name!r} parameters found matching specified pattern {pattern!r}')
info = param.ipython.ParamPager()(obj)
if ansi is False:
info = ansi_escape.sub('', info)
Expand Down Expand Up @@ -210,7 +209,7 @@ def target_info(cls, obj, ansi=False):
target_footer = ("\nTo see the options info for one of these target specifications,"
"\nwhich are of the form {type}[.{group}[.{label}]], do holoviews.help({type}).")

return '\n'.join([heading, target_header, target_info, target_footer])
return f'{heading}\n{target_header}\n{target_info}\n{target_footer}'


@classmethod
Expand Down Expand Up @@ -247,8 +246,7 @@ def options_info(cls, plot_class, ansi=False, pattern=None):
lines += ["The plot options are the parameters of the plotting class:\n",
param_info]
elif pattern is not None:
lines+= ['No %r parameters found matching specified pattern %r.'
% (plot_class.__name__, pattern)]
lines+= [f'No {plot_class.__name__!r} parameters found matching specified pattern {pattern!r}.']
else:
lines+= [f'No {plot_class.__name__!r} parameters found.']

Expand Down
7 changes: 3 additions & 4 deletions holoviews/core/spaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,11 +419,10 @@ def hist(self, dimension=None, num_bins=20, bin_range=None,
if issubclass(self.type, (NdOverlay, Overlay)):
layout.main_layer = kwargs['index']
return layout
elif len(histmaps) > 1:
return Layout(histmaps)
else:
if len(histmaps) > 1:
return Layout(histmaps)
else:
return histmaps[0]
return histmaps[0]


class Callable(param.Parameterized):
Expand Down
3 changes: 1 addition & 2 deletions holoviews/core/tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,8 +270,7 @@ def __getattr__(self, identifier):
self.__dict__[sanitized] = child_tree
return child_tree
else:
raise AttributeError('%r object has no attribute %s.' %
(type(self).__name__, identifier))
raise AttributeError(f'{type(self).__name__!r} object has no attribute {identifier}.')


def __iter__(self):
Expand Down
5 changes: 2 additions & 3 deletions holoviews/core/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -1722,9 +1722,8 @@ def stream_parameters(streams, no_duplicates=True, exclude=['name', '_memoize_ke
clashes = sorted(clashes)
if clashes:
clashing = ', '.join([repr(c) for c in clash_streams[:-1]])
raise Exception('The supplied stream objects %s and %s '
'clash on the following parameters: %r'
% (clashing, clash_streams[-1], clashes))
raise Exception('The supplied stream objects {} and {} '
'clash on the following parameters: {!r}'.format(clashing, clash_streams[-1], clashes))
return [name for group in param_groups.values() for name in group
if name not in exclude]

Expand Down
Loading

0 comments on commit dfb2a96

Please sign in to comment.