Skip to content

MNT black → ruff format #31015

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:
command: |
source build_tools/shared.sh
# Include pytest compatibility with mypy
pip install pytest $(get_dep ruff min) $(get_dep mypy min) $(get_dep black min) cython-lint
pip install pytest $(get_dep ruff min) $(get_dep mypy min) cython-lint
- run:
name: linting
command: ./build_tools/linting.sh
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/arm-unit-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ jobs:
run: |
source build_tools/shared.sh
# Include pytest compatibility with mypy
pip install pytest $(get_dep ruff min) $(get_dep mypy min) $(get_dep black min) cython-lint
pip install pytest $(get_dep ruff min) $(get_dep mypy min) cython-lint
- name: Run linters
run: ./build_tools/linting.sh
- name: Run Meson OpenMP checks
Expand Down
3 changes: 1 addition & 2 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,10 @@ jobs:
curl https://raw.githubusercontent.com/${{ github.repository }}/main/build_tools/shared.sh --retry 5 -o ./build_tools/shared.sh
source build_tools/shared.sh
# Include pytest compatibility with mypy
pip install pytest $(get_dep ruff min) $(get_dep mypy min) $(get_dep black min) cython-lint
pip install pytest $(get_dep ruff min) $(get_dep mypy min)
# we save the versions of the linters to be used in the error message later.
python -c "from importlib.metadata import version; print(f\"ruff={version('ruff')}\")" >> /tmp/versions.txt
python -c "from importlib.metadata import version; print(f\"mypy={version('mypy')}\")" >> /tmp/versions.txt
python -c "from importlib.metadata import version; print(f\"black={version('black')}\")" >> /tmp/versions.txt
python -c "from importlib.metadata import version; print(f\"cython-lint={version('cython-lint')}\")" >> /tmp/versions.txt

- name: Run linting
Expand Down
7 changes: 2 additions & 5 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,11 @@ repos:
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.11.0
rev: v0.11.2
hooks:
- id: ruff
args: ["--fix", "--output-format=full"]
- repo: https://github.com/psf/black
rev: 24.3.0
hooks:
- id: black
- id: ruff-format
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.15.0
hooks:
Expand Down
8 changes: 4 additions & 4 deletions README.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
.. -*- mode: rst -*-

|Azure| |Codecov| |CircleCI| |Nightly wheels| |Black| |PythonVersion| |PyPi| |DOI| |Benchmark|
|Azure| |Codecov| |CircleCI| |Nightly wheels| |Ruff| |PythonVersion| |PyPi| |DOI| |Benchmark|

.. |Azure| image:: https://dev.azure.com/scikit-learn/scikit-learn/_apis/build/status/scikit-learn.scikit-learn?branchName=main
:target: https://dev.azure.com/scikit-learn/scikit-learn/_build/latest?definitionId=1&branchName=main
Expand All @@ -14,15 +14,15 @@
.. |Nightly wheels| image:: https://github.com/scikit-learn/scikit-learn/workflows/Wheel%20builder/badge.svg?event=schedule
:target: https://github.com/scikit-learn/scikit-learn/actions?query=workflow%3A%22Wheel+builder%22+event%3Aschedule

.. |Ruff| image:: https://img.shields.io/badge/code%20style-ruff-000000.svg
:target: https://github.com/astral-sh/ruff

.. |PythonVersion| image:: https://img.shields.io/pypi/pyversions/scikit-learn.svg
:target: https://pypi.org/project/scikit-learn/

.. |PyPi| image:: https://img.shields.io/pypi/v/scikit-learn
:target: https://pypi.org/project/scikit-learn

.. |Black| image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/psf/black

.. |DOI| image:: https://zenodo.org/badge/21369/scikit-learn/scikit-learn.svg
:target: https://zenodo.org/badge/latestdoi/21369/scikit-learn/scikit-learn

Expand Down
2 changes: 1 addition & 1 deletion azure-pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ jobs:
- bash: |
source build_tools/shared.sh
# Include pytest compatibility with mypy
pip install pytest $(get_dep ruff min) $(get_dep mypy min) $(get_dep black min) cython-lint
pip install pytest $(get_dep ruff min) $(get_dep mypy min) cython-lint
displayName: Install linters
- bash: |
./build_tools/linting.sh
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/bench_hist_gradient_boosting_adult.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def predict(est, data_test, target_test):
toc = time()
roc_auc = roc_auc_score(target_test, predicted_proba_test[:, 1])
acc = accuracy_score(target_test, predicted_test)
print(f"predicted in {toc - tic:.3f}s, ROC AUC: {roc_auc:.4f}, ACC: {acc :.4f}")
print(f"predicted in {toc - tic:.3f}s, ROC AUC: {roc_auc:.4f}, ACC: {acc:.4f}")


data = fetch_openml(data_id=179, as_frame=True) # adult dataset
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/bench_hist_gradient_boosting_higgsboson.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def predict(est, data_test, target_test):
toc = time()
roc_auc = roc_auc_score(target_test, predicted_proba_test[:, 1])
acc = accuracy_score(target_test, predicted_test)
print(f"predicted in {toc - tic:.3f}s, ROC AUC: {roc_auc:.4f}, ACC: {acc :.4f}")
print(f"predicted in {toc - tic:.3f}s, ROC AUC: {roc_auc:.4f}, ACC: {acc:.4f}")


df = load_data()
Expand Down
42 changes: 19 additions & 23 deletions build_tools/get_comment.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,7 @@ def get_step_message(log, start, end, title, message, details):
if end not in log:
return ""
res = (
"-----------------------------------------------\n"
f"### {title}\n\n"
f"{message}\n\n"
f"-----------------------------------------------\n### {title}\n\n{message}\n\n"
)
if details:
res += (
Expand Down Expand Up @@ -92,33 +90,31 @@ def get_message(log_file, repo, pr_number, sha, run_id, details, versions):

message = ""

# black
# ruff check
message += get_step_message(
log,
start="### Running black ###",
end="Problems detected by black",
title="`black`",
start="### Running the ruff linter ###",
end="Problems detected by ruff check",
title="`ruff check`",
message=(
"`black` detected issues. Please run `black .` locally and push "
"the changes. Here you can see the detected issues. Note that "
"running black might also fix some of the issues which might be "
"detected by `ruff`. Note that the installed `black` version is "
f"`black={versions['black']}`."
"`ruff` detected issues. Please run "
"`ruff check --fix --output-format=full` locally, fix the remaining "
"issues, and push the changes. Here you can see the detected issues. Note "
f"that the installed `ruff` version is `ruff={versions['ruff']}`."
),
details=details,
)

# ruff
# ruff format
message += get_step_message(
log,
start="### Running ruff ###",
end="Problems detected by ruff",
title="`ruff`",
start="### Running the ruff formatter ###",
end="Problems detected by ruff format",
title="`ruff format`",
message=(
"`ruff` detected issues. Please run "
"`ruff check --fix --output-format=full` locally, fix the remaining "
"issues, and push the changes. Here you can see the detected issues. Note "
f"that the installed `ruff` version is `ruff={versions['ruff']}`."
"`ruff` detected issues. Please run `ruff format` locally and push "
"the changes. Here you can see the detected issues. Note that the "
f"installed `ruff` version is `ruff={versions['ruff']}`."
),
details=details,
)
Expand Down Expand Up @@ -239,7 +235,7 @@ def get_headers(token):
def find_lint_bot_comments(repo, token, pr_number):
"""Get the comment from the linting bot."""
# repo is in the form of "org/repo"
# API doc: https://docs.github.com/en/rest/issues/comments?apiVersion=2022-11-28#list-issue-comments # noqa
# API doc: https://docs.github.com/en/rest/issues/comments?apiVersion=2022-11-28#list-issue-comments
response = requests.get(
f"https://api.github.com/repos/{repo}/issues/{pr_number}/comments",
headers=get_headers(token),
Expand Down Expand Up @@ -274,15 +270,15 @@ def create_or_update_comment(comment, message, repo, pr_number, token):
# repo is in the form of "org/repo"
if comment is not None:
print("updating existing comment")
# API doc: https://docs.github.com/en/rest/issues/comments?apiVersion=2022-11-28#update-an-issue-comment # noqa
# API doc: https://docs.github.com/en/rest/issues/comments?apiVersion=2022-11-28#update-an-issue-comment
response = requests.patch(
f"https://api.github.com/repos/{repo}/issues/comments/{comment['id']}",
headers=get_headers(token),
json={"body": message},
)
else:
print("creating new comment")
# API doc: https://docs.github.com/en/rest/issues/comments?apiVersion=2022-11-28#create-an-issue-comment # noqa
# API doc: https://docs.github.com/en/rest/issues/comments?apiVersion=2022-11-28#create-an-issue-comment
response = requests.post(
f"https://api.github.com/repos/{repo}/issues/{pr_number}/comments",
headers=get_headers(token),
Expand Down
17 changes: 8 additions & 9 deletions build_tools/linting.sh
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,25 @@ set -o pipefail

global_status=0

echo -e "### Running black ###\n"
black --check --diff .
echo -e "### Running the ruff linter ###\n"
ruff check --output-format=full
status=$?

if [[ $status -eq 0 ]]
then
echo -e "No problem detected by black\n"
echo -e "No problem detected by the ruff linter\n"
else
echo -e "Problems detected by black, please run black and commit the result\n"
echo -e "Problems detected by ruff check, please fix them\n"
global_status=1
fi

echo -e "### Running ruff ###\n"
ruff check --output-format=full
echo -e "### Running the ruff formatter ###\n"
ruff format --diff
status=$?
if [[ $status -eq 0 ]]
then
echo -e "No problem detected by ruff\n"
echo -e "No problem detected by the ruff formatter\n"
else
echo -e "Problems detected by ruff, please fix them\n"
echo -e "Problems detected by ruff format, please run ruff format and commit the result\n"
global_status=1
fi

Expand Down
4 changes: 2 additions & 2 deletions doc/developers/contributing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ how to set up your git repository:

.. prompt:: bash

pip install pytest pytest-cov ruff mypy numpydoc black==24.3.0
pip install pytest pytest-cov ruff==0.11.2 mypy numpydoc

.. _upstream:

Expand Down Expand Up @@ -1565,7 +1565,7 @@ make this task easier and faster (in no particular order).
variable) in the code base.

- Configure `git blame` to ignore the commit that migrated the code style to
`black`.
`black` and then `ruff`.

.. prompt:: bash

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def create_species_bunch(species_name, train, test, coverages, xgrid, ygrid):


def plot_species_distribution(
species=("bradypus_variegatus_0", "microryzomys_minutus_0")
species=("bradypus_variegatus_0", "microryzomys_minutus_0"),
):
"""
Plot the species distribution.
Expand Down
2 changes: 1 addition & 1 deletion examples/applications/plot_time_series_lagged_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ def consolidate_scores(cv_results, scores, metric):
time = cv_results["fit_time"]
scores["fit_time"].append(f"{time.mean():.2f} ± {time.std():.2f} s")

scores["loss"].append(f"quantile {int(quantile*100)}")
scores["loss"].append(f"quantile {int(quantile * 100)}")
for key, value in cv_results.items():
if key.startswith("test_"):
metric = key.split("test_")[1]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def plot_top_words(model, feature_names, n_top_words, title):

ax = axes[topic_idx]
ax.barh(top_features, weights, height=0.7)
ax.set_title(f"Topic {topic_idx +1}", fontdict={"fontsize": 30})
ax.set_title(f"Topic {topic_idx + 1}", fontdict={"fontsize": 30})
ax.tick_params(axis="both", which="major", labelsize=20)
for i in "top right left".split():
ax.spines[i].set_visible(False)
Expand Down
2 changes: 1 addition & 1 deletion examples/covariance/plot_mahalanobis_distances.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
Proceedings of the National Academy of Sciences of the United States
of America, 17, 684-688.

""" # noqa: E501
"""

# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
Expand Down
4 changes: 2 additions & 2 deletions examples/ensemble/plot_bias_variance.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,8 @@ def generate(n_samples, noise, n_repeat=1):

plt.subplot(2, n_estimators, n_estimators + n + 1)
plt.plot(X_test, y_error, "r", label="$error(x)$")
plt.plot(X_test, y_bias, "b", label="$bias^2(x)$"),
plt.plot(X_test, y_var, "g", label="$variance(x)$"),
plt.plot(X_test, y_bias, "b", label="$bias^2(x)$")
plt.plot(X_test, y_var, "g", label="$variance(x)$")
plt.plot(X_test, y_noise, "c", label="$noise(x)$")

plt.xlim([-5, 5])
Expand Down
2 changes: 1 addition & 1 deletion examples/feature_selection/plot_rfe_digits.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

See also :ref:`sphx_glr_auto_examples_feature_selection_plot_rfe_with_cross_validation.py`

""" # noqa: E501
"""

# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
# were already standardized.
# For a more complete example on the interpretations of the coefficients of
# linear models, you may refer to
# :ref:`sphx_glr_auto_examples_inspection_plot_linear_model_coefficient_interpretation.py`. # noqa: E501
# :ref:`sphx_glr_auto_examples_inspection_plot_linear_model_coefficient_interpretation.py`.
import matplotlib.pyplot as plt
import numpy as np

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -606,8 +606,9 @@ def score_estimator(
"predicted, frequency*severity model": np.sum(
exposure * glm_freq.predict(X) * glm_sev.predict(X)
),
"predicted, tweedie, power=%.2f"
% glm_pure_premium.power: np.sum(exposure * glm_pure_premium.predict(X)),
"predicted, tweedie, power=%.2f" % glm_pure_premium.power: np.sum(
exposure * glm_pure_premium.predict(X)
),
}
)

Expand Down
1 change: 0 additions & 1 deletion examples/manifold/plot_lle_digits.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause


# %%
# Load digits dataset
# -------------------
Expand Down
2 changes: 1 addition & 1 deletion examples/manifold/plot_manifold_sphere.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
t = random_state.rand(n_samples) * np.pi

# Sever the poles from the sphere.
indices = (t < (np.pi - (np.pi / 8))) & (t > ((np.pi / 8)))
indices = (t < (np.pi - (np.pi / 8))) & (t > (np.pi / 8))
colors = p[indices]
x, y, z = (
np.sin(t[indices]) * np.cos(p[indices]),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

See also :ref:`sphx_glr_auto_examples_miscellaneous_plot_roc_curve_visualization_api.py`

""" # noqa: E501
"""

# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
Expand Down
2 changes: 1 addition & 1 deletion examples/model_selection/plot_likelihood_ratios.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class proportion than the target application.
from sklearn.datasets import make_classification

X, y = make_classification(n_samples=10_000, weights=[0.9, 0.1], random_state=0)
print(f"Percentage of people carrying the disease: {100*y.mean():.2f}%")
print(f"Percentage of people carrying the disease: {100 * y.mean():.2f}%")

# %%
# A machine learning model is built to diagnose if a person with some given
Expand Down
6 changes: 3 additions & 3 deletions examples/model_selection/plot_roc.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,9 +152,9 @@
#
# We can briefly demo the effect of :func:`numpy.ravel`:

print(f"y_score:\n{y_score[0:2,:]}")
print(f"y_score:\n{y_score[0:2, :]}")
print()
print(f"y_score.ravel():\n{y_score[0:2,:].ravel()}")
print(f"y_score.ravel():\n{y_score[0:2, :].ravel()}")

# %%
# In a multi-class classification setup with highly imbalanced classes,
Expand Down Expand Up @@ -359,7 +359,7 @@
plt.plot(
fpr_grid,
mean_tpr[ix],
label=f"Mean {label_a} vs {label_b} (AUC = {mean_score :.2f})",
label=f"Mean {label_a} vs {label_b} (AUC = {mean_score:.2f})",
linestyle=":",
linewidth=4,
)
Expand Down
2 changes: 1 addition & 1 deletion examples/text/plot_document_classification_20newsgroups.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,7 @@ def benchmark(clf, custom_name=False):
# Notice that the most important hyperparameters values were tuned using a grid
# search procedure not shown in this notebook for the sake of simplicity. See
# the example script
# :ref:`sphx_glr_auto_examples_model_selection_plot_grid_search_text_feature_extraction.py` # noqa: E501
# :ref:`sphx_glr_auto_examples_model_selection_plot_grid_search_text_feature_extraction.py`
# for a demo on how such tuning can be done.

from sklearn.ensemble import RandomForestClassifier
Expand Down
2 changes: 1 addition & 1 deletion maint_tools/bump-dependencies-versions.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def get_min_version_with_wheel(package_name, python_version):
for file_info in release_info:
if (
file_info["packagetype"] == "bdist_wheel"
and f'cp{python_version.replace(".", "")}' in file_info["filename"]
and f"cp{python_version.replace('.', '')}" in file_info["filename"]
and not file_info["yanked"]
):
compatible_versions.append(ver)
Expand Down
Loading
Loading