Skip to content

STY: Enable some passing rules #57200

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 11 commits into from
Feb 2, 2024
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
6 changes: 2 additions & 4 deletions pandas/_libs/tslibs/vectorized.pyi
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
"""
For cython types that cannot be represented precisely, closest-available
python equivalents are used, and the precise types kept as adjacent comments.
"""
# For cython types that cannot be represented precisely, closest-available
# python equivalents are used, and the precise types kept as adjacent comments.
from datetime import tzinfo

import numpy as np
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/indexers/objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -399,7 +399,7 @@ def get_window_bounds(
start_arrays = []
end_arrays = []
window_indices_start = 0
for key, indices in self.groupby_indices.items():
for indices in self.groupby_indices.values():
index_array: np.ndarray | None

if self.index_array is not None:
Expand Down
2 changes: 1 addition & 1 deletion pandas/io/formats/style_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -1996,7 +1996,7 @@ class Tooltips:

def __init__(
self,
css_props: CSSProperties = [
css_props: CSSProperties = [ # noqa: B006
("visibility", "hidden"),
("position", "absolute"),
("z-index", 1),
Expand Down
4 changes: 2 additions & 2 deletions pandas/io/json/_normalize.py
Original file line number Diff line number Diff line change
Expand Up @@ -537,8 +537,8 @@ def _recursive_extract(data, path, seen_meta, level: int = 0) -> None:
if values.ndim > 1:
# GH 37782
values = np.empty((len(v),), dtype=object)
for i, v in enumerate(v):
values[i] = v
for i, val in enumerate(v):
values[i] = val

result[k] = values.repeat(lengths)
return result
12 changes: 6 additions & 6 deletions pandas/tests/arrays/masked/test_arithmetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,15 @@ def test_array_scalar_like_equivalence(data, all_arithmetic_operators):
scalar_array = pd.array([scalar] * len(data), dtype=data.dtype)

# TODO also add len-1 array (np.array([scalar], dtype=data.dtype.numpy_dtype))
for scalar in [scalar, data.dtype.type(scalar)]:
for val in [scalar, data.dtype.type(scalar)]:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What rule is this?

Not sure I like this change (or if its worth the churn).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://docs.astral.sh/ruff/rules/loop-variable-overrides-iterator/

I think this could be useful generally. In the file above (pandas/io/json/_normalize.py), if v needed to be used after looping it would no longer be the original object it would be an object element

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My bad, wasn't paying too close attention.

I guess a more descriptive name would be nicer, but I'm fine with it as it is.

if is_bool_not_implemented(data, all_arithmetic_operators):
msg = "operator '.*' not implemented for bool dtypes"
with pytest.raises(NotImplementedError, match=msg):
op(data, scalar)
op(data, val)
with pytest.raises(NotImplementedError, match=msg):
op(data, scalar_array)
else:
result = op(data, scalar)
result = op(data, val)
expected = op(data, scalar_array)
tm.assert_extension_array_equal(result, expected)

Expand Down Expand Up @@ -214,13 +214,13 @@ def test_error_len_mismatch(data, all_arithmetic_operators):
msg = "operator '.*' not implemented for bool dtypes"
err = NotImplementedError

for other in [other, np.array(other)]:
for val in [other, np.array(other)]:
with pytest.raises(err, match=msg):
op(data, other)
op(data, val)

s = pd.Series(data)
with pytest.raises(err, match=msg):
op(s, other)
op(s, val)


@pytest.mark.parametrize("op", ["__neg__", "__abs__", "__invert__"])
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/copy_view/index/test_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from pandas.tests.copy_view.util import get_array


def index_view(index_data=[1, 2]):
def index_view(index_data):
df = DataFrame({"a": index_data, "b": 1.5})
view = df[:]
df = df.set_index("a", drop=True)
Expand Down Expand Up @@ -142,7 +142,7 @@ def test_index_from_index(using_copy_on_write, warn_copy_on_write):
],
)
def test_index_ops(using_copy_on_write, func, request):
idx, view_ = index_view()
idx, view_ = index_view([1, 2])
expected = idx.copy(deep=True)
if "astype" in request.node.callspec.id:
expected = expected.astype("Int64")
Expand Down
8 changes: 4 additions & 4 deletions pandas/tests/frame/test_query_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -949,8 +949,8 @@ def test_str_query_method(self, parser, engine):
ops = 2 * ([eq] + [ne])
msg = r"'(Not)?In' nodes are not implemented"

for lhs, op, rhs in zip(lhs, ops, rhs):
ex = f"{lhs} {op} {rhs}"
for lh, op_, rh in zip(lhs, ops, rhs):
ex = f"{lh} {op_} {rh}"
with pytest.raises(NotImplementedError, match=msg):
df.query(
ex,
Expand Down Expand Up @@ -990,8 +990,8 @@ def test_str_list_query_method(self, parser, engine):
ops = 2 * ([eq] + [ne])
msg = r"'(Not)?In' nodes are not implemented"

for lhs, op, rhs in zip(lhs, ops, rhs):
ex = f"{lhs} {op} {rhs}"
for lh, ops_, rh in zip(lhs, ops, rhs):
ex = f"{lh} {ops_} {rh}"
with pytest.raises(NotImplementedError, match=msg):
df.query(ex, engine=engine, parser=parser)
else:
Expand Down
4 changes: 3 additions & 1 deletion pandas/tests/io/test_feather.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@ def check_external_error_on_write(self, df):
with tm.ensure_clean() as path:
to_feather(df, path)

def check_round_trip(self, df, expected=None, write_kwargs={}, **read_kwargs):
def check_round_trip(self, df, expected=None, write_kwargs=None, **read_kwargs):
if write_kwargs is None:
write_kwargs = {}
if expected is None:
expected = df.copy()

Expand Down
4 changes: 3 additions & 1 deletion pandas/tests/plotting/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -433,7 +433,7 @@ def _check_box_return_type(
raise AssertionError


def _check_grid_settings(obj, kinds, kws={}):
def _check_grid_settings(obj, kinds, kws=None):
# Make sure plot defaults to rcParams['axes.grid'] setting, GH 9792

import matplotlib as mpl
Expand All @@ -446,6 +446,8 @@ def is_grid_on():

return not (xoff and yoff)

if kws is None:
kws = {}
spndx = 1
for kind in kinds:
mpl.pyplot.subplot(1, 4 * len(kinds), spndx)
Expand Down
8 changes: 6 additions & 2 deletions pandas/tests/reshape/test_pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -890,10 +890,14 @@ def _check_output(
result,
values_col,
data,
index=["A", "B"],
columns=["C"],
index=None,
columns=None,
margins_col="All",
):
if index is None:
index = ["A", "B"]
if columns is None:
columns = ["C"]
col_margins = result.loc[result.index[:-1], margins_col]
expected_col_margins = data.groupby(index)[values_col].mean()
tm.assert_series_equal(col_margins, expected_col_margins, check_names=False)
Expand Down
8 changes: 4 additions & 4 deletions pandas/tests/window/test_expanding.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,9 +178,9 @@ def test_expanding_count_with_min_periods_exceeding_series_length(frame_or_serie
def test_iter_expanding_dataframe(df, expected, min_periods):
# GH 11704
df = DataFrame(df)
expected = [DataFrame(values, index=index) for (values, index) in expected]
expecteds = [DataFrame(values, index=index) for (values, index) in expected]

for expected, actual in zip(expected, df.expanding(min_periods)):
for expected, actual in zip(expecteds, df.expanding(min_periods)):
tm.assert_frame_equal(actual, expected)


Expand All @@ -197,9 +197,9 @@ def test_iter_expanding_dataframe(df, expected, min_periods):
)
def test_iter_expanding_series(ser, expected, min_periods):
# GH 11704
expected = [Series(values, index=index) for (values, index) in expected]
expecteds = [Series(values, index=index) for (values, index) in expected]

for expected, actual in zip(expected, ser.expanding(min_periods)):
for expected, actual in zip(expecteds, ser.expanding(min_periods)):
tm.assert_series_equal(actual, expected)


Expand Down
18 changes: 10 additions & 8 deletions pandas/tests/window/test_rolling.py
Original file line number Diff line number Diff line change
Expand Up @@ -760,9 +760,9 @@ def test_rolling_count_default_min_periods_with_null_values(frame_or_series):
def test_iter_rolling_dataframe(df, expected, window, min_periods):
# GH 11704
df = DataFrame(df)
expected = [DataFrame(values, index=index) for (values, index) in expected]
expecteds = [DataFrame(values, index=index) for (values, index) in expected]

for expected, actual in zip(expected, df.rolling(window, min_periods=min_periods)):
for expected, actual in zip(expecteds, df.rolling(window, min_periods=min_periods)):
tm.assert_frame_equal(actual, expected)


Expand Down Expand Up @@ -805,10 +805,10 @@ def test_iter_rolling_on_dataframe(expected, window):
}
)

expected = [
expecteds = [
DataFrame(values, index=df.loc[index, "C"]) for (values, index) in expected
]
for expected, actual in zip(expected, df.rolling(window, on="C")):
for expected, actual in zip(expecteds, df.rolling(window, on="C")):
tm.assert_frame_equal(actual, expected)


Expand Down Expand Up @@ -856,9 +856,11 @@ def test_iter_rolling_on_dataframe_unordered():
)
def test_iter_rolling_series(ser, expected, window, min_periods):
# GH 11704
expected = [Series(values, index=index) for (values, index) in expected]
expecteds = [Series(values, index=index) for (values, index) in expected]

for expected, actual in zip(expected, ser.rolling(window, min_periods=min_periods)):
for expected, actual in zip(
expecteds, ser.rolling(window, min_periods=min_periods)
):
tm.assert_series_equal(actual, expected)


Expand Down Expand Up @@ -904,11 +906,11 @@ def test_iter_rolling_datetime(expected, expected_index, window):
# GH 11704
ser = Series(range(5), index=date_range(start="2020-01-01", periods=5, freq="D"))

expected = [
expecteds = [
Series(values, index=idx) for (values, idx) in zip(expected, expected_index)
]

for expected, actual in zip(expected, ser.rolling(window)):
for expected, actual in zip(expecteds, ser.rolling(window)):
tm.assert_series_equal(actual, expected)


Expand Down
18 changes: 0 additions & 18 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -249,12 +249,6 @@ ignore = [
"E402",
# do not assign a lambda expression, use a def
"E731",
# line break before binary operator
# "W503", # not yet implemented
# line break after binary operator
# "W504", # not yet implemented
# controversial
"B006",
# controversial
"B007",
# controversial
Expand All @@ -263,18 +257,10 @@ ignore = [
"B009",
# getattr is used to side-step mypy
"B010",
# tests use assert False
"B011",
# tests use comparisons but not their returned value
"B015",
# false positives
"B019",
# Loop control variable overrides iterable it iterates
"B020",
# Function definition does not bind loop variable
"B023",
# Functions defined inside a loop must not use variables redefined in the loop
# "B301", # not yet implemented
# Only works with python >=3.10
"B905",
# Too many arguments to function call
Expand All @@ -289,14 +275,10 @@ ignore = [
"PLW2901",
# Global statements are discouraged
"PLW0603",
# Docstrings should not be included in stubs
"PYI021",
# Use `typing.NamedTuple` instead of `collections.namedtuple`
"PYI024",
# No builtin `eval()` allowed
"PGH001",
# compare-to-empty-string
"PLC1901",
# while int | float can be shortened to float, the former is more explicit
"PYI041",
# incorrect-dict-iterator, flags valid Series.items usage
Expand Down