From 9e9da08327f6294c7012ad70547be5e28f0e23b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20H=C3=B8xbro=20Hansen?= Date: Thu, 21 Sep 2023 09:47:17 +0200 Subject: [PATCH] Update lint (#29) --- .pre-commit-config.yaml | 4 +- holonote/annotate/annotator.py | 98 +++++++++++----------- holonote/annotate/connector.py | 7 +- holonote/annotate/table.py | 54 +++++++----- holonote/app/panel.py | 11 ++- holonote/tests/conftest.py | 9 +- holonote/tests/test_annotators_advanced.py | 4 +- holonote/tests/test_annotators_basic.py | 36 ++++---- pyproject.toml | 6 +- 9 files changed, 124 insertions(+), 105 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a18cf58..9a9b9b5 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -16,13 +16,13 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.0.285 + rev: v0.0.290 hooks: - id: ruff args: [holonote] files: holonote/ - repo: https://github.com/hoxbro/clean_notebook - rev: v0.1.10 + rev: v0.1.11 hooks: - id: clean-notebook - repo: https://github.com/codespell-project/codespell diff --git a/holonote/annotate/annotator.py b/holonote/annotate/annotator.py index 43be723..0f2bf37 100644 --- a/holonote/annotate/annotator.py +++ b/holonote/annotate/annotator.py @@ -22,11 +22,11 @@ class Indicator: displayed (vectorized) HoloViews object. """ - range_style = dict(color='red', alpha=0.4, apply_ranges=False) + range_style = {'color': 'red', 'alpha': 0.4, 'apply_ranges': False} point_style = {} indicator_highlight = {'alpha':(0.7,0.2)} - edit_range_style = dict(alpha=0.4, line_alpha=1, line_width=1, line_color='black') + edit_range_style = {'alpha': 0.4, 'line_alpha': 1, 'line_width': 1, 'line_color': 'black'} edit_point_style = {} @classmethod @@ -66,7 +66,8 @@ def ranges_1d(cls, region_df, field_df, invert_axes=False, extra_params=None): NOTE: Should use VSpans once available! """ if extra_params is None: - raise Exception('Extra parameters required until vectorized HSpans/VSpans supported') + msg = 'Extra parameters required until vectorized HSpans/VSpans supported' + raise Exception(msg) return cls._range_indicators(region_df, field_df, "1d", invert_axes, extra_params) @classmethod @@ -160,9 +161,11 @@ def normalize_spec(self, input_spec: dict[str, Any]) -> SpecDict: v = {"type": v, "region": "range"} if v["region"] not in ["range", "point", "geometry"]: - raise ValueError("Region type must be range, point, or geometry.") + msg = 'Region type must be range, point, or geometry.' + raise ValueError(msg) if v["region"] == "geometry" and not isinstance(k, tuple): - raise ValueError("Geometry region dimension must be a tuple.") + msg = 'Geometry region dimension must be a tuple.' + raise ValueError(msg) new_spec[k] = v return new_spec @@ -230,7 +233,8 @@ def _set_regions(self, **items): # TODO: Validate values based on spec for dim, values in items.items(): if dim not in self.spec: - raise ValueError(f"Dimension {dim} not in spec") + msg = f'Dimension {dim} not in spec' + raise ValueError(msg) self._region[dim] = values def clear_regions(self): @@ -240,32 +244,29 @@ def clear_regions(self): def set_range(self, startx, endx, starty=None, endy=None): print("set_range is legacy use set_regions instead") if None in [starty, endy] and ([starty, endy] != [None, None]): - raise ValueError('Both starty and endy need to be non-None') + msg = 'Both starty and endy need to be non-None' + raise ValueError(msg) value = (startx, endx) if starty is None else (startx, endx, starty, endy) kdims = list(self.spec) if len(value) == 2: if len(kdims) != 1: - raise ValueError('Only one key dimension is allowed in spec.') + msg = 'Only one key dimension is allowed in spec.' + raise ValueError(msg) if (r := self.spec[kdims[0]]['region']) != 'range': - raise ValueError( - "Only 'range' region allowed for 'set_range', " - f"{kdims[0]!r} is {r!r}." - ) + msg = f"Only 'range' region allowed for 'set_range', {kdims[0]!r} is {r!r}." + raise ValueError(msg) regions = {kdims[0]: value} elif len(value) == 4: if len(kdims) != 2: - raise ValueError('Only two key dimensions is allowed in spec.') + msg = 'Only two key dimensions is allowed in spec.' + raise ValueError(msg) if (r := self.spec[kdims[0]]['region']) != 'range': - raise ValueError( - "Only 'range' region allowed for 'set_range', " - f"{kdims[0]!r} is {r!r}." - ) + msg = f"Only 'range' region allowed for 'set_range', {kdims[0]!r} is {r!r}." + raise ValueError(msg) if (r := self.spec[kdims[1]]['region']) != 'range': - raise ValueError( - "Only 'range' region allowed for 'set_range', " - f"{kdims[1]!r} is {r!r}." - ) + msg = f"Only 'range' region allowed for 'set_range', {kdims[1]!r} is {r!r}." + raise ValueError(msg) regions = {kdims[0]: (value[0], value[1]), kdims[1]: (value[2], value[3])} self.set_regions(**regions) @@ -276,26 +277,22 @@ def set_point(self, posx, posy=None): kdims = list(self.spec) if posy is None: if len(kdims) != 1: - raise ValueError('Only one key dimension is allowed in spec.') + msg = 'Only one key dimension is allowed in spec.' + raise ValueError(msg) if (r := self.spec[kdims[0]]['region']) != 'point': - raise ValueError( - "Only 'point' region allowed for 'set_point', " - f"{kdims[0]!r} is {r!r}." - ) + msg = f"Only 'point' region allowed for 'set_point', {kdims[0]!r} is {r!r}." + raise ValueError(msg) regions = {kdims[0]: posx} else: if len(kdims) != 2: - raise ValueError('Only two key dimensions is allowed in spec.') + msg = 'Only two key dimensions is allowed in spec.' + raise ValueError(msg) if (r := self.spec[kdims[0]]['region']) != 'point': - raise ValueError( - "Only 'point' region allowed for 'set_point', " - f"{kdims[0]!r} is {r!r}." - ) + msg = f"Only 'point' region allowed for 'set_point', {kdims[0]!r} is {r!r}." + raise ValueError(msg) if (r := self.spec[kdims[1]]['region']) != 'point': - raise ValueError( - "Only 'point' region allowed for 'set_point', " - f"{kdims[1]!r} is {r!r}." - ) + msg = f"Only 'point' region allowed for 'set_point', {kdims[1]!r} is {r!r}." + raise ValueError(msg) regions = {kdims[0]: posx, kdims[1]: posy} self.set_regions(**regions) @@ -310,8 +307,8 @@ def _add_annotation(self, **fields): # Don't do anything if self.region is an empty dict if self.region and self.region != self._last_region: if len(self.annotation_table._annotators)>1: - raise AssertionError('Multiple annotation instances attached to the connector: ' - 'Call add_annotation directly from the associated connector.') + msg = 'Multiple annotation instances attached to the connector: Call add_annotation directly from the associated connector.' + raise AssertionError(msg) self.annotation_table.add_annotation(self._region, spec=self.spec, **fields) self._last_region = self._region.copy() @@ -330,7 +327,8 @@ def delete_annotation(self, index): try: self.annotation_table.delete_annotation(index) except KeyError: - raise ValueError(f"Annotation with index {index!r} does not exist.") from None + msg = f'Annotation with index {index!r} does not exist.' + raise ValueError(msg) from None if index in self.selected_indices: self.selected_indices.remove(index) @@ -375,7 +373,7 @@ def define_fields(self, fields_df, preserve_index=False): print("define_fields is legacy use define_annotations instead") if not preserve_index: indices = [self.connector.primary_key(self.connector) for el in range(len(fields_df))] - index_mapping = {old:new for old, new in zip(fields_df.index, indices)} + index_mapping = dict(zip(fields_df.index, indices)) fields_df = fields_df.set_index(pd.Series(indices, name=self.connector.primary_key.field_name)) else: @@ -385,14 +383,16 @@ def define_fields(self, fields_df, preserve_index=False): def define_ranges(self, startx, endx, starty=None, endy=None, dims=None): print("define_ranges is legacy use define_annotations instead") if dims is None: - raise ValueError('Please specify dimension annotated by defined ranges') + msg = 'Please specify dimension annotated by defined ranges' + raise ValueError(msg) self.annotation_table.define_ranges(dims, startx, endx, starty, endy) def define_points(self, posx, posy=None, dims=None): print("define_points is legacy use define_annotations instead") if dims is None: - raise ValueError('Please specify dimension annotated by defined ranges') + msg = 'Please specify dimension annotated by defined ranges' + raise ValueError(msg) self.annotation_table.define_points(dims, posx, posy=posy) @@ -473,7 +473,8 @@ def edit_tools(self)-> list[Tool]: @classmethod def _infer_kdim_dtypes(cls, element): if not isinstance(element, hv.Element): - raise ValueError('Supplied object {element} is not a bare HoloViews Element') + msg = 'Supplied object {element} is not a bare HoloViews Element' + raise ValueError(msg) kdim_dtypes = {} for kdim in element.dimensions(selection='key'): kdim_dtypes[str(kdim)] = type(element.dimension_values(kdim)[0]) @@ -522,9 +523,7 @@ def _filter_stream_values(self, bounds, x, y, geometry): bounds = None # If selection enabled, tap stream used for selection not for creating point regions - if 'point' in self.region_types and self.selection_enabled: - x, y = None, None - elif 'point' not in self.region_types: + if ('point' in self.region_types and self.selection_enabled) or 'point' not in self.region_types: x, y = None, None return bounds, x, y, geometry @@ -559,7 +558,8 @@ def inner(bounds, x, y, geometry): elif len(kdims) == 2: self.annotator._set_regions(**{kdims[0]: x, kdims[1]: y}) else: - raise ValueError('Only 1d and 2d supported for Points') + msg = 'Only 1d and 2d supported for Points' + raise ValueError(msg) return region_element @@ -774,7 +774,8 @@ def _infer_kdim_dtypes(self, element: hv.Element) -> dict: def _create_annotation_element(self, element_key: tuple[str, ...]) -> AnnotationDisplay: for key in element_key: if key not in self.spec: - raise ValueError(f"Dimension {key!r} not in spec") + msg = f'Dimension {key!r} not in spec' + raise ValueError(msg) return AnnotationDisplay(self, kdims=list(element_key)) def get_element(self, kdims: tuple[str, ...] | str) -> AnnotationDisplay: @@ -828,7 +829,8 @@ def delete_annotation(self, index): def delete_annotations(self, *indices): if not indices: - raise ValueError('At least one index must be specified to delete annotations') + msg = 'At least one index must be specified to delete annotations' + raise ValueError(msg) for index in indices: super().delete_annotation(index) self.refresh() diff --git a/holonote/annotate/connector.py b/holonote/annotate/connector.py index 328f997..3ed0eea 100644 --- a/holonote/annotate/connector.py +++ b/holonote/annotate/connector.py @@ -174,7 +174,7 @@ class Connector(param.Parameterized): @classmethod def field_value_to_type(cls, value): if isinstance(value, list): - assert all([isinstance(el, str) for el in value]), 'Only string enums supported' + assert all(isinstance(el, str) for el in value), 'Only string enums supported' return str elif hasattr(value, 'dtype'): return value.dtype @@ -183,7 +183,8 @@ def field_value_to_type(cls, value): elif isinstance(value, param.Parameter) and value.default is not None: return type(value.default) else: - raise Exception(f'Connector cannot handle type {type(value)!s}') + msg = f'Connector cannot handle type {type(value)!s}' + raise TypeError(msg) @classmethod def schema_from_field_values(cls, fields): @@ -355,7 +356,7 @@ def delete_row(self, id_val): def update_row(self, **updates): # updates as a dictionary OR remove posarg? assert self.primary_key.field_name in updates id_val = updates.pop(self.primary_key.field_name) - set_updates = ', '.join('\"' + k + '\"' + " = ?" for k in updates.keys()) + set_updates = ', '.join('\"' + k + '\"' + " = ?" for k in updates) query = f"UPDATE {self.table_name} SET " + set_updates + f" WHERE \"{self.primary_key.field_name}\" = ?;" self.cursor.execute(query, [*updates.values(), id_val]) self.con.commit() diff --git a/holonote/annotate/table.py b/holonote/annotate/table.py index cf74995..910f1de 100644 --- a/holonote/annotate/table.py +++ b/holonote/annotate/table.py @@ -49,9 +49,11 @@ def load(self, connector=None, fields_df=None, primary_key_name=None, fields=Non fields = [] if [connector, primary_key_name] == [None,None]: - raise ValueError('Either a connector instance must be supplied or the primary key name supplied') + msg = "Either a connector instance must be supplied or the primary key name supplied" + raise ValueError(msg) if len(fields) < 1: - raise ValueError('More than one field column is required') + msg = "More than one field column is required" + raise ValueError(msg) primary_key_name = primary_key_name if primary_key_name else connector.primary_key.field_name if fields_df: @@ -93,7 +95,8 @@ def has_snapshot(self) -> bool: def revert_to_snapshot(self): "Clears outstanding changes and used to implement an basic undo system." if self._field_df_snapshot is None: - raise Exception('Call snapshot method before calling revert_to_snapshot') + msg = "Call snapshot method before calling revert_to_snapshot" + raise Exception(msg) self._field_df = self._field_df_snapshot self._region_df = self._region_df_snapshot self.clear_edits() @@ -139,7 +142,8 @@ def _create_commits(self): region_inds = set(self._region_df['_id'].unique()) unassigned_inds = fields_inds - region_inds if unassigned_inds: - raise ValueError(f'Following annotations have no associated region: {unassigned_inds}') + msg = f"Following annotations have no associated region: {unassigned_inds}" + raise ValueError(msg) commits = [] for edit in self._edits: @@ -209,10 +213,11 @@ def add_annotation(self, regions: dict[str, Any], spec: SpecDict, **fields): def _add_annotation_fields(self, index_value, fields=None): - index_name_set = set() if self._field_df.index.name is None else set([self._field_df.index.name]) + index_name_set = set() if self._field_df.index.name is None else {self._field_df.index.name} unknown_kwargs = set(fields.keys()) - set(self._field_df.columns) if unknown_kwargs - index_name_set: - raise KeyError(f'Unknown fields columns: {list(unknown_kwargs)}') + msg = f"Unknown fields columns: {list(unknown_kwargs)}" + raise KeyError(msg) new_fields = pd.DataFrame([dict(fields, **{self._field_df.index.name:index_value})]) new_fields = new_fields.set_index(self._field_df.index.name) @@ -220,7 +225,8 @@ def _add_annotation_fields(self, index_value, fields=None): def delete_annotation(self, index): if index is None: - raise ValueError('Deletion index cannot be None') + msg = "Deletion index cannot be None" + raise ValueError(msg) self._region_df = self._region_df[self._region_df['_id'] != index] # Could match multiple rows self._field_df = self._field_df.drop(index, axis=0) @@ -232,16 +238,18 @@ def update_annotation_fields(self, index, **fields): self._field_df.loc[index, column] = value self._edits.append({'operation':'update', 'id':index, - 'fields' : [c for c in fields.keys()], + 'fields' : list(fields), 'region_fields' : []}) # Methods to map into holoviews def _validate_index_to_fields(self, series): if series.index.name != self._field_df.index.name: - raise ValueError(f'Index name {series.index.name} does not match fields index name {self._field_df.index.name}') + msg = f"Index name {series.index.name} does not match fields index name {self._field_df.index.name}" + raise ValueError(msg) if series.index.dtype != self._field_df.index.dtype: - raise ValueError('Index dtype does not match fields index dtype') + msg = "Index dtype does not match fields index dtype" + raise ValueError(msg) def _assert_indices_match(self, *series): if all(s.index is series[0].index for s in series): @@ -249,11 +257,13 @@ def _assert_indices_match(self, *series): else: index_names = [s.index.name for s in series] if not all(name == index_names[0] for name in index_names): - raise ValueError(f'Index names do not match: {index_names}') + msg = f"Index names do not match: {index_names}" + raise ValueError(msg) # TODO: Match dtypes match_values = all(all(s.index == series[0].index) for s in series) if not match_values: - raise ValueError('Indices do not match') + msg = "Indices do not match" + raise ValueError(msg) # for s in series: # self._validate_index_to_fields(s) @@ -276,9 +286,11 @@ def define_points(self, dims, posx, posy=None): if isinstance(dims, str): dims = (dims,) if posy is None and len(dims)==2: - raise ValueError('Two dimensions declared but data for only one specified') + msg = "Two dimensions declared but data for only one specified" + raise ValueError(msg) if posy is not None and len(dims)==1: - raise ValueError('Only one dimensions declared but data for more than one specified.') + msg = "Only one dimensions declared but data for more than one specified." + raise ValueError(msg) if len(dims)==2: self._assert_indices_match(posx, posy) @@ -286,7 +298,8 @@ def define_points(self, dims, posx, posy=None): mismatches = [el for el in posx.index if self._index_mapping.get(el,el) not in self._field_df.index] if any(mismatches): - raise KeyError(f'Keys {mismatches} do not match any fields entries') + msg = f"Keys {mismatches} do not match any fields entries" + raise KeyError(msg) dim2 = None if len(dims)==1 else dims[1] value = zip(posx, [None] * len(posx)) if len(dims)==1 else zip(posx, posy) @@ -300,10 +313,12 @@ def define_points(self, dims, posx, posy=None): def define_ranges(self, dims, startx, endx, starty=None, endy=None): if isinstance(dims, str): dims = (dims,) - if len(dims)==2 and any([el is None for el in [starty, endy]]): - raise ValueError('Two dimensions declared but insufficient data specified') + if len(dims)==2 and any(el is None for el in [starty, endy]): + msg = "Two dimensions declared but insufficient data specified" + raise ValueError(msg) if len(dims)==1 and (starty, endy) != (None, None): - raise ValueError('Only one dimensions declared but data for more than one specified.') + msg = "Only one dimensions declared but data for more than one specified." + raise ValueError(msg) if len(dims)==1: self._assert_indices_match(startx, endx) @@ -313,7 +328,8 @@ def define_ranges(self, dims, startx, endx, starty=None, endy=None): mismatches = [el for el in startx.index if self._index_mapping.get(el,el) not in self._field_df.index] if any(mismatches): - raise KeyError(f'Keys {mismatches} do not match any fields entries') + msg = f"Keys {mismatches} do not match any fields entries" + raise KeyError(msg) dim2 = None if len(dims)==1 else dims[1] diff --git a/holonote/app/panel.py b/holonote/app/panel.py index 296d62d..08053ac 100644 --- a/holonote/app/panel.py +++ b/holonote/app/panel.py @@ -1,5 +1,6 @@ from __future__ import annotations +import contextlib import datetime as dt from typing import TYPE_CHECKING, Any @@ -89,10 +90,9 @@ def _reset_fields_widgets(self): for widget_name, default in self._fields_values.items(): if isinstance(default, param.Parameter): default = default.default - try: + with contextlib.suppress(Exception): + # TODO: Fix when lists (for categories, not the same as the default!) self._fields_widgets[widget_name].value = default - except Exception: - pass # TODO: Fix when lists (for categories, not the same as the default!) def _callback_apply(self, event): selected_ind = ( @@ -111,9 +111,8 @@ def _callback_apply(self, event): self.annotator.update_annotation_fields( selected_ind, **fields_values ) # TODO: Handle only changed - elif self._widget_mode_group.value == "-": - if selected_ind is not None: - self.annotator.delete_annotation(selected_ind) + elif self._widget_mode_group.value == "-" and selected_ind is not None: + self.annotator.delete_annotation(selected_ind) def _callback_commit(self, event): self.annotator.commit() diff --git a/holonote/tests/conftest.py b/holonote/tests/conftest.py index fc5db89..f37ea36 100644 --- a/holonote/tests/conftest.py +++ b/holonote/tests/conftest.py @@ -1,5 +1,6 @@ from __future__ import annotations +import contextlib from typing import Iterator import holoviews as hv @@ -14,14 +15,10 @@ def conn_sqlite_uuid(tmp_path) -> Iterator[SQLiteDB]: conn = SQLiteDB(filename=str(tmp_path / "test.db"), primary_key=UUIDHexStringKey()) yield conn - try: + with contextlib.suppress(Exception): conn.cursor.close() - except Exception: - pass - try: + with contextlib.suppress(Exception): conn.con.close() - except Exception: - pass @pytest.fixture() diff --git a/holonote/tests/test_annotators_advanced.py b/holonote/tests/test_annotators_advanced.py index 4f3cb61..d1a764d 100644 --- a/holonote/tests/test_annotators_advanced.py +++ b/holonote/tests/test_annotators_advanced.py @@ -75,9 +75,9 @@ def test_insertion_values(self, multiple_fields_annotator): commits = multiple_fields_annotator.commit(return_commits=True) kwargs = commits[0]['kwargs'] assert len(commits)==1, 'Only one insertion commit made' - assert 'uuid' in kwargs.keys(), 'Expected uuid primary key in kwargs' + assert 'uuid' in kwargs, 'Expected uuid primary key in kwargs' kwargs.pop('uuid') - assert kwargs == dict(field1='A test field', field2='Another test field', start_TIME=start, end_TIME=end) + assert kwargs == {"field1": 'A test field', "field2": 'Another test field', "start_TIME": start, "end_TIME": end} def test_commit_insertion(self, multiple_fields_annotator): diff --git a/holonote/tests/test_annotators_basic.py b/holonote/tests/test_annotators_basic.py index cdcacfd..fbddd25 100644 --- a/holonote/tests/test_annotators_basic.py +++ b/holonote/tests/test_annotators_basic.py @@ -32,9 +32,9 @@ def test_range_insertion_values(self, annotator_range1d) -> None: commits = annotator_range1d.commit(return_commits=True) assert len(commits)==1, 'Only one insertion commit made' kwargs = commits[0]['kwargs'] - assert 'uuid' in kwargs.keys(), 'Expected uuid primary key in kwargs' + assert 'uuid' in kwargs, 'Expected uuid primary key in kwargs' kwargs.pop('uuid') - assert kwargs, dict(description='A test annotation!', start_TIME=start, end_TIME=end) + assert kwargs, {'description': 'A test annotation!', 'start_TIME': start, 'end_TIME': end} def test_range_commit_insertion(self, annotator_range1d): start, end = np.datetime64('2022-06-06'), np.datetime64('2022-06-08') @@ -65,12 +65,12 @@ def test_range_addition_deletion_by_uuid(self, annotator_range1d): annotator_range1d.add_annotation(description='Annotation 3') annotator_range1d.commit(return_commits=True) sql_df = annotator_range1d.connector.load_dataframe() - assert set(sql_df['description']) ==set(['Annotation 1', 'Annotation 2', 'Annotation 3']) + assert set(sql_df['description']) == {'Annotation 1', 'Annotation 2', 'Annotation 3'} deletion_index = sql_df.index[1] annotator_range1d.delete_annotation(deletion_index) annotator_range1d.commit(return_commits=True) sql_df = annotator_range1d.connector.load_dataframe() - assert set(sql_df['description']) == set(['Annotation 1', 'Annotation 3']) + assert set(sql_df['description']) == {'Annotation 1', 'Annotation 3'} def test_range_define_preserved_index_mismatch(self, annotator_range1d): @@ -141,10 +141,10 @@ def test_range_insertion_values(self, annotator_range2d): commits = annotator_range2d.commit(return_commits=True) assert len(commits)==1, 'Only one insertion commit made' kwargs = commits[0]['kwargs'] - assert 'uuid' in kwargs.keys(), 'Expected uuid primary key in kwargs' + assert 'uuid' in kwargs, 'Expected uuid primary key in kwargs' kwargs.pop('uuid') - assert kwargs == dict(description='A test annotation!', - start_x=startx, end_x=endx, start_y=starty, end_y=endy) + assert kwargs == {'description': 'A test annotation!', + 'start_x': startx, 'end_x': endx, 'start_y': starty, 'end_y': endy} def test_range_commit_insertion(self, annotator_range2d): startx, endx, starty, endy = -0.25, 0.25, -0.1, 0.1 @@ -177,12 +177,12 @@ def test_range_addition_deletion_by_uuid(self, annotator_range2d): annotator_range2d.add_annotation(description='Annotation 3') annotator_range2d.commit(return_commits=True) sql_df = annotator_range2d.connector.load_dataframe() - assert set(sql_df['description']) == set(['Annotation 1', 'Annotation 2', 'Annotation 3']) + assert set(sql_df['description']) == {'Annotation 1', 'Annotation 2', 'Annotation 3'} deletion_index = sql_df.index[1] annotator_range2d.delete_annotation(deletion_index) annotator_range2d.commit(return_commits=True) sql_df = annotator_range2d.connector.load_dataframe() - assert set(sql_df['description']) == set(['Annotation 1', 'Annotation 3']) + assert set(sql_df['description']) == {'Annotation 1', 'Annotation 3'} def test_range_define_preserved_index_mismatch(self, annotator_range2d): @@ -262,9 +262,9 @@ def test_point_insertion_values(self, annotator_point1d): commits = annotator_point1d.commit(return_commits=True) assert len(commits)==1, 'Only one insertion commit made' kwargs = commits[0]['kwargs'] - assert 'uuid' in kwargs.keys(), 'Expected uuid primary key in kwargs' + assert 'uuid' in kwargs, 'Expected uuid primary key in kwargs' kwargs.pop('uuid') - assert kwargs == dict(description='A test annotation!', point_TIME=timestamp) + assert kwargs == {'description': 'A test annotation!', 'point_TIME': timestamp} def test_point_commit_insertion(self, annotator_point1d): timestamp = np.datetime64('2022-06-06') @@ -294,12 +294,12 @@ def test_point_addition_deletion_by_uuid(self, annotator_point1d): annotator_point1d.add_annotation(description='Annotation 3') annotator_point1d.commit(return_commits=True) sql_df = annotator_point1d.connector.load_dataframe() - assert set(sql_df['description']) == set(['Annotation 1', 'Annotation 2', 'Annotation 3']) + assert set(sql_df['description']) == {'Annotation 1', 'Annotation 2', 'Annotation 3'} deletion_index = sql_df.index[1] annotator_point1d.delete_annotation(deletion_index) annotator_point1d.commit(return_commits=True) sql_df = annotator_point1d.connector.load_dataframe() - assert set(sql_df['description']) == set(['Annotation 1', 'Annotation 3']) + assert set(sql_df['description']) == {'Annotation 1', 'Annotation 3'} def test_point_define_preserved_index_mismatch(self, annotator_point1d): timestamps = [np.datetime64('2022-06-%.2d' % d) for d in range(6,15, 4)] @@ -366,9 +366,9 @@ def test_point_insertion_values(self, annotator_point2d): commits = annotator_point2d.commit(return_commits=True) assert len(commits)==1, 'Only one insertion commit made' kwargs = commits[0]['kwargs'] - assert 'uuid' in kwargs.keys(), 'Expected uuid primary key in kwargs' + assert 'uuid' in kwargs, 'Expected uuid primary key in kwargs' kwargs.pop('uuid') - assert kwargs == dict(description='A test annotation!', point_x=x, point_y=y) + assert kwargs == {'description': 'A test annotation!', 'point_x': x, 'point_y': y} def test_point_commit_insertion(self, annotator_point2d): x, y = 0.5, 0.3 @@ -399,12 +399,12 @@ def test_point_addition_deletion_by_uuid(self, annotator_point2d): annotator_point2d.add_annotation(description='Annotation 3') annotator_point2d.commit(return_commits=True) sql_df = annotator_point2d.connector.load_dataframe() - assert set(sql_df['description']) == set(['Annotation 1', 'Annotation 2', 'Annotation 3']) + assert set(sql_df['description']) == {'Annotation 1', 'Annotation 2', 'Annotation 3'} deletion_index = sql_df.index[1] annotator_point2d.delete_annotation(deletion_index) annotator_point2d.commit(return_commits=True) sql_df = annotator_point2d.connector.load_dataframe() - assert set(sql_df['description']) == set(['Annotation 1', 'Annotation 3']) + assert set(sql_df['description']) == {'Annotation 1', 'Annotation 3'} def test_point_define_preserved_index_mismatch(self, annotator_point2d): xs, ys = [-0.1,-0.2,-0.3], [0.1,0.2,0.3] @@ -449,7 +449,7 @@ def test_point_define_unassigned_indices(self, annotator_point2d): annotator_point2d.define_points(data2['xs'], data2['ys']) -@pytest.mark.parametrize('fields', (["test"], ["test1", "test2"])) +@pytest.mark.parametrize('fields', [["test"], ["test1", "test2"]]) def test_connector_use_annotator_fields(conn_sqlite_uuid, fields): annotator = Annotator({"TIME": float}, connector=conn_sqlite_uuid, fields=fields) diff --git a/pyproject.toml b/pyproject.toml index 167ade4..1be5d16 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -47,18 +47,23 @@ target-version = "py38" select = [ "B", + "C4", "E", + "EM", "F", "FLY", "I", "ICN", + "ISC", "NPY", "PIE", "PLC", "PLE", "PLR", "PLW", + "PT", "RUF", + "SIM", "UP", "W", ] @@ -71,7 +76,6 @@ ignore = [ "E731", # Do not assign a lambda expression, use a def "E741", # Ambiguous variable name "F405", # From star imports - "PLC1901", # empty string is falsey "PLE0604", # Invalid object in `__all__`, must contain only strings "PLE0605", # Invalid format for `__all__` "PLR091", # Too many arguments/branches/statements