Skip to content

Commit 99d32f5

Browse files
authored
Enable ruff rule that enforces using items() to iterate over dict key/value pairs (#2811)
1 parent 7cb7cfc commit 99d32f5

File tree

8 files changed

+28
-30
lines changed

8 files changed

+28
-30
lines changed

esmvalcore/_recipe/check.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -329,13 +329,13 @@ def extract_shape(settings: dict[str, Any]) -> None:
329329
"crop": {True, False},
330330
"decomposed": {True, False},
331331
}
332-
for key in valid:
332+
for key, valid_values in valid.items():
333333
value = settings.get(key)
334-
if not (value is None or value in valid[key]):
334+
if not (value is None or value in valid_values):
335335
msg = (
336336
f"In preprocessor function `extract_shape`: Invalid value "
337337
f"'{value}' for argument '{key}', choose from "
338-
"{}".format(", ".join(f"'{k}'".lower() for k in valid[key]))
338+
"{}".format(", ".join(f"'{k}'".lower() for k in valid_values))
339339
)
340340
raise RecipeError(msg)
341341

esmvalcore/_task.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -81,12 +81,12 @@ def _get_resource_usage(process, start_time, children=True):
8181
processes = [process]
8282

8383
# Update resource usage
84-
for proc in cache:
84+
for proc, cached_value in cache.items():
8585
# Set cpu percent and memory usage to 0 for old processes
8686
if proc not in processes:
87-
cache[proc][1] = 0
88-
cache[proc][2] = 0
89-
cache[proc][3] = 0
87+
cached_value[1] = 0
88+
cached_value[2] = 0
89+
cached_value[3] = 0
9090
for proc in processes:
9191
# Update current processes
9292
cache[proc] = [
@@ -206,9 +206,9 @@ def _ncl_type(value):
206206
int: "int64",
207207
dict: "logical",
208208
}
209-
for type_ in typemap:
209+
for type_, ncl_type in typemap.items():
210210
if isinstance(value, type_):
211-
return typemap[type_]
211+
return ncl_type
212212
msg = f"Unable to map {type(value)} to an NCL type"
213213
raise ValueError(msg)
214214

