Skip to content

Commit db8af0e

Browse files
DEV/STYLE: use ruff for linting (#50160)
* Test ruff for linting * further updates * add pre-commit * fixup * restore flake (still needed for validate_docstrings) * hey, all the per-file-ignores can be removed! * Update pandas/tests/io/test_html.py Co-authored-by: Joris Van den Bossche <[email protected]> * remove outdated per-file-ignores * update to .216, set target version * sync version with environment (todo - remove later) * CI didnt start, empty commit to retry? * remove ruff from environment.yml * back to 0.0.215 Co-authored-by: MarcoGorelli <> Co-authored-by: Marco Edward Gorelli <[email protected]>
1 parent 05e9359 commit db8af0e

23 files changed

+135
-349
lines changed

.pre-commit-config.yaml

+4-20
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ default_stages: [
1515
ci:
1616
autofix_prs: false
1717
repos:
18+
- repo: https://github.com/charliermarsh/ruff-pre-commit
19+
rev: v0.0.215
20+
hooks:
21+
- id: ruff
1822
- repo: https://github.com/MarcoGorelli/absolufy-imports
1923
rev: v0.3.1
2024
hooks:
@@ -66,13 +70,6 @@ repos:
6670
--linelength=88,
6771
'--filter=-readability/casting,-runtime/int,-build/include_subdir,-readability/fn_size'
6872
]
69-
- repo: https://github.com/PyCQA/flake8
70-
rev: 6.0.0
71-
hooks:
72-
- id: flake8
73-
additional_dependencies: &flake8_dependencies
74-
- flake8==6.0.0
75-
- flake8-bugbear==22.7.1
7673
- repo: https://github.com/pycqa/pylint
7774
rev: v2.15.9
7875
hooks:
@@ -117,12 +114,6 @@ repos:
117114
rev: v0.6.7
118115
hooks:
119116
- id: sphinx-lint
120-
- repo: https://github.com/asottile/yesqa
121-
rev: v1.4.0
122-
hooks:
123-
- id: yesqa
124-
additional_dependencies: *flake8_dependencies
125-
stages: [manual]
126117
- repo: local
127118
hooks:
128119
# NOTE: we make `black` a local hook because if it's installed from
@@ -326,13 +317,6 @@ repos:
326317
files: ^(environment.yml|requirements-dev.txt)$
327318
pass_filenames: false
328319
additional_dependencies: [pyyaml, toml]
329-
- id: sync-flake8-versions
330-
name: Check flake8 version is synced across flake8, yesqa, and environment.yml
331-
language: python
332-
entry: python scripts/sync_flake8_versions.py
333-
files: ^(\.pre-commit-config\.yaml|environment\.yml)$
334-
pass_filenames: false
335-
additional_dependencies: [pyyaml, toml]
336320
- id: title-capitalization
337321
name: Validate correct capitalization among titles in documentation
338322
entry: python scripts/validate_rst_title_capitalization.py

doc/source/development/contributing_codebase.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ Pre-commit
4343
----------
4444

4545
Additionally, :ref:`Continuous Integration <contributing.ci>` will run code formatting checks
46-
like ``black``, ``flake8``,
46+
like ``black``, ``ruff``,
4747
``isort``, and ``cpplint`` and more using `pre-commit hooks <https://pre-commit.com/>`_
4848
Any warnings from these checks will cause the :ref:`Continuous Integration <contributing.ci>` to fail; therefore,
4949
it is helpful to run the check yourself before submitting code. This

environment.yml

+1-2
Original file line numberDiff line numberDiff line change
@@ -78,12 +78,11 @@ dependencies:
7878
- black=22.10.0
7979
- cpplint
8080
- flake8=6.0.0
81-
- flake8-bugbear=22.7.1 # used by flake8, find likely bugs
8281
- isort>=5.2.1 # check that imports are in the right order
8382
- mypy=0.991
8483
- pre-commit>=2.15.0
85-
- pycodestyle # used by flake8
8684
- pyupgrade
85+
- ruff=0.0.215
8786

8887
# documentation
8988
- gitpython # obtain contributors from git for whatsnew

pandas/core/computation/pytables.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ def stringify(value):
242242
return TermValue(v, v, kind)
243243
elif kind == "bool":
244244
if isinstance(v, str):
245-
v = not v.strip().lower() in [
245+
v = v.strip().lower() not in [
246246
"false",
247247
"f",
248248
"no",

pandas/core/generic.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -10811,7 +10811,7 @@ def _accum_func(
1081110811

1081210812
if axis == 1:
1081310813
return self.T._accum_func(
10814-
name, func, axis=0, skipna=skipna, *args, **kwargs
10814+
name, func, axis=0, skipna=skipna, *args, **kwargs # noqa: B026
1081510815
).T
1081610816

1081710817
def block_accum_func(blk_values):

pandas/core/reshape/merge.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from typing import (
1111
TYPE_CHECKING,
1212
Hashable,
13+
Literal,
1314
Sequence,
1415
cast,
1516
)
@@ -31,7 +32,6 @@
3132
DtypeObj,
3233
IndexLabel,
3334
JoinHow,
34-
Literal,
3535
MergeHow,
3636
Shape,
3737
Suffixes,

pandas/io/formats/latex.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def _split_into_full_short_caption(
5454
return full_caption, short_caption
5555

5656

57-
class RowStringConverter(ABC):
57+
class RowStringConverter:
5858
r"""Converter for dataframe rows into LaTeX strings.
5959
6060
Parameters

pandas/io/formats/style.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2253,7 +2253,7 @@ def set_sticky(
22532253
"props": props + "top:0px; z-index:2;",
22542254
}
22552255
]
2256-
if not self.index.names[0] is None:
2256+
if self.index.names[0] is not None:
22572257
styles[0]["props"] = (
22582258
props + f"top:0px; z-index:2; height:{pixel_size}px;"
22592259
)

pandas/io/parsers/python_parser.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -1017,12 +1017,12 @@ def _rows_to_cols(self, content: list[list[Scalar]]) -> list[np.ndarray]:
10171017
content_len = len(content)
10181018
content = []
10191019

1020-
for (i, l) in iter_content:
1021-
actual_len = len(l)
1020+
for (i, _content) in iter_content:
1021+
actual_len = len(_content)
10221022

10231023
if actual_len > col_len:
10241024
if callable(self.on_bad_lines):
1025-
new_l = self.on_bad_lines(l)
1025+
new_l = self.on_bad_lines(_content)
10261026
if new_l is not None:
10271027
content.append(new_l)
10281028
elif self.on_bad_lines in (
@@ -1035,7 +1035,7 @@ def _rows_to_cols(self, content: list[list[Scalar]]) -> list[np.ndarray]:
10351035
if self.on_bad_lines == self.BadLineHandleMethod.ERROR:
10361036
break
10371037
else:
1038-
content.append(l)
1038+
content.append(_content)
10391039

10401040
for row_num, actual_len in bad_lines:
10411041
msg = (

pandas/plotting/_matplotlib/core.py

+19-2
Original file line numberDiff line numberDiff line change
@@ -455,6 +455,7 @@ def generate(self) -> None:
455455
self._post_plot_logic_common(ax, self.data)
456456
self._post_plot_logic(ax, self.data)
457457

458+
@abstractmethod
458459
def _args_adjust(self) -> None:
459460
pass
460461

@@ -664,6 +665,7 @@ def _post_plot_logic_common(self, ax, data):
664665
else: # pragma no cover
665666
raise ValueError
666667

668+
@abstractmethod
667669
def _post_plot_logic(self, ax, data) -> None:
668670
"""Post process for each axes. Overridden in child classes"""
669671

@@ -1278,6 +1280,9 @@ def _make_plot(self):
12781280
err_kwds["ecolor"] = scatter.get_facecolor()[0]
12791281
ax.errorbar(data[x].values, data[y].values, linestyle="none", **err_kwds)
12801282

1283+
def _args_adjust(self) -> None:
1284+
pass
1285+
12811286

12821287
class HexBinPlot(PlanePlot):
12831288
@property
@@ -1310,6 +1315,9 @@ def _make_plot(self) -> None:
13101315
def _make_legend(self) -> None:
13111316
pass
13121317

1318+
def _args_adjust(self) -> None:
1319+
pass
1320+
13131321

13141322
class LinePlot(MPLPlot):
13151323
_default_rot = 0
@@ -1469,6 +1477,9 @@ def _update_stacker(cls, ax: Axes, stacking_id, values) -> None:
14691477
elif (values <= 0).all():
14701478
ax._stacker_neg_prior[stacking_id] += values
14711479

1480+
def _args_adjust(self) -> None:
1481+
pass
1482+
14721483
def _post_plot_logic(self, ax: Axes, data) -> None:
14731484
from matplotlib.ticker import FixedLocator
14741485

@@ -1573,6 +1584,9 @@ def _plot( # type: ignore[override]
15731584
res = [rect]
15741585
return res
15751586

1587+
def _args_adjust(self) -> None:
1588+
pass
1589+
15761590
def _post_plot_logic(self, ax: Axes, data) -> None:
15771591
LinePlot._post_plot_logic(self, ax, data)
15781592

@@ -1855,5 +1869,8 @@ def blank_labeler(label, value):
18551869

18561870
# leglabels is used for legend labels
18571871
leglabels = labels if labels is not None else idx
1858-
for p, l in zip(patches, leglabels):
1859-
self._append_legend_handles_labels(p, l)
1872+
for _patch, _leglabel in zip(patches, leglabels):
1873+
self._append_legend_handles_labels(_patch, _leglabel)
1874+
1875+
def _post_plot_logic(self, ax: Axes, data) -> None:
1876+
pass

pandas/tests/arithmetic/test_datetime64.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -201,13 +201,13 @@ def test_nat_comparisons(
201201
expected,
202202
):
203203
box = index_or_series
204-
l, r = pair
204+
lhs, rhs = pair
205205
if reverse:
206206
# add lhs / rhs switched data
207-
l, r = r, l
207+
lhs, rhs = rhs, lhs
208208

209-
left = Series(l, dtype=dtype)
210-
right = box(r, dtype=dtype)
209+
left = Series(lhs, dtype=dtype)
210+
right = box(rhs, dtype=dtype)
211211

212212
result = op(left, right)
213213

pandas/tests/frame/test_constructors.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2469,7 +2469,7 @@ def test_dict_nocopy(
24692469
if (
24702470
using_array_manager
24712471
and not copy
2472-
and not (any_numpy_dtype in (tm.STRING_DTYPES + tm.BYTES_DTYPES))
2472+
and any_numpy_dtype not in tm.STRING_DTYPES + tm.BYTES_DTYPES
24732473
):
24742474
# TODO(ArrayManager) properly honor copy keyword for dict input
24752475
td.mark_array_manager_not_yet_implemented(request)

pandas/tests/indexes/period/test_indexing.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -778,8 +778,8 @@ def test_contains_freq_mismatch(self):
778778
rng = period_range("2007-01", freq="M", periods=10)
779779

780780
assert Period("2007-01", freq="M") in rng
781-
assert not Period("2007-01", freq="D") in rng
782-
assert not Period("2007-01", freq="2M") in rng
781+
assert Period("2007-01", freq="D") not in rng
782+
assert Period("2007-01", freq="2M") not in rng
783783

784784
def test_contains_nat(self):
785785
# see gh-13582

pandas/tests/io/formats/test_format.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ def has_horizontally_truncated_repr(df):
134134
return False
135135
# Make sure each row has this ... in the same place
136136
r = repr(df)
137-
for ix, l in enumerate(r.splitlines()):
137+
for ix, _ in enumerate(r.splitlines()):
138138
if not r.split()[cand_col] == "...":
139139
return False
140140
return True

pandas/tests/io/test_html.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -405,10 +405,8 @@ def test_invalid_table_attrs(self, banklist_data):
405405
url, match="First Federal Bank of Florida", attrs={"id": "tasdfable"}
406406
)
407407

408-
def _bank_data(self, path, *args, **kwargs):
409-
return self.read_html(
410-
path, match="Metcalf", attrs={"id": "table"}, *args, **kwargs
411-
)
408+
def _bank_data(self, path, **kwargs):
409+
return self.read_html(path, match="Metcalf", attrs={"id": "table"}, **kwargs)
412410

413411
@pytest.mark.slow
414412
def test_multiindex_header(self, banklist_data):

pandas/tests/plotting/test_datetimelike.py

+13-13
Original file line numberDiff line numberDiff line change
@@ -1021,10 +1021,10 @@ def test_time(self):
10211021
# verify tick labels
10221022
ticks = ax.get_xticks()
10231023
labels = ax.get_xticklabels()
1024-
for t, l in zip(ticks, labels):
1025-
m, s = divmod(int(t), 60)
1024+
for _tick, _label in zip(ticks, labels):
1025+
m, s = divmod(int(_tick), 60)
10261026
h, m = divmod(m, 60)
1027-
rs = l.get_text()
1027+
rs = _label.get_text()
10281028
if len(rs) > 0:
10291029
if s != 0:
10301030
xp = time(h, m, s).strftime("%H:%M:%S")
@@ -1045,10 +1045,10 @@ def test_time_change_xlim(self):
10451045
# verify tick labels
10461046
ticks = ax.get_xticks()
10471047
labels = ax.get_xticklabels()
1048-
for t, l in zip(ticks, labels):
1049-
m, s = divmod(int(t), 60)
1048+
for _tick, _label in zip(ticks, labels):
1049+
m, s = divmod(int(_tick), 60)
10501050
h, m = divmod(m, 60)
1051-
rs = l.get_text()
1051+
rs = _label.get_text()
10521052
if len(rs) > 0:
10531053
if s != 0:
10541054
xp = time(h, m, s).strftime("%H:%M:%S")
@@ -1062,10 +1062,10 @@ def test_time_change_xlim(self):
10621062
# check tick labels again
10631063
ticks = ax.get_xticks()
10641064
labels = ax.get_xticklabels()
1065-
for t, l in zip(ticks, labels):
1066-
m, s = divmod(int(t), 60)
1065+
for _tick, _label in zip(ticks, labels):
1066+
m, s = divmod(int(_tick), 60)
10671067
h, m = divmod(m, 60)
1068-
rs = l.get_text()
1068+
rs = _label.get_text()
10691069
if len(rs) > 0:
10701070
if s != 0:
10711071
xp = time(h, m, s).strftime("%H:%M:%S")
@@ -1086,13 +1086,13 @@ def test_time_musec(self):
10861086
# verify tick labels
10871087
ticks = ax.get_xticks()
10881088
labels = ax.get_xticklabels()
1089-
for t, l in zip(ticks, labels):
1090-
m, s = divmod(int(t), 60)
1089+
for _tick, _label in zip(ticks, labels):
1090+
m, s = divmod(int(_tick), 60)
10911091

1092-
us = round((t - int(t)) * 1e6)
1092+
us = round((_tick - int(_tick)) * 1e6)
10931093

10941094
h, m = divmod(m, 60)
1095-
rs = l.get_text()
1095+
rs = _label.get_text()
10961096
if len(rs) > 0:
10971097
if (us % 1000) != 0:
10981098
xp = time(h, m, s, us).strftime("%H:%M:%S.%f")

pandas/util/_doctools.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -77,9 +77,9 @@ def plot(self, left, right, labels: Iterable[str] = (), vertical: bool = True):
7777
# left
7878
max_left_cols = max(self._shape(df)[1] for df in left)
7979
max_left_rows = max(self._shape(df)[0] for df in left)
80-
for i, (l, label) in enumerate(zip(left, labels)):
80+
for i, (_left, _label) in enumerate(zip(left, labels)):
8181
ax = fig.add_subplot(gs[i, 0:max_left_cols])
82-
self._make_table(ax, l, title=label, height=1.0 / max_left_rows)
82+
self._make_table(ax, _left, title=_label, height=1.0 / max_left_rows)
8383
# right
8484
ax = plt.subplot(gs[:, max_left_cols:])
8585
self._make_table(ax, right, title="Result", height=1.05 / vcells)
@@ -90,10 +90,10 @@ def plot(self, left, right, labels: Iterable[str] = (), vertical: bool = True):
9090
gs = gridspec.GridSpec(1, hcells)
9191
# left
9292
i = 0
93-
for df, label in zip(left, labels):
93+
for df, _label in zip(left, labels):
9494
sp = self._shape(df)
9595
ax = fig.add_subplot(gs[0, i : i + sp[1]])
96-
self._make_table(ax, df, title=label, height=height)
96+
self._make_table(ax, df, title=_label, height=height)
9797
i += sp[1]
9898
# right
9999
ax = plt.subplot(gs[0, i:])

0 commit comments

Comments
 (0)