Skip to content

Commit 5d5bc5b

Browse files
Enforce ruff/flake8-simplify rules (SIM) (#10462)
* 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 ruf/flake8-simplify rule SIM118 SIM118 Use `key in dict` instead of `key in dict.keys()` * 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)
1 parent e71bb12 commit 5d5bc5b

26 files changed

+80
-83
lines changed

pyproject.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,7 @@ extend-select = [
256256
"PIE", # flake8-pie
257257
"TID", # flake8-tidy-imports (absolute imports)
258258
"PYI", # flake8-pyi
259+
"SIM", # flake8-simplify
259260
"FLY", # flynt
260261
"I", # isort
261262
"PERF", # Perflint
@@ -277,6 +278,9 @@ ignore = [
277278
"PIE790", # unnecessary pass statement
278279
"PYI019", # use `Self` instead of custom TypeVar
279280
"PYI041", # use `float` instead of `int | float`
281+
"SIM108", # use ternary operator instead of `if`-`else`-block
282+
"SIM117", # use a single `with` statement instead of nested `with` statements
283+
"SIM300", # yoda condition detected
280284
"PERF203", # try-except within a loop incurs performance overhead
281285
"E402", # module level import not at top of file
282286
"E731", # do not assign a lambda expression, use a def

xarray/backends/netCDF4_.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,7 @@ def _extract_nc4_variable_encoding(
298298
del encoding["chunksizes"]
299299

300300
var_has_unlim_dim = any(dim in unlimited_dims for dim in variable.dims)
301-
if not raise_on_invalid and var_has_unlim_dim and "contiguous" in encoding.keys():
301+
if not raise_on_invalid and var_has_unlim_dim and "contiguous" in encoding:
302302
del encoding["contiguous"]
303303

304304
for k in safe_to_drop:

xarray/backends/pydap_.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -348,14 +348,14 @@ def group_fqn(store, path=None, g_fqn=None) -> dict[str, str]:
348348
if not g_fqn:
349349
g_fqn = {}
350350
groups = [
351-
store[key].id
352-
for key in store.keys()
353-
if isinstance(store[key], GroupType)
351+
var.id for var in store.values() if isinstance(var, GroupType)
354352
]
355353
for g in groups:
356354
g_fqn.update({g: path})
357355
subgroups = [
358-
var for var in store[g] if isinstance(store[g][var], GroupType)
356+
key
357+
for key, var in store[g].items()
358+
if isinstance(var, GroupType)
359359
]
360360
if len(subgroups) > 0:
361361
npath = path + g

xarray/coding/times.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -733,7 +733,7 @@ def infer_calendar_name(dates) -> CFCalendar:
733733
"""Given an array of datetimes, infer the CF calendar name"""
734734
if is_np_datetime_like(dates.dtype):
735735
return "proleptic_gregorian"
736-
elif dates.dtype == np.dtype("O") and dates.size > 0:
736+
elif dates.dtype == np.dtype("O") and dates.size > 0: # noqa: SIM102
737737
# Logic copied from core.common.contains_cftime_datetimes.
738738
if cftime is not None:
739739
sample = np.asarray(dates).flat[0]

xarray/computation/rolling.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1079,7 +1079,7 @@ def __init__(
10791079
self.side = side
10801080
self.boundary = boundary
10811081

1082-
missing_dims = tuple(dim for dim in windows.keys() if dim not in self.obj.dims)
1082+
missing_dims = tuple(dim for dim in windows if dim not in self.obj.dims)
10831083
if missing_dims:
10841084
raise ValueError(
10851085
f"Window dimensions {missing_dims} not found in {self.obj.__class__.__name__} "

xarray/core/common.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1247,9 +1247,7 @@ def _dataset_indexer(dim: Hashable) -> DataArray:
12471247
_dataarray_indexer if isinstance(cond, DataArray) else _dataset_indexer
12481248
)
12491249

1250-
indexers = {}
1251-
for dim in cond.sizes.keys():
1252-
indexers[dim] = _get_indexer(dim)
1250+
indexers = {dim: _get_indexer(dim) for dim in cond.sizes}
12531251

12541252
self = self.isel(**indexers)
12551253
cond = cond.isel(**indexers)

xarray/core/dataarray.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ def _check_data_shape(
212212
data_shape = tuple(
213213
(
214214
as_variable(coords[k], k, auto_convert=False).size
215-
if k in coords.keys()
215+
if k in coords
216216
else 1
217217
)
218218
for k in dims

xarray/core/dataset.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4086,21 +4086,20 @@ def _rename(
40864086
is raised at the right stack level.
40874087
"""
40884088
name_dict = either_dict_or_kwargs(name_dict, names, "rename")
4089-
for k in name_dict.keys():
4089+
for k, new_k in name_dict.items():
40904090
if k not in self and k not in self.dims:
40914091
raise ValueError(
40924092
f"cannot rename {k!r} because it is not a "
40934093
"variable or dimension in this dataset"
40944094
)
40954095

40964096
create_dim_coord = False
4097-
new_k = name_dict[k]
40984097

40994098
if k == new_k:
41004099
continue # Same name, nothing to do
41014100

41024101
if k in self.dims and new_k in self._coord_names:
4103-
coord_dims = self._variables[name_dict[k]].dims
4102+
coord_dims = self._variables[new_k].dims
41044103
if coord_dims == (k,):
41054104
create_dim_coord = True
41064105
elif k in self._coord_names and new_k in self.dims:
@@ -4110,7 +4109,7 @@ def _rename(
41104109

41114110
if create_dim_coord:
41124111
warnings.warn(
4113-
f"rename {k!r} to {name_dict[k]!r} does not create an index "
4112+
f"rename {k!r} to {new_k!r} does not create an index "
41144113
"anymore. Try using swap_dims instead or use set_index "
41154114
"after rename to create an indexed coordinate.",
41164115
UserWarning,
@@ -8976,16 +8975,18 @@ def pad(
89768975
variables[name] = var
89778976
elif name in self.data_vars:
89788977
if utils.is_dict_like(constant_values):
8979-
if name in constant_values.keys():
8978+
if name in constant_values:
89808979
filtered_constant_values = constant_values[name]
89818980
elif not set(var.dims).isdisjoint(constant_values.keys()):
89828981
filtered_constant_values = {
8983-
k: v for k, v in constant_values.items() if k in var.dims
8982+
k: v # type: ignore[misc]
8983+
for k, v in constant_values.items()
8984+
if k in var.dims
89848985
}
89858986
else:
89868987
filtered_constant_values = 0 # TODO: https://github.com/pydata/xarray/pull/9353#discussion_r1724018352
89878988
else:
8988-
filtered_constant_values = constant_values
8989+
filtered_constant_values = constant_values # type: ignore[assignment]
89898990
variables[name] = var.pad(
89908991
pad_width=var_pad_width,
89918992
mode=mode,

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

0 commit comments

Comments
 (0)