esmvalcore/config/_diagnostics.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -164,9 +164,8 @@ def replace_tags_in_dict(self, dct: dict):
164164
Tags are updated one level deep, and only if the corresponding
165165
section exists in the ``TagsManager``.
166166
"""
167-
for key in dct:
167+
for key, tags in dct.items():
168168
if key in self:
169-
tags = dct[key]
170169
dct[key] = self.get_tag_values(key, tags)
171170

172171

esmvalcore/dataset.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,9 @@
6969

7070
def _augment(base: dict, update: dict) -> None:
7171
"""Update dict `base` with values from dict `update`."""
72-
for key in update:
72+
for key, value in update.items():
7373
if key not in base:
74-
base[key] = update[key]
74+
base[key] = value
7575

7676

7777
def _isglob(facet_value: FacetValue | None) -> bool:

esmvalcore/preprocessor/__init__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ def _get_itype(step: str) -> str:
259259

260260
def check_preprocessor_settings(settings: dict[str, Any]) -> None:
261261
"""Check preprocessor settings."""
262-
for step in settings:
262+
for step, kwargs in settings.items():
263263
if step not in DEFAULT_ORDER:
264264
msg = (
265265
f"Unknown preprocessor function '{step}', choose from: "
@@ -294,7 +294,7 @@ def check_preprocessor_settings(settings: dict[str, Any]) -> None:
294294
],
295295
)
296296
if check_args:
297-
invalid_args = set(settings[step]) - set(args)
297+
invalid_args = set(kwargs) - set(args)
298298
if invalid_args:
299299
msg = (
300300
f"Invalid argument(s) [{', '.join(invalid_args)}] "
@@ -310,7 +310,7 @@ def check_preprocessor_settings(settings: dict[str, Any]) -> None:
310310
if p.default is not inspect.Parameter.empty
311311
]
312312
end = None if not defaults else -len(defaults)
313-
missing_args = set(args[:end]) - set(settings[step])
313+
missing_args = set(args[:end]) - set(kwargs)
314314
if missing_args:
315315
msg = (
316316
f"Missing required argument(s) {missing_args} for "
@@ -320,7 +320,7 @@ def check_preprocessor_settings(settings: dict[str, Any]) -> None:
320320

321321
# Final sanity check in case the above fails to catch a mistake
322322
try:
323-
signature.bind(None, **settings[step])
323+
signature.bind(None, **kwargs)
324324
except TypeError:
325325
logger.error(
326326
"Wrong preprocessor function arguments in function '%s'",

pyproject.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,6 @@ ignore = [
188188
"N818", # Exception name should be named with an Error suffix
189189
"PERF", # Use comprehensions
190190
"PGH003", # Use specific rule codes when ignoring type issues
191-
"PLC0206", # Extracting value from dictionary without calling `.items()`
192191
"PLR2004", # Don't use magic values
193192
"PLW2901", # Don't overwrite a loop variable
194193
"PT009", # Use a regular `assert` instead of unittest-style `assertListEqual`

tests/unit/config/test_config.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -205,8 +205,8 @@ def test_load_default_config(cfg_default, monkeypatch):
205205
assert all(hasattr(session, attr) for attr in directory_attrs)
206206

207207
# Check default values
208-
for key in default_cfg:
209-
assert session[key] == default_cfg[key]
208+
for key, value in default_cfg.items():
209+
assert session[key] == value
210210

211211
# Check output directories
212212
assert str(session.session_dir).startswith(

tests/unit/recipe/test_recipe.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -334,9 +334,9 @@ def test_update_multiproduct_multi_model_statistics():
334334
)
335335

336336
for product in output:
337-
for attr in common_attributes:
337+
for attr, value in common_attributes.items():
338338
assert attr in product.attributes
339-
assert product.attributes[attr] == common_attributes[attr]
339+
assert product.attributes[attr] == value
340340
assert "alias" in product.attributes
341341
assert "dataset" in product.attributes
342342
assert "multi_model_statistics" in product.attributes
@@ -419,9 +419,9 @@ def test_update_multiproduct_no_timerange():
419419

420420
assert product.filename == Path("/preproc/d/var/CMIP6_MultiModelMean.nc")
421421

422-
for attr in common_attributes:
422+
for attr, value in common_attributes.items():
423423
assert attr in product.attributes
424-
assert product.attributes[attr] == common_attributes[attr]
424+
assert product.attributes[attr] == value
425425
assert "alias" in product.attributes
426426
assert "dataset" in product.attributes
427427
assert "multi_model_statistics" in product.attributes
@@ -523,9 +523,9 @@ def test_update_multiproduct_multi_model_statistics_percentile():
523523
)
524524

525525
for product in output:
526-
for attr in common_attributes:
526+
for attr, value in common_attributes.items():
527527
assert attr in product.attributes
528-
assert product.attributes[attr] == common_attributes[attr]
528+
assert product.attributes[attr] == value
529529
assert "alias" in product.attributes
530530
assert "dataset" in product.attributes
531531
assert "multi_model_statistics" in product.attributes
@@ -617,9 +617,9 @@ def test_update_multiproduct_ensemble_statistics():
617617
"/preproc/d/var/CMIP6_CanESM2_EnsembleMedian_2000-2000.nc",
618618
)
619619

620-
for attr in common_attributes:
620+
for attr, value in common_attributes.items():
621621
assert attr in product.attributes
622-
assert product.attributes[attr] == common_attributes[attr]
622+
assert product.attributes[attr] == value
623623
assert "alias" in product.attributes
624624
assert product.attributes["alias"] == "EnsembleMedian"
625625
assert "dataset" in product.attributes
@@ -704,9 +704,9 @@ def test_update_multiproduct_ensemble_statistics_percentile():
704704
"/preproc/d/var/CMIP6_CanESM2_EnsemblePercentile5_2000-2000.nc",
705705
)
706706

707-
for attr in common_attributes:
707+
for attr, value in common_attributes.items():
708708
assert attr in product.attributes
709-
assert product.attributes[attr] == common_attributes[attr]
709+
assert product.attributes[attr] == value
710710
assert "alias" in product.attributes
711711
assert product.attributes["alias"] == "EnsemblePercentile5"
712712
assert "dataset" in product.attributes

0 commit comments

Comments
 (0)