Skip to content

Commit db9976a

Browse files
Bordapre-commit-ci[bot]aymuos15ericspodKumoLiu
authored andcommitted
Complete replace flake8 with ruff and update rules (Project-MONAI#8694)
This pull request removes support for `flake8` in favor of using `ruff` as the primary Python linter and code style checker. It updates configuration files, scripts, and workflow definitions to reflect this change, and consolidates all linting rules and ignores into `pyproject.toml` under the `[tool.ruff]` section. **Migration from flake8 to ruff:** * Removed all references to `flake8` and its plugins from `requirements-dev.txt`, `setup.cfg`, and the `runtests.sh` script, making `ruff` the sole linter for code style checks. [[1]](diffhunk://#diff-2b4945591edfeaa4cf4d3f155e66d4b43d1bda7a55d881d5cf3107f1b05abbbcL13-L15) [[2]](diffhunk://#diff-fa602a8a75dc9dcc92261bac5f533c2a85e34fcceaff63b3a3a81d9acde2fc52L182-L211) [[3]](diffhunk://#diff-8b8238839d9c98a26d9a1d5a504a38807afa0dbee153e4d565de8e617e98e51fL46) [[4]](diffhunk://#diff-8b8238839d9c98a26d9a1d5a504a38807afa0dbee153e4d565de8e617e98e51fL63-R62) [[5]](diffhunk://#diff-8b8238839d9c98a26d9a1d5a504a38807afa0dbee153e4d565de8e617e98e51fL83) [[6]](diffhunk://#diff-8b8238839d9c98a26d9a1d5a504a38807afa0dbee153e4d565de8e617e98e51fL270) [[7]](diffhunk://#diff-8b8238839d9c98a26d9a1d5a504a38807afa0dbee153e4d565de8e617e98e51fL302-L304) [[8]](diffhunk://#diff-8b8238839d9c98a26d9a1d5a504a38807afa0dbee153e4d565de8e617e98e51fL536-L561) * Updated GitHub Actions workflow job names from `flake8-py3` to `lint-py3` to reflect the switch to `ruff`. [[1]](diffhunk://#diff-cbf97851bdfebccf2fcdd8848c6a93adb8d8affd5c6b1faf00238d528c3ef6cbL25-R25) [[2]](diffhunk://#diff-9b4c9bf29b5daef8f9801986e98f75a0dfd296014e719d3fcfb1ac359c063c74L8-R8) **Ruff configuration enhancements:** * Expanded the `[tool.ruff.lint].select` list in `pyproject.toml` to include additional rule sets previously covered by `flake8` plugins (e.g., `B` for flake8-bugbear, `C90` for mccabe, `N` for pep8-naming, etc.). * Migrated and extended ignore rules from `flake8` to `ruff`, ensuring that all previously ignored warnings and errors are now managed through `pyproject.toml`. * Adjusted `line-length` in `pyproject.toml` from 133 to 120 to standardize formatting. **Cleanup:** * Removed the `[flake8]` section from `setup.cfg`, consolidating all linting configuration into `pyproject.toml`. --------- Signed-off-by: jirka <jirka.borovec@seznam.cz> Signed-off-by: jirka <6035284+Borda@users.noreply.github.com> Signed-off-by: Soumya Snigdha Kundu <soumya_snigdha.kundu@kcl.ac.uk> Signed-off-by: Eric Kerfoot <17726042+ericspod@users.noreply.github.com> Signed-off-by: Jirka Borovec <6035284+Borda@users.noreply.github.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Soumya Snigdha Kundu <soumyawork15@gmail.com> Co-authored-by: Eric Kerfoot <17726042+ericspod@users.noreply.github.com> Co-authored-by: YunLiu <55491388+KumoLiu@users.noreply.github.com>
1 parent d0b237b commit db9976a

File tree

23 files changed

+51
-118
lines changed

23 files changed

+51
-118
lines changed

CONTRIBUTING.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ Please note that, as per PyTorch, MONAI uses American English spelling. This mea
3737

3838
### Preparing pull requests
3939

40-
To ensure the code quality, MONAI relies on several linting tools ([flake8 and its plugins](https://gitlab.com/pycqa/flake8), [black](https://github.com/psf/black), [isort](https://github.com/timothycrosley/isort), [ruff](https://github.com/astral-sh/ruff)),
40+
To ensure the code quality, MONAI relies on several linting tools ([black](https://github.com/psf/black), [isort](https://github.com/timothycrosley/isort), [ruff](https://github.com/astral-sh/ruff)),
4141
static type analysis tools ([mypy](https://github.com/python/mypy), [pytype](https://github.com/google/pytype)), as well as a set of unit/integration tests.
4242

4343
This section highlights all the necessary preparation steps required before sending a pull request.
@@ -51,7 +51,7 @@ To collaborate efficiently, please read through this section and follow them.
5151

5252
#### Checking the coding style
5353

54-
Coding style is checked and enforced by flake8, black, isort, and ruff, using [a flake8 configuration](./setup.cfg) similar to [PyTorch's](https://github.com/pytorch/pytorch/blob/master/.flake8).
54+
Coding style is checked and enforced by black, isort, and ruff.
5555
Before submitting a pull request, we recommend that all linting should pass, by running the following command locally:
5656

5757
```bash

monai/apps/auto3dseg/bundle_gen.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,7 @@ def _create_cmd(self, train_params: None | dict = None) -> tuple[str, str]:
208208
config_files = []
209209
if os.path.isdir(config_dir):
210210
for file in sorted(os.listdir(config_dir)):
211-
if file.endswith("yaml") or file.endswith("json"):
211+
if file.endswith(("yaml", "json")):
212212
# Python Fire may be confused by single-quoted WindowsPath
213213
config_files.append(Path(os.path.join(config_dir, file)).as_posix())
214214

monai/apps/deepedit/transforms.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -164,8 +164,6 @@ class NormalizeLabelsInDatasetd(RemapLabelsToSequentiald):
164164
which better describes the transform's functionality.
165165
"""
166166

167-
pass
168-
169167

170168
class SingleLabelSelectiond(MapTransform):
171169

monai/apps/detection/transforms/box_ops.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ def flip_boxes(
179179
spatial_dims: int = get_spatial_dims(boxes=boxes)
180180
spatial_size = ensure_tuple_rep(spatial_size, spatial_dims)
181181
if flip_axes is None:
182-
flip_axes = tuple(range(0, spatial_dims))
182+
flip_axes = tuple(range(spatial_dims))
183183
flip_axes = ensure_tuple(flip_axes)
184184

185185
# flip box

monai/auto3dseg/algo_gen.py

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -25,23 +25,18 @@ class Algo:
2525

2626
def set_data_stats(self, *args, **kwargs):
2727
"""Provide dataset (and summaries) so that the model creation can depend on the input datasets."""
28-
pass
2928

3029
def train(self, *args, **kwargs):
3130
"""Read training/validation data and output a model."""
32-
pass
3331

3432
def predict(self, *args, **kwargs):
3533
"""Read test data and output model predictions."""
36-
pass
3734

3835
def get_score(self, *args, **kwargs):
3936
"""Returns the model quality measurement based on training and validation datasets."""
40-
pass
4137

4238
def get_output_path(self, *args, **kwargs):
4339
"""Returns the algo output paths for scripts location"""
44-
pass
4540

4641

4742
class AlgoGen(Randomizable):
@@ -70,31 +65,24 @@ class AlgoGen(Randomizable):
7065

7166
def set_data_stats(self, *args, **kwargs): # type ignore
7267
"""Provide dataset summaries/properties so that the generator can be conditioned on the input datasets."""
73-
pass
7468

7569
def set_budget(self, *args, **kwargs):
7670
"""Provide computational budget so that the generator outputs algorithms that requires reasonable resources."""
77-
pass
7871

7972
def set_score(self, *args, **kwargs):
8073
"""Feedback from the previously generated algo, the score can be used for new Algo generations."""
81-
pass
8274

8375
def get_data_stats(self, *args, **kwargs):
8476
"""Get current dataset summaries."""
85-
pass
8677

8778
def get_budget(self, *args, **kwargs):
8879
"""Get the current computational budget."""
89-
pass
9080

9181
def get_history(self, *args, **kwargs):
9282
"""Get the previously generated algo."""
93-
pass
9483

9584
def generate(self):
9685
"""Generate new Algo -- based on data_stats, budget, and history of previous algo generations."""
97-
pass
9886

9987
def run_algo(self, *args, **kwargs):
10088
"""
@@ -104,4 +92,3 @@ def run_algo(self, *args, **kwargs):
10492
implemented separately is preferred to run them. In this case the controller should also report back the
10593
scores and the algo history, so that the future ``AlgoGen.generate`` can leverage the information.
10694
"""
107-
pass

monai/data/box_utils.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -591,7 +591,7 @@ def convert_box_mode(
591591

592592
# check validity of corners
593593
spatial_dims = get_spatial_dims(boxes=boxes_t)
594-
for axis in range(0, spatial_dims):
594+
for axis in range(spatial_dims):
595595
if (corners[spatial_dims + axis] < corners[axis]).sum() > 0:
596596
warnings.warn("Given boxes has invalid values. The box size must be non-negative.")
597597

@@ -731,7 +731,7 @@ def is_valid_box_values(boxes: NdarrayOrTensor) -> bool:
731731
whether ``boxes`` is valid
732732
"""
733733
spatial_dims = get_spatial_dims(boxes=boxes)
734-
for axis in range(0, spatial_dims):
734+
for axis in range(spatial_dims):
735735
if (boxes[:, spatial_dims + axis] < boxes[:, axis]).sum() > 0:
736736
return False
737737
return True
@@ -1041,7 +1041,7 @@ def spatial_crop_boxes(
10411041

10421042
# makes sure the bounding boxes are within the patch
10431043
spatial_dims = get_spatial_dims(boxes=boxes, spatial_size=roi_end)
1044-
for axis in range(0, spatial_dims):
1044+
for axis in range(spatial_dims):
10451045
boxes_t[:, axis] = boxes_t[:, axis].clamp(min=roi_start_t[axis], max=roi_end_t[axis] - TO_REMOVE)
10461046
boxes_t[:, axis + spatial_dims] = boxes_t[:, axis + spatial_dims].clamp(
10471047
min=roi_start_t[axis], max=roi_end_t[axis] - TO_REMOVE
@@ -1134,7 +1134,7 @@ def non_max_suppression(
11341134

11351135
# initialize the list of picked indexes
11361136
pick = []
1137-
idxs = torch.Tensor(list(range(0, boxes_sort.shape[0]))).to(device=boxes_t.device, dtype=torch.long)
1137+
idxs = torch.Tensor(list(range(boxes_sort.shape[0]))).to(device=boxes_t.device, dtype=torch.long)
11381138

11391139
# keep looping while some indexes still remain in the indexes list
11401140
while len(idxs) > 0:

monai/fl/client/client_algo.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@ def initialize(self, extra: dict | None = None) -> None:
3434
Args:
3535
extra: optional extra information, e.g. dict of `ExtraItems.CLIENT_NAME` and/or `ExtraItems.APP_ROOT`.
3636
"""
37-
pass
3837

3938
def finalize(self, extra: dict | None = None) -> None:
4039
"""
@@ -43,7 +42,6 @@ def finalize(self, extra: dict | None = None) -> None:
4342
Args:
4443
extra: Dict with additional information that can be provided by the FL system.
4544
"""
46-
pass
4745

4846
def abort(self, extra: dict | None = None) -> None:
4947
"""
@@ -53,8 +51,6 @@ def abort(self, extra: dict | None = None) -> None:
5351
extra: Dict with additional information that can be provided by the FL system.
5452
"""
5553

56-
pass
57-
5854

5955
class ClientAlgoStats(BaseClient):
6056

monai/metrics/loss_metric.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,10 @@
1616
import torch
1717
from torch.nn.modules.loss import _Loss
1818

19+
from monai.config import TensorOrList
1920
from monai.metrics.utils import do_metric_reduction
2021
from monai.utils import MetricReduction
2122

22-
from ..config import TensorOrList
2323
from .metric import CumulativeIterationMetric
2424

2525

monai/networks/blocks/feature_pyramid_network.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,6 @@ def forward(self, results: list[Tensor], x: list[Tensor], names: list[str]):
8585
- the extended set of results of the FPN
8686
- the extended set of names for the results
8787
"""
88-
pass
8988

9089

9190
class LastLevelMaxPool(ExtraFPNBlock):

monai/networks/nets/dints.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -627,7 +627,6 @@ def __init__(
627627

628628
def forward(self, x):
629629
"""This function to be implemented by the architecture instances or search spaces."""
630-
pass
631630

632631

633632
class TopologyInstance(TopologyConstruction):

0 commit comments

Comments
 (0)