Skip to content

Commit

Permalink
refactor: Ruff 0.8.0 (#6459)
Browse files Browse the repository at this point in the history
  • Loading branch information
hoxbro authored Dec 2, 2024
1 parent 877ec01 commit 0305b47
Show file tree
Hide file tree
Showing 42 changed files with 80 additions and 94 deletions.
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ repos:
- id: check-json
- id: detect-private-key
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.7.1
rev: v0.8.1
hooks:
- id: ruff
files: holoviews/|scripts/
Expand All @@ -43,7 +43,7 @@ repos:
hooks:
- id: shellcheck
- repo: https://github.com/hoxbro/prettier-pre-commit
rev: v3.3.3
rev: v3.4.1
hooks:
- id: prettier
exclude: conda.recipe/meta.yaml
Expand Down
2 changes: 1 addition & 1 deletion holoviews/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ def __getattr__(name):
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")

__all__ = [k for k in locals() if not k.startswith('_')]
__all__ += ['annotate', '__version__']
__all__ += ['__version__', 'annotate']

def __dir__():
return __all__
Expand Down
2 changes: 1 addition & 1 deletion holoviews/core/boundingregion.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ class AARectangle:
Usage: aar = AARectangle( (x1,y1),(x2,y2), ... , (xN,yN) )
"""
__slots__ = ['_left', '_bottom', '_right', '_top']
__slots__ = ['_bottom', '_left', '_right', '_top']


def __init__(self, *points):
Expand Down
2 changes: 1 addition & 1 deletion holoviews/core/data/dictionary.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def validate(cls, dataset, vdims=True):
lengths = [(dim, 1 if isscalar(dataset.data[dim]) else len(dataset.data[dim]))
for dim in dimensions]
if len({l for d, l in lengths if l > 1}) > 1:
lengths = ', '.join(['%s: %d' % l for l in sorted(lengths)])
lengths = ', '.join(['{}: {}'.format(*l) for l in sorted(lengths)])
raise DataError('Length of columns must be equal or scalar, '
f'columns have lengths: {lengths}', cls)

Expand Down
6 changes: 3 additions & 3 deletions holoviews/core/data/grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,10 +126,10 @@ def init(cls, eltype, data, kdims, vdims):
# If empty or an irregular mesh
pass
elif len(shape) != len(expected):
raise error('The shape of the %s value array does not '
raise error(f'The shape of the {vdim} value array does not '
'match the expected dimensionality indicated '
'by the key dimensions. Expected %d-D array, '
'found %d-D array.' % (vdim, len(expected), len(shape)))
f'by the key dimensions. Expected {len(expected)}-D array, '
f'found {len(shape)}-D array.')
elif any((e not in (s, s + 1)) for s, e in zip(shape, valid_shape)):
raise error(f'Key dimension values and value array {vdim} '
f'shapes do not match. Expected shape {valid_shape}, '
Expand Down
5 changes: 2 additions & 3 deletions holoviews/core/data/pandas.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,8 @@ def init(cls, eltype, data, kdims, vdims):
if any(d.ndim > 1 for d in data):
raise ValueError('PandasInterface cannot interpret multi-dimensional arrays.')
elif len(data) < min_dims:
raise DataError('Data contains fewer columns than the %s element expects. Expected '
'at least %d columns but found only %d columns.' %
(eltype.__name__, min_dims, len(data)))
raise DataError(f'Data contains fewer columns than the {eltype.__name__} element expects. Expected '
f'at least {min_dims} columns but found only {len(data)} columns.')
elif not cls.expanded(data):
raise ValueError('PandasInterface expects data to be of uniform shape.')
data = pd.DataFrame(dict(zip(columns, data)), columns=columns)
Expand Down
7 changes: 3 additions & 4 deletions holoviews/core/data/spatialpandas.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,10 @@ def validate(cls, dataset, vdims=True):
dim_types = 'key' if vdims else 'all'
geom_dims = cls.geom_dims(dataset)
if len(geom_dims) != 2:
raise DataError('Expected %s instance to declare two key '
raise DataError(f'Expected {type(dataset).__name__} instance to declare two key '
'dimensions corresponding to the geometry '
'coordinates but %d dimensions were found '
'which did not refer to any columns.'
% (type(dataset).__name__, len(geom_dims)), cls)
f'coordinates but {len(geom_dims)} dimensions were found '
'which did not refer to any columns.', cls)
not_found = [d.name for d in dataset.dimensions(dim_types)
if d not in geom_dims and d.name not in dataset.data]
if not_found:
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 @@ -180,7 +180,7 @@ def retrieve_unit_and_label(dim):
data = {d: np.asarray(values) if d in kdims else values
for d, values in data.items()}
coord_dims = [data[kd.name].ndim for kd in kdims]
dims = tuple('dim_%d' % i for i in range(max(coord_dims)))[::-1]
dims = tuple(f'dim_{i}' for i in range(max(coord_dims)))[::-1]
coords = {}
for kd in kdims:
coord_vals = data[kd.name]
Expand Down
2 changes: 1 addition & 1 deletion holoviews/core/dimension.py
Original file line number Diff line number Diff line change
Expand Up @@ -700,7 +700,7 @@ def __getstate__(self):
obj_dict = self.__dict__.copy()
try:
if Store.save_option_state and (obj_dict.get('_id', None) is not None):
custom_key = '_custom_option_%d' % obj_dict['_id']
custom_key = '_custom_option_{}'.format(obj_dict['_id'])
if custom_key not in obj_dict:
obj_dict[custom_key] = {backend:s[obj_dict['_id']]
for backend,s in Store._custom_options.items()
Expand Down
4 changes: 2 additions & 2 deletions holoviews/core/element.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,9 +277,9 @@ def pprint_cell(self, row, col):
"""
ndims = self.ndims
if col >= self.cols:
raise Exception("Maximum column index is %d" % self.cols-1)
raise Exception(f"Maximum column index is {self.cols-1}")
elif row >= self.rows:
raise Exception("Maximum row index is %d" % self.rows-1)
raise Exception(f"Maximum row index is {self.cols-1}")
elif row == 0:
if col >= ndims:
if self.vdims:
Expand Down
12 changes: 5 additions & 7 deletions holoviews/core/ndmapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,10 +147,9 @@ def _item_check(self, dim_vals, data):
raise TypeError(f'{slf} does not accept {data} type, data elements have '
f'to be a {data_type}.')
elif not len(dim_vals) == self.ndims:
raise KeyError('The data contains keys of length %d, but the kdims '
'only declare %d dimensions. Ensure that the number '
'of kdims match the length of the keys in your data.'
% (len(dim_vals), self.ndims))
raise KeyError(f'The data contains keys of length {len(dim_vals)}, but the kdims '
f'only declare {self.ndims} dimensions. Ensure that the number '
'of kdims match the length of the keys in your data.')


def _add_item(self, dim_vals, data, sort=True, update=True):
Expand Down Expand Up @@ -475,8 +474,7 @@ def info(self):
"""
if (len(self.values()) > 0):
info_str = self.__class__.__name__ +\
" containing %d items of type %s\n" % (len(self.keys()),
type(self.values()[0]).__name__)
f" containing {len(self.keys())} items of type {type(self.values()[0]).__name__}\n"
else:
info_str = self.__class__.__name__ + " containing no items\n"
info_str += ('-' * (len(info_str)-1)) + "\n\n"
Expand Down Expand Up @@ -920,7 +918,7 @@ def dframe(self, dimensions=None, multi_index=False):
for dim, val in key_dims:
dimn = 1
while dim in df:
dim = dim+'_%d' % dimn
dim = dim+f'_{dimn}'
if dim in df:
dimn += 1
df.insert(0, dim, val)
Expand Down
11 changes: 5 additions & 6 deletions holoviews/core/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -1522,9 +1522,8 @@ def propagate(o):

# Clean up the custom tree if it was not applied
if new_id not in Store.custom_options(backend=backend):
raise AssertionError("New option id %d does not match any "
"option trees in Store.custom_options."
% new_id)
raise AssertionError(f"New option id {new_id} does not match any "
"option trees in Store.custom_options.")
return applied

@classmethod
Expand Down Expand Up @@ -1722,11 +1721,11 @@ def merge_options(cls, groups, options=None,**kwargs):
additions.update({k:kws})
if spec_key not in options:
options[spec_key] = {}
for key in additions:
for key, value in additions.items():
if key in options[spec_key]:
options[spec_key][key].update(additions[key])
options[spec_key][key].update(value)
else:
options[spec_key][key] = additions[key]
options[spec_key][key] = value
return options


Expand Down
2 changes: 1 addition & 1 deletion holoviews/core/pprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -412,4 +412,4 @@ def ndmapping_info(cls_or_slf, node, siblings, level, value_dims):
return level, lines


__all__ = ['PrettyPrinter', 'InfoPrinter']
__all__ = ['InfoPrinter', 'PrettyPrinter']
3 changes: 1 addition & 2 deletions holoviews/core/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -1976,8 +1976,7 @@ def cross_index(values, index):
lengths = [len(v) for v in values]
length = np.prod(lengths)
if index >= length:
raise IndexError('Index %d out of bounds for cross-product of size %d'
% (index, length))
raise IndexError(f'Index {index} out of bounds for cross-product of size {lengths}')
indexes = []
for i in range(1, len(values))[::-1]:
p = np.prod(lengths[-i:])
Expand Down
3 changes: 1 addition & 2 deletions holoviews/element/comparison.py
Original file line number Diff line number Diff line change
Expand Up @@ -532,8 +532,7 @@ def compare_dataset(cls, el1, el2, msg='Dataset'):
el2.dimension_values(d, flat=tabular))
for d in el1.vdims]
if el1.shape[0] != el2.shape[0]:
raise AssertionError("%s not of matching length, %d vs. %d."
% (msg, el1.shape[0], el2.shape[0]))
raise AssertionError(f"{msg} not of matching length, {el1.shape[0]} vs. {el2.shape[0]}.")
for dim, d1, d2 in dimension_data:
with contextlib.suppress(Exception):
np.testing.assert_equal(d1, d2)
Expand Down
4 changes: 2 additions & 2 deletions holoviews/element/graphs.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,8 +223,8 @@ def _validate(self):
mismatch = npaths != nedges
if mismatch:
raise ValueError('Ensure that the number of edges supplied '
'to the Graph (%d) matches the number of '
'edgepaths (%d)' % (nedges, npaths))
f'to the Graph ({nedges}) matches the number of '
f'edgepaths ({npaths})')

def clone(self, data=None, shared_data=True, new_type=None, link=True,
*args, **overrides):
Expand Down
9 changes: 4 additions & 5 deletions holoviews/element/raster.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def __getitem__(self, slices):
if not isinstance(slices, tuple):
slices = (slices, slice(None))
elif len(slices) > (2 + self.depth):
raise KeyError("Can only slice %d dimensions" % 2 + self.depth)
raise KeyError(f"Can only slice {2 + self.depth} dimensions")
elif len(slices) == 3 and slices[-1] not in [self.vdims[0].name, slice(None)]:
raise KeyError(f"{self.vdims[0].name!r} is the only selectable value dimension")

Expand Down Expand Up @@ -268,8 +268,8 @@ def __init__(self, data, kdims=None, vdims=None, bounds=None, extents=None,
if not xdensity: xdensity = 1
if not ydensity: ydensity = 1
elif isinstance(data, np.ndarray) and data.ndim < self._ndim:
raise ValueError('%s type expects %d-D array received %d-D '
'array.' % (type(self).__name__, self._ndim, data.ndim))
raise ValueError(f'{type(self).__name__} type expects {self._ndim}-D array received {data.ndim}-D '
'array.')

if rtol is not None:
params['rtol'] = rtol
Expand Down Expand Up @@ -319,8 +319,7 @@ def __init__(self, data, kdims=None, vdims=None, bounds=None, extents=None,
def _validate(self, data_bounds, supplied_bounds):
if len(self.shape) == 3:
if self.shape[2] != len(self.vdims):
raise ValueError("Input array has shape %r but %d value dimensions defined"
% (self.shape, len(self.vdims)))
raise ValueError(f"Input array has shape {self.shape!r} but {len(self.vdims)} value dimensions defined")

# Ensure coordinates are regularly sampled
clsname = type(self).__name__
Expand Down
2 changes: 1 addition & 1 deletion holoviews/element/tabular.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def pprint_cell(self, row, col):
if col > 2:
raise Exception("Only two columns available in a ItemTable.")
elif row >= self.rows:
raise Exception("Maximum row index is %d" % self.rows-1)
raise Exception(f"Maximum row index is {self.rows-1}")
elif col == 0:
return self.dimensions('value')[row].pprint_label
else:
Expand Down
2 changes: 1 addition & 1 deletion holoviews/ipython/magics.py
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ def elapsed_time():
seconds = time.time() - TimerMagic.start_time
minutes = seconds // 60
hours = minutes // 60
return "Timer elapsed: %02d:%02d:%02d" % (hours, minutes % 60, seconds % 60)
return f"Timer elapsed: {hours:02d}:{minutes % 60:02d}:{seconds % 60:02d}"

@classmethod
def option_completer(cls, k,v):
Expand Down
6 changes: 2 additions & 4 deletions holoviews/ipython/widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,7 @@ def __call__(self, percentage):
elapsed = time.time() - self.start_time
if clear_output:
clear_output()
self.out = '\r' + ('100%% %s %02d:%02d:%02d'
% (self.label.lower(), elapsed//3600,
elapsed//60, elapsed%60))
self.out = f'\r100% {self.label.lower()} {elapsed//3600:02d}:{elapsed//60:02d}:{elapsed%60:02d}'
output = ''.join([pg.out for pg in self.current_progress])
sys.stdout.write(output)
else:
Expand Down Expand Up @@ -109,7 +107,7 @@ def _get_socket(self, min_port=8080, max_port=8100, max_tries=20):
min_port=min_port,
max_port=max_port,
max_tries=max_tries)
self.param.message("Progress broadcast bound to port %d" % port)
self.param.message(f"Progress broadcast bound to port {port}")
return sock
except Exception:
self.param.message("No suitable port found for progress broadcast.")
Expand Down
2 changes: 1 addition & 1 deletion holoviews/plotting/bokeh/annotation.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ def get_data(self, element, ranges, style):
if 'text_baseline' not in style:
style['text_baseline'] = baseline
if 'text_font_size' not in style:
style['text_font_size'] = '%dPt' % element.fontsize
style['text_font_size'] = f"{int(element.fontsize)}Pt"
if 'color' in style:
style['text_color'] = style.pop('color')
style['angle'] = np.deg2rad(style.get('angle', element.rotation))
Expand Down
3 changes: 1 addition & 2 deletions holoviews/plotting/bokeh/element.py
Original file line number Diff line number Diff line change
Expand Up @@ -2848,8 +2848,7 @@ def _get_colormapper(self, eldim, element, ranges, style, factors=None, colors=N
if isinstance(cmap, list) and len(cmap) != ncolors:
raise ValueError('The number of colors in the colormap '
'must match the intervals defined in the '
'color_levels, expected %d colors found %d.'
% (ncolors, len(cmap)))
f'color_levels, expected {ncolors} colors found {len(cmap)}.')
palette = process_cmap(cmap, ncolors, categorical=categorical)
if isinstance(self.color_levels, list):
palette, (low, high) = color_intervals(palette, self.color_levels, clip=(low, high))
Expand Down
2 changes: 1 addition & 1 deletion holoviews/plotting/bokeh/graphs.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ def _get_edge_paths(self, element, ranges):
mapping = {'xs': 'xs', 'ys': 'ys'}
else:
raise ValueError("Edge paths do not match the number of supplied edges."
"Expected %d, found %d paths." % (len(element), len(edges)))
f"Expected {len(element)}, found {len(edges)} paths.")
elif self.directed:
xdim, ydim = element.nodes.kdims[:2]
x_range = ranges[xdim.label]['combined']
Expand Down
4 changes: 2 additions & 2 deletions holoviews/plotting/bokeh/links.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,8 +235,8 @@ def __init__(self, root_model, link, source_plot, target_plot):
tgt_len = [len(v) for v in tgt_cds.data.values()]
if src_len and tgt_len and (src_len[0] != tgt_len[0]):
raise ValueError('DataLink source data length must match target '
'data length, found source length of %d and '
'target length of %d.' % (src_len[0], tgt_len[0]))
f'data length, found source length of {src_len[0]} and '
f'target length of {tgt_len[0]}.')

# Ensure the data sources are compatible (i.e. overlapping columns are equal)
for k, v in tgt_cds.data.items():
Expand Down
3 changes: 1 addition & 2 deletions holoviews/plotting/bokeh/raster.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,7 @@ def _postprocess_hover(self, renderer, source):
return date.toISOString().slice(0, 19).replace('T', ' ')
}
"""
for key in formatters:
formatter = formatters[key]
for key, formatter in formatters.values():
if isinstance(formatter, str) and formatter.lower() == "datetime":
formatters[key] = CustomJSHover(code=datetime_code)

Expand Down
3 changes: 1 addition & 2 deletions holoviews/plotting/mpl/element.py
Original file line number Diff line number Diff line change
Expand Up @@ -997,8 +997,7 @@ def _norm_kwargs(self, element, ranges, opts, vdim, values=None, prefix=''):
if isinstance(cmap, list) and len(cmap) != ncolors:
raise ValueError('The number of colors in the colormap '
'must match the intervals defined in the '
'color_levels, expected %d colors found %d.'
% (ncolors, len(cmap)))
f'color_levels, expected {ncolors} colors found {len(cmap)}.')
try:
el_min, el_max = np.nanmin(values), np.nanmax(values)
except ValueError:
Expand Down
3 changes: 1 addition & 2 deletions holoviews/plotting/plotly/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -817,8 +817,7 @@ def get_colorscale(cmap, levels=None, cmin=None, cmax=None):
if isinstance(cmap, list) and len(cmap) != ncolors:
raise ValueError('The number of colors in the colormap '
'must match the intervals defined in the '
'color_levels, expected %d colors found %d.'
% (ncolors, len(cmap)))
f'color_levels, expected {ncolors} colors found {len(cmap)}.')
try:
palette = process_cmap(cmap, ncolors)
except Exception as e:
Expand Down
2 changes: 1 addition & 1 deletion holoviews/plotting/renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ def html(self, obj, fmt=None, css=None, resources='CDN', **kwargs):
figdata = figdata.encode("utf-8")
elif fmt == 'pdf' and 'height' not in css:
_, h = self.get_size(plot)
css['height'] = '%dpx' % (h*self.dpi*1.15)
css['height'] = f"{int(h*self.dpi*1.15)}px"

if isinstance(css, dict):
css = '; '.join(f"{k}: {v}" for k, v in css.items())
Expand Down
3 changes: 1 addition & 2 deletions holoviews/plotting/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -985,8 +985,7 @@ def color_intervals(colors, levels, clip=None, N=255):
if len(colors) != len(levels)-1:
raise ValueError('The number of colors in the colormap '
'must match the intervals defined in the '
'color_levels, expected %d colors found %d.'
% (N, len(colors)))
f'color_levels, expected {N} colors found {len(colors)}.')
intervals = np.diff(levels)
cmin, cmax = min(levels), max(levels)
interval = cmax-cmin
Expand Down
Loading

0 comments on commit 0305b47

Please sign in to comment.