Skip to content

Commit a8de733

Browse files
DimitriPapadopoulosIllviljanpre-commit-ci[bot]
authored
Enforce ruff/flake8-simplify rules (SIM) (#10480)
* Apply ruff/flake8-simplify rule SIM102 SIM102 Use a single `if` statement instead of nested `if` statements * Apply ruff/flake8-simplify rule SIM113 SIM113 Use `enumerate()` for index variable in `for` loop * Apply ruff/flake8-simplify rule SIM114 SIM114 Combine `if` branches using logical `or` operator * Apply ruff/flake8-simplify rule SIM201 SIM201 Use `... != ...` instead of `not ... == ..."` * Apply ruff/flake8-simplify rule SIM905 SIM905 Consider using a list literal instead of `str.split` * Apply ruff/flake8-simplify rule SIM910 SIM910 Use `.get(...)` instead of `.get(..., None)` * Enforce ruff/flake8-simplify rules (SIM) * Move comment near the related code Co-authored-by: Illviljan <14371165+Illviljan@users.noreply.github.com> * Ignore SIM102 as well SIM102 Use a single `if` statement instead of nested `if` statements * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: Illviljan <14371165+Illviljan@users.noreply.github.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent f33ee6c commit a8de733

File tree

13 files changed

+43
-44
lines changed

13 files changed

+43
-44
lines changed

pyproject.toml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,7 @@ extend-select = [
262262
"PIE", # flake8-pie
263263
"TID", # flake8-tidy-imports (absolute imports)
264264
"PYI", # flake8-pyi
265+
"SIM", # flake8-simplify
265266
"FLY", # flynt
266267
"I", # isort
267268
"PERF", # Perflint
@@ -283,6 +284,11 @@ ignore = [
283284
"PIE790", # unnecessary pass statement
284285
"PYI019", # use `Self` instead of custom TypeVar
285286
"PYI041", # use `float` instead of `int | float`
287+
"SIM102", # use a single `if` statement instead of nested `if` statements
288+
"SIM108", # use ternary operator instead of `if`-`else`-block
289+
"SIM117", # use a single `with` statement instead of nested `with` statements
290+
"SIM118", # use `key in dict` instead of `key in dict.keys()`
291+
"SIM300", # yoda condition detected
286292
"PERF203", # try-except within a loop incurs performance overhead
287293
"E402", # module level import not at top of file
288294
"E731", # do not assign a lambda expression, use a def

xarray/core/formatting.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -989,9 +989,10 @@ def diff_array_repr(a, b, compat):
989989
):
990990
summary.append(coords_diff)
991991

992-
if compat == "identical":
993-
if attrs_diff := diff_attrs_repr(a.attrs, b.attrs, compat):
994-
summary.append(attrs_diff)
992+
if compat == "identical" and (
993+
attrs_diff := diff_attrs_repr(a.attrs, b.attrs, compat)
994+
):
995+
summary.append(attrs_diff)
995996

996997
return "\n".join(summary)
997998

@@ -1029,9 +1030,10 @@ def diff_dataset_repr(a, b, compat):
10291030
):
10301031
summary.append(data_diff)
10311032

1032-
if compat == "identical":
1033-
if attrs_diff := diff_attrs_repr(a.attrs, b.attrs, compat):
1034-
summary.append(attrs_diff)
1033+
if compat == "identical" and (
1034+
attrs_diff := diff_attrs_repr(a.attrs, b.attrs, compat)
1035+
):
1036+
summary.append(attrs_diff)
10351037

10361038
return "\n".join(summary)
10371039

xarray/core/indexes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1247,7 +1247,7 @@ def create_variables(
12471247
level = name
12481248
dtype = self.level_coords_dtype[name] # type: ignore[index] # TODO: are Hashables ok?
12491249

1250-
var = variables.get(name, None)
1250+
var = variables.get(name)
12511251
if var is not None:
12521252
attrs = var.attrs
12531253
encoding = var.encoding

xarray/core/resample_cftime.py

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -84,22 +84,16 @@ def __init__(
8484
self.freq = to_offset(freq)
8585
self.origin = origin
8686

87-
if isinstance(self.freq, MonthEnd | QuarterEnd | YearEnd):
88-
if closed is None:
89-
self.closed = "right"
90-
else:
91-
self.closed = closed
92-
if label is None:
93-
self.label = "right"
94-
else:
95-
self.label = label
96-
# The backward resample sets ``closed`` to ``'right'`` by default
97-
# since the last value should be considered as the edge point for
98-
# the last bin. When origin in "end" or "end_day", the value for a
99-
# specific ``cftime.datetime`` index stands for the resample result
100-
# from the current ``cftime.datetime`` minus ``freq`` to the current
101-
# ``cftime.datetime`` with a right close.
102-
elif self.origin in ["end", "end_day"]:
87+
if isinstance(self.freq, MonthEnd | QuarterEnd | YearEnd) or self.origin in [
88+
"end",
89+
"end_day",
90+
]:
91+
# The backward resample sets ``closed`` to ``'right'`` by default
92+
# since the last value should be considered as the edge point for
93+
# the last bin. When origin in "end" or "end_day", the value for a
94+
# specific ``cftime.datetime`` index stands for the resample result
95+
# from the current ``cftime.datetime`` minus ``freq`` to the current
96+
# ``cftime.datetime`` with a right close.
10397
if closed is None:
10498
self.closed = "right"
10599
else:

xarray/groupers.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -701,25 +701,23 @@ def find_independent_seasons(seasons: Sequence[str]) -> Sequence[SeasonsGroup]:
701701
grouped = defaultdict(list)
702702
codes = defaultdict(list)
703703
seen: set[tuple[int, ...]] = set()
704-
idx = 0
705704
# This is quadratic, but the number of seasons is at most 12
706705
for i, current in enumerate(season_inds):
707706
# Start with a group
708707
if current not in seen:
709-
grouped[idx].append(current)
710-
codes[idx].append(i)
708+
grouped[i].append(current)
709+
codes[i].append(i)
711710
seen.add(current)
712711

713712
# Loop through remaining groups, and look for overlaps
714713
for j, second in enumerate(season_inds[i:]):
715-
if not (set(chain(*grouped[idx])) & set(second)) and second not in seen:
716-
grouped[idx].append(second)
717-
codes[idx].append(j + i)
714+
if not (set(chain(*grouped[i])) & set(second)) and second not in seen:
715+
grouped[i].append(second)
716+
codes[i].append(j + i)
718717
seen.add(second)
719718
if len(seen) == len(seasons):
720719
break
721-
# found all non-overlapping groups for this row, increment and start over
722-
idx += 1
720+
# found all non-overlapping groups for this row start over
723721

724722
grouped_ints = tuple(tuple(idx) for idx in grouped.values() if idx)
725723
return [

xarray/plot/facetgrid.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -549,7 +549,7 @@ def map_plot1d(
549549
)
550550

551551
if add_legend:
552-
use_legend_elements = not func.__name__ == "hist"
552+
use_legend_elements = func.__name__ != "hist"
553553
if use_legend_elements:
554554
self.add_legend(
555555
use_legend_elements=use_legend_elements,

xarray/plot/utils.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -419,9 +419,10 @@ def _infer_xy_labels(
419419
_assert_valid_xy(darray, x, "x")
420420
_assert_valid_xy(darray, y, "y")
421421

422-
if darray._indexes.get(x, 1) is darray._indexes.get(y, 2):
423-
if isinstance(darray._indexes[x], PandasMultiIndex):
424-
raise ValueError("x and y cannot be levels of the same MultiIndex")
422+
if darray._indexes.get(x, 1) is darray._indexes.get(y, 2) and isinstance(
423+
darray._indexes[x], PandasMultiIndex
424+
):
425+
raise ValueError("x and y cannot be levels of the same MultiIndex")
425426

426427
return x, y
427428

xarray/structure/merge.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,7 @@ def merge_collected(
300300
variables = [variable for variable, _ in elements_list]
301301
try:
302302
merged_vars[name] = unique_variable(
303-
name, variables, compat, equals.get(name, None)
303+
name, variables, compat, equals.get(name)
304304
)
305305
except MergeError:
306306
if compat != "minimal":

xarray/tests/test_coding.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,8 +94,8 @@ def test_coder_roundtrip() -> None:
9494
assert_identical(original, roundtripped)
9595

9696

97-
@pytest.mark.parametrize("dtype", "u1 u2 i1 i2 f2 f4".split())
98-
@pytest.mark.parametrize("dtype2", "f4 f8".split())
97+
@pytest.mark.parametrize("dtype", ["u1", "u2", "i1", "i2", "f2", "f4"])
98+
@pytest.mark.parametrize("dtype2", ["f4", "f8"])
9999
def test_scaling_converts_to_float(dtype: str, dtype2: str) -> None:
100100
dt = np.dtype(dtype2)
101101
original = xr.Variable(

xarray/tests/test_dask.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1636,7 +1636,7 @@ def test_normalize_token_with_backend(map_ds):
16361636
with create_tmp_file(allow_cleanup_failure=ON_WINDOWS) as tmp_file:
16371637
map_ds.to_netcdf(tmp_file)
16381638
read = xr.open_dataset(tmp_file)
1639-
assert not dask.base.tokenize(map_ds) == dask.base.tokenize(read)
1639+
assert dask.base.tokenize(map_ds) != dask.base.tokenize(read)
16401640
read.close()
16411641

16421642

0 commit comments

Comments
 (0)