Skip to content

Commit cdd338c

Browse files
authored
Linting: Enable PLR6301, # could be a function, class method or static method (open-edge-platform#2288)
* PLR6301 Method could be a function, class method, or static method * "PLR6301", # could be a function, class method or static method Signed-off-by: Samet Akcay <[email protected]> * revert missing pytest fixture * refactor: convert instance methods to static methods where applicable Signed-off-by: Samet Akcay <[email protected]> * Fix data tests Signed-off-by: Samet Akcay <[email protected]> * Fix shanghai tech config filename * Fix base anomaly module tests * Fix base anomaly module tests Signed-off-by: Samet Akcay <[email protected]> * add staticmethod before parametrize Signed-off-by: Samet Akcay <[email protected]> --------- Signed-off-by: Samet Akcay <[email protected]>
1 parent 18ab25c commit cdd338c

File tree

79 files changed

+404
-248
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

79 files changed

+404
-248
lines changed
File renamed without changes.

pyproject.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,6 @@ lint.ignore = [
165165
"A004", # import is shadowing a Python built-in
166166
"A005", # Module is shadowing a Python built-in
167167
"B909", # Mutation to loop iterable during iteration
168-
"PLR6301", # could be a function, class method or static method
169168
"PLC2701", # Private name import
170169
"PLC0415", # import should be at the top of the file
171170
"PLR0917", # Too many positional arguments

src/anomalib/callbacks/graph.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,8 @@ class GraphLogger(Callback):
3333
>>> engine = Engine(logger=logger, callbacks=callbacks)
3434
"""
3535

36-
def on_train_start(self, trainer: Trainer, pl_module: LightningModule) -> None:
36+
@staticmethod
37+
def on_train_start(trainer: Trainer, pl_module: LightningModule) -> None:
3738
"""Log model graph to respective logger.
3839
3940
Args:
@@ -47,7 +48,8 @@ def on_train_start(self, trainer: Trainer, pl_module: LightningModule) -> None:
4748
logger.watch(pl_module, log_graph=True, log="all")
4849
break
4950

50-
def on_train_end(self, trainer: Trainer, pl_module: LightningModule) -> None:
51+
@staticmethod
52+
def on_train_end(trainer: Trainer, pl_module: LightningModule) -> None:
5153
"""Unwatch model if configured for wandb and log it model graph in Tensorboard if specified.
5254
5355
Args:

src/anomalib/callbacks/metrics.py

Lines changed: 8 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -98,11 +98,8 @@ def setup(
9898
pl_module.pixel_metrics = create_metric_collection(pixel_metric_names, "pixel_")
9999
self._set_threshold(pl_module)
100100

101-
def on_validation_epoch_start(
102-
self,
103-
trainer: Trainer,
104-
pl_module: AnomalyModule,
105-
) -> None:
101+
@staticmethod
102+
def on_validation_epoch_start(trainer: Trainer, pl_module: AnomalyModule) -> None:
106103
del trainer # Unused argument.
107104

108105
pl_module.image_metrics.reset()
@@ -123,21 +120,14 @@ def on_validation_batch_end(
123120
self._outputs_to_device(outputs)
124121
self._update_metrics(pl_module.image_metrics, pl_module.pixel_metrics, outputs)
125122

126-
def on_validation_epoch_end(
127-
self,
128-
trainer: Trainer,
129-
pl_module: AnomalyModule,
130-
) -> None:
123+
def on_validation_epoch_end(self, trainer: Trainer, pl_module: AnomalyModule) -> None:
131124
del trainer # Unused argument.
132125

133126
self._set_threshold(pl_module)
134127
self._log_metrics(pl_module)
135128

136-
def on_test_epoch_start(
137-
self,
138-
trainer: Trainer,
139-
pl_module: AnomalyModule,
140-
) -> None:
129+
@staticmethod
130+
def on_test_epoch_start(trainer: Trainer, pl_module: AnomalyModule) -> None:
141131
del trainer # Unused argument.
142132

143133
pl_module.image_metrics.reset()
@@ -158,16 +148,13 @@ def on_test_batch_end(
158148
self._outputs_to_device(outputs)
159149
self._update_metrics(pl_module.image_metrics, pl_module.pixel_metrics, outputs)
160150

161-
def on_test_epoch_end(
162-
self,
163-
trainer: Trainer,
164-
pl_module: AnomalyModule,
165-
) -> None:
151+
def on_test_epoch_end(self, trainer: Trainer, pl_module: AnomalyModule) -> None:
166152
del trainer # Unused argument.
167153

168154
self._log_metrics(pl_module)
169155

170-
def _set_threshold(self, pl_module: AnomalyModule) -> None:
156+
@staticmethod
157+
def _set_threshold(pl_module: AnomalyModule) -> None:
171158
pl_module.image_metrics.set_threshold(pl_module.image_threshold.value.item())
172159
pl_module.pixel_metrics.set_threshold(pl_module.pixel_threshold.value.item())
173160

src/anomalib/callbacks/nncf/utils.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,8 @@ def __next__(self) -> torch.Tensor:
4040
loaded_item = next(self._data_loader_iter)
4141
return loaded_item["image"]
4242

43-
def get_inputs(self, dataloader_output: dict[str, str | torch.Tensor]) -> tuple[tuple, dict]:
43+
@staticmethod
44+
def get_inputs(dataloader_output: dict[str, str | torch.Tensor]) -> tuple[tuple, dict]:
4445
"""Get input to model.
4546
4647
Returns:
@@ -49,7 +50,8 @@ def get_inputs(self, dataloader_output: dict[str, str | torch.Tensor]) -> tuple[
4950
"""
5051
return (dataloader_output,), {}
5152

52-
def get_target(self, _): # noqa: ANN001, ANN201
53+
@staticmethod
54+
def get_target(_) -> None: # noqa: ANN001
5355
"""Return structure for ground truth in loss criterion based on dataloader output.
5456
5557
This implementation does not do anything and is a placeholder.

src/anomalib/callbacks/normalization/min_max_normalization.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ class _MinMaxNormalizationCallback(NormalizationCallback):
2323
Note: This callback is set within the Engine.
2424
"""
2525

26-
def setup(self, trainer: Trainer, pl_module: AnomalyModule, stage: str | None = None) -> None:
26+
@staticmethod
27+
def setup(trainer: Trainer, pl_module: AnomalyModule, stage: str | None = None) -> None:
2728
"""Add min_max metrics to normalization metrics."""
2829
del trainer, stage # These variables are not used.
2930

@@ -48,23 +49,25 @@ def setup(self, trainer: Trainer, pl_module: AnomalyModule, stage: str | None =
4849
msg = f"Expected normalization_metric {name} to be of type MinMax, got {type(metric)}"
4950
raise TypeError(msg)
5051

51-
def on_test_start(self, trainer: Trainer, pl_module: AnomalyModule) -> None:
52+
@staticmethod
53+
def on_test_start(trainer: Trainer, pl_module: AnomalyModule) -> None:
5254
"""Call when the test begins."""
5355
del trainer # `trainer` variable is not used.
5456

5557
for metric in (pl_module.image_metrics, pl_module.pixel_metrics):
5658
if metric is not None:
5759
metric.set_threshold(0.5)
5860

59-
def on_validation_epoch_start(self, trainer: Trainer, pl_module: AnomalyModule) -> None:
61+
@staticmethod
62+
def on_validation_epoch_start(trainer: Trainer, pl_module: AnomalyModule) -> None:
6063
"""Call when the validation epoch begins."""
6164
del trainer # `trainer` variable is not used.
6265

6366
if hasattr(pl_module, "normalization_metrics"):
6467
pl_module.normalization_metrics.reset()
6568

69+
@staticmethod
6670
def on_validation_batch_end(
67-
self,
6871
trainer: Trainer,
6972
pl_module: AnomalyModule,
7073
outputs: STEP_OUTPUT,

src/anomalib/callbacks/thresholding.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,8 @@ def _load_from_config(self, threshold: DictConfig | str | ListConfig | list[dict
133133
msg = f"Invalid threshold config {threshold}"
134134
raise TypeError(msg)
135135

136-
def _get_threshold_from_config(self, threshold: DictConfig | str | dict[str, str | float]) -> Threshold:
136+
@staticmethod
137+
def _get_threshold_from_config(threshold: DictConfig | str | dict[str, str | float]) -> Threshold:
137138
"""Return the instantiated threshold object.
138139
139140
Example:
@@ -170,7 +171,8 @@ def _get_threshold_from_config(self, threshold: DictConfig | str | dict[str, str
170171
class_ = getattr(module, class_path)
171172
return class_(**init_args)
172173

173-
def _reset(self, pl_module: AnomalyModule) -> None:
174+
@staticmethod
175+
def _reset(pl_module: AnomalyModule) -> None:
174176
pl_module.image_threshold.reset()
175177
pl_module.pixel_threshold.reset()
176178

@@ -182,14 +184,16 @@ def _outputs_to_cpu(self, output: STEP_OUTPUT) -> STEP_OUTPUT | dict[str, Any]:
182184
output = output.cpu()
183185
return output
184186

185-
def _update(self, pl_module: AnomalyModule, outputs: STEP_OUTPUT) -> None:
187+
@staticmethod
188+
def _update(pl_module: AnomalyModule, outputs: STEP_OUTPUT) -> None:
186189
pl_module.image_threshold.cpu()
187190
pl_module.image_threshold.update(outputs["pred_scores"], outputs["label"].int())
188191
if "mask" in outputs and "anomaly_maps" in outputs:
189192
pl_module.pixel_threshold.cpu()
190193
pl_module.pixel_threshold.update(outputs["anomaly_maps"], outputs["mask"].int())
191194

192-
def _compute(self, pl_module: AnomalyModule) -> None:
195+
@staticmethod
196+
def _compute(pl_module: AnomalyModule) -> None:
193197
pl_module.image_threshold.compute()
194198
if pl_module.pixel_threshold._update_called: # noqa: SLF001
195199
pl_module.pixel_threshold.compute()

src/anomalib/callbacks/visualizer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,8 +146,8 @@ def on_predict_batch_end(
146146
def on_predict_end(self, trainer: Trainer, pl_module: AnomalyModule) -> None:
147147
return self.on_test_end(trainer, pl_module)
148148

149+
@staticmethod
149150
def _add_to_logger(
150-
self,
151151
result: GeneratorResult,
152152
module: AnomalyModule,
153153
trainer: Trainer,

src/anomalib/cli/cli.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,8 @@ def __init__(self, args: Sequence[str] | None = None, run: bool = True) -> None:
6464
if run:
6565
self._run_subcommand()
6666

67-
def init_parser(self, **kwargs) -> ArgumentParser:
67+
@staticmethod
68+
def init_parser(**kwargs) -> ArgumentParser:
6869
"""Method that instantiates the argument parser."""
6970
kwargs.setdefault("dump_header", [f"anomalib=={__version__}"])
7071
parser = ArgumentParser(formatter_class=CustomHelpFormatter, **kwargs)
@@ -139,7 +140,8 @@ def add_subcommands(self, **kwargs) -> None:
139140
self.subcommand_parsers[subcommand] = sub_parser
140141
parser_subcommands.add_subcommand(subcommand, sub_parser, help=value["description"])
141142

142-
def add_arguments_to_parser(self, parser: ArgumentParser) -> None:
143+
@staticmethod
144+
def add_arguments_to_parser(parser: ArgumentParser) -> None:
143145
"""Extend trainer's arguments to add engine arguments.
144146
145147
.. note::
@@ -399,8 +401,8 @@ def export(self) -> Callable:
399401
"""Export the model using engine's export method."""
400402
return self.engine.export
401403

404+
@staticmethod
402405
def _add_trainer_arguments_to_parser(
403-
self,
404406
parser: ArgumentParser,
405407
add_optimizer: bool = False,
406408
add_scheduler: bool = False,
@@ -427,7 +429,8 @@ def _add_trainer_arguments_to_parser(
427429
**scheduler_kwargs,
428430
)
429431

430-
def _add_default_arguments_to_parser(self, parser: ArgumentParser) -> None:
432+
@staticmethod
433+
def _add_default_arguments_to_parser(parser: ArgumentParser) -> None:
431434
"""Adds default arguments to the parser."""
432435
parser.add_argument(
433436
"--seed_everything",

src/anomalib/data/video/shanghaitech.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,8 @@ class ShanghaiTechTrainClipsIndexer(ClipsIndexer):
118118
clips indexer implementations are needed.
119119
"""
120120

121-
def get_mask(self, idx: int) -> torch.Tensor | None:
121+
@staticmethod
122+
def get_mask(idx: int) -> torch.Tensor | None:
122123
"""No masks available for training set."""
123124
del idx # Unused argument
124125
return None

src/anomalib/deploy/inferencers/base_inferencer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ def _normalize(
118118

119119
return anomaly_maps, float(pred_scores)
120120

121-
def _load_metadata(self, path: str | Path | dict | None = None) -> dict | DictConfig:
121+
def _load_metadata(self, path: str | Path | dict | None = None) -> dict | DictConfig: # noqa: PLR6301
122122
"""Load the meta data from the given path.
123123
124124
Args:

src/anomalib/deploy/inferencers/openvino_inferencer.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,8 @@ def load_model(self, path: str | Path | tuple[bytes, bytes]) -> tuple[Any, Any,
150150

151151
return input_blob, output_blob, compile_model
152152

153-
def pre_process(self, image: np.ndarray) -> np.ndarray:
153+
@staticmethod
154+
def pre_process(image: np.ndarray) -> np.ndarray:
154155
"""Pre-process the input image by applying transformations.
155156
156157
Args:

src/anomalib/metrics/threshold/base.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ class Threshold(Metric):
2323
def __init__(self, **kwargs) -> None:
2424
super().__init__(**kwargs)
2525

26-
def compute(self) -> torch.Tensor:
26+
def compute(self) -> torch.Tensor: # noqa: PLR6301
2727
"""Compute the threshold.
2828
2929
Returns:
@@ -32,7 +32,7 @@ def compute(self) -> torch.Tensor:
3232
msg = "Subclass of Threshold must implement the compute method"
3333
raise NotImplementedError(msg)
3434

35-
def update(self, *args, **kwargs) -> None: # noqa: ARG002
35+
def update(self, *args, **kwargs) -> None: # noqa: ARG002, PLR6301
3636
"""Update the metric state.
3737
3838
Args:

src/anomalib/metrics/threshold/manual_threshold.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,8 @@ def compute(self) -> torch.Tensor:
5656
"""
5757
return self.value
5858

59-
def update(self, *args, **kwargs) -> None:
59+
@staticmethod
60+
def update(*args, **kwargs) -> None:
6061
"""Do nothing.
6162
6263
Args:

src/anomalib/models/components/base/anomaly_module.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,8 @@ def _add_metrics(self, name: str, state_dict: OrderedDict[str, torch.Tensor]) ->
215215
logger.info("Loading %s metrics from state dict", class_name)
216216
metrics.add_metrics(metrics_cls())
217217

218-
def _get_instance(self, state_dict: OrderedDict[str, Any], dict_key: str) -> Threshold:
218+
@staticmethod
219+
def _get_instance(state_dict: OrderedDict[str, Any], dict_key: str) -> Threshold:
219220
"""Get the threshold class from the ``state_dict``."""
220221
class_path = state_dict.pop(dict_key)
221222
module = importlib.import_module(".".join(class_path.split(".")[:-1]))
@@ -240,7 +241,7 @@ def set_transform(self, transform: Transform) -> None:
240241
"""Update the transform linked to the model instance."""
241242
self._transform = transform
242243

243-
def configure_transforms(self, image_size: tuple[int, int] | None = None) -> Transform:
244+
def configure_transforms(self, image_size: tuple[int, int] | None = None) -> Transform: # noqa: PLR6301
244245
"""Default transforms.
245246
246247
The default transform is resize to 256x256 and normalize to ImageNet stats. Individual models can override

src/anomalib/models/components/base/export_mixin.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -310,8 +310,8 @@ def _compress_ov_model(
310310

311311
return model
312312

313+
@staticmethod
313314
def _post_training_quantization_ov(
314-
self,
315315
model: "CompiledModel",
316316
datamodule: AnomalibDataModule | None = None,
317317
) -> "CompiledModel":
@@ -346,8 +346,8 @@ def _post_training_quantization_ov(
346346
calibration_dataset = nncf.Dataset(dataloader, lambda x: x["image"])
347347
return nncf.quantize(model, calibration_dataset)
348348

349+
@staticmethod
349350
def _accuracy_control_quantization_ov(
350-
self,
351351
model: "CompiledModel",
352352
datamodule: AnomalibDataModule | None = None,
353353
metric: Metric | str | None = None,

src/anomalib/models/components/dimensionality_reduction/random_projection.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,8 @@ def _sparse_random_matrix(self, n_features: int) -> torch.Tensor:
9898

9999
return components
100100

101-
def _johnson_lindenstrauss_min_dim(self, n_samples: int, eps: float = 0.1) -> int | np.integer:
101+
@staticmethod
102+
def _johnson_lindenstrauss_min_dim(n_samples: int, eps: float = 0.1) -> int | np.integer:
102103
"""Find a 'safe' number of components to randomly project to.
103104
104105
Ref eqn 2.1 https://cseweb.ucsd.edu/~dasgupta/papers/jl.pdf

src/anomalib/models/components/flow/all_in_one_block.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -330,7 +330,8 @@ def forward(
330330

331331
return (x_out,), log_jac_det
332332

333-
def output_dims(self, input_dims: list[tuple[int]]) -> list[tuple[int]]:
333+
@staticmethod
334+
def output_dims(input_dims: list[tuple[int]]) -> list[tuple[int]]:
334335
"""Output dimensions of the layer.
335336
336337
Args:

src/anomalib/models/image/cfa/lightning_model.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,8 @@ def validation_step(self, batch: dict[str, str | torch.Tensor], *args, **kwargs)
104104
batch["anomaly_maps"] = self.model(batch["image"])
105105
return batch
106106

107-
def backward(self, loss: torch.Tensor, *args, **kwargs) -> None:
107+
@staticmethod
108+
def backward(loss: torch.Tensor, *args, **kwargs) -> None:
108109
"""Perform backward-pass for the CFA model.
109110
110111
Args:

src/anomalib/models/image/csflow/loss.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@
1010
class CsFlowLoss(nn.Module):
1111
"""Loss function for the CS-Flow Model Implementation."""
1212

13-
def forward(self, z_dist: torch.Tensor, jacobians: torch.Tensor) -> torch.Tensor:
13+
@staticmethod
14+
def forward(z_dist: torch.Tensor, jacobians: torch.Tensor) -> torch.Tensor:
1415
"""Compute the loss CS-Flow.
1516
1617
Args:

0 commit comments

Comments
 (0)