Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

refactor: resolve and enforce Ruff SIM118 and SIM401 (#5435)

Alex1ce0ec5eed66
diff --git a/conftest.py b/conftest.py
index 3650e5775..cd5d2b8d3 100644
--- a/conftest.py
+++ b/conftest.py
@@ -707,7 +707,7 @@ main deps:
- torch-{torch.__version__}
- commit: {torch.version.git_version}
- cuda: {torch.version.cuda}
- - nvidia-driver: {env_info["nvidia"] if "nvidia" in env_info else None}
+ - nvidia-driver: {env_info.get("nvidia")}
x deps:
- {accelerate_info}
dev deps:
diff --git a/kornia/augmentation/_2d/intensity/solarize.py b/kornia/augmentation/_2d/intensity/solarize.py
index a9b873874..499aa9045 100644
--- a/kornia/augmentation/_2d/intensity/solarize.py
+++ b/kornia/augmentation/_2d/intensity/solarize.py
@@ -107,8 +107,5 @@ class RandomSolarize(IntensityAugmentationBase2D):
) -> torch.Tensor:
thresholds = params["thresholds"]
additions: Optional[torch.Tensor]
- if "additions" in params:
- additions = params["additions"]
- else:
- additions = None
+ additions = params.get("additions")
return solarize(input, thresholds, additions)
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index ce342bd86..5bdaf0aaa 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -271,7 +271,7 @@ class _BasicAugmentationBase(nn.Module):
**kwargs: Any,
) -> Tuple[Dict[str, torch.Tensor], Dict[str, Any]]:
# NOTE: determine how to save self._params
- save_kwargs = kwargs["save_kwargs"] if "save_kwargs" in kwargs else False
+ save_kwargs = kwargs.get("save_kwargs", False)
params = self._params if params is None else params
flags = self.flags if flags is None else flags
diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.py
index cabbdb56c..0cc81b4b6 100644
--- a/kornia/augmentation/container/ops.py
+++ b/kornia/augmentation/container/ops.py
@@ -250,7 +250,7 @@ class AugmentationSequentialOps:
outputs = []
for inp, dcate in zip(arg, _data_keys):
op = self._get_op(dcate)
- extra_arg = extra_args[dcate] if dcate in extra_args else {}
+ extra_arg = extra_args.get(dcate, {})
if dcate.name == "MASK" and isinstance(inp, list):
# Mirror ``transform``: a list of masks is inverted element by element.
outputs.append(MaskSequentialOps.inverse_list(inp, module, param=param, extra_args=extra_arg))
diff --git a/kornia/augmentation/presets/ada.py b/kornia/augmentation/presets/ada.py
index efcd919de..6a2a0d5ba 100644
--- a/kornia/augmentation/presets/ada.py
+++ b/kornia/augmentation/presets/ada.py
@@ -239,7 +239,7 @@ class AdaptiveDiscriminatorAugmentation(AugmentationSequential):
merged: _inputs_type
if isinstance(original, dict) and isinstance(augmented, dict):
merged = {}
- for key in original.keys():
+ for key in original:
merged_tensor = original[key].clone()
merged_tensor[p_tensor] = augmented[key]
merged[key] = merged_tensor
diff --git a/kornia/feature/adalam/adalam.py b/kornia/feature/adalam/adalam.py
index 2828e1776..dbd63a5a5 100644
--- a/kornia/feature/adalam/adalam.py
+++ b/kornia/feature/adalam/adalam.py
@@ -91,7 +91,7 @@ def match_adalam(
else:
config_ = get_adalam_default_config()
for key, val in config.items():
- if key not in config_.keys():
+ if key not in config_:
print(
f"WARNING: custom configuration contains a key which is not recognized ({key}). "
f"Known configurations are {list(config_.keys())}."
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index 76a248db1..bd4edc384 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -603,7 +603,7 @@ class LocalFeatureMatcher(nn.Module):
"""
num_image_pairs: int = data["image0"].shape[0]
- if ("lafs0" not in data.keys()) or ("descriptors0" not in data.keys()):
+ if ("lafs0" not in data) or ("descriptors0" not in data):
# One can supply pre-extracted local features
mask0 = data.get("mask0")
if mask0 is not None and mask0.dim() == 3:
@@ -613,7 +613,7 @@ class LocalFeatureMatcher(nn.Module):
else:
lafs0, descs0 = data["lafs0"], data["descriptors0"]
- if ("lafs1" not in data.keys()) or ("descriptors1" not in data.keys()):
+ if ("lafs1" not in data) or ("descriptors1" not in data):
mask1 = data.get("mask1")
if mask1 is not None and mask1.dim() == 3:
mask1 = mask1.unsqueeze(1)
diff --git a/kornia/feature/loftr/loftr.py b/kornia/feature/loftr/loftr.py
index 00c797b4f..b5b807564 100644
--- a/kornia/feature/loftr/loftr.py
+++ b/kornia/feature/loftr/loftr.py
@@ -121,7 +121,7 @@ class LoFTR(nn.Module):
self.fine_matching = FineMatching()
self.pretrained = pretrained
if pretrained is not None:
- if pretrained not in urls.keys():
+ if pretrained not in urls:
raise ValueError(f"pretrained should be None or one of {urls.keys()}")
pretrained_dict = load_state_dict_from_url(urls[pretrained], map_location=torch.device("cpu"))
diff --git a/kornia/models/efficient_vit/model.py b/kornia/models/efficient_vit/model.py
index f55239879..af9278f63 100644
--- a/kornia/models/efficient_vit/model.py
+++ b/kornia/models/efficient_vit/model.py
@@ -81,7 +81,7 @@ class EfficientViT(ModelBase[EfficientViTConfig]):
# load the model from the checkpoint
try:
model_file = load_state_dict_from_url(config.checkpoint, map_location="cpu")
- model_file = model_file["state_dict"] if "state_dict" in model_file else model_file
+ model_file = model_file.get("state_dict", model_file)
except RuntimeError:
raise RuntimeError(f"Unable to load the model from {config.checkpoint}.") from None
diff --git a/kornia/models/rt_detr/model.py b/kornia/models/rt_detr/model.py
index 5f77ed877..fbcfcb8af 100644
--- a/kornia/models/rt_detr/model.py
+++ b/kornia/models/rt_detr/model.py
@@ -275,7 +275,7 @@ class RTDETR(ONNXExportMixin, ModelBase[RTDETRConfig]):
new_state_dict = {}
# Apply the regex-based mapping function to each key
- for old_name in state_dict.keys():
+ for old_name in state_dict:
new_name = map_name(old_name)
new_state_dict[new_name] = state_dict[old_name]
diff --git a/kornia/models/tiny_vit.py b/kornia/models/tiny_vit.py
index 54c05e5e8..4114df463 100644
--- a/kornia/models/tiny_vit.py
+++ b/kornia/models/tiny_vit.py
@@ -715,7 +715,7 @@ def _load_pretrained(model: TinyViT, url: str | list[str]) -> TinyViT:
# https://github.com/microsoft/Cream/blob/8dc38822b99fff8c262c585a32a4f09ac504d693/TinyViT/utils.py#L163
# bicubic interpolate attention biases
- ab_keys = [k for k in state_dict.keys() if "attention_biases" in k]
+ ab_keys = [k for k in state_dict if "attention_biases" in k]
for k in ab_keys:
n_heads1, L1 = state_dict[k].shape
n_heads2, L2 = model_state_dict[k].shape
diff --git a/pyproject.toml b/pyproject.toml
index 1b4bc150f..62e4bca94 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -229,10 +229,12 @@ select = [
"SIM103", # needless-bool
"SIM114", # if-with-same-arms
"SIM115", # open-file-with-context-handler
+ "SIM118", # in-dict-keys
"SIM201", # negate-equal-op
"SIM210", # if-expr-with-true-false
"SIM211", # if-expr-with-false-true
"SIM222", # expr-or-true
+ "SIM401", # if-else-block-instead-of-dict-get
"SIM910", # dict-get-with-none-default
"SLOT", # flake8-slots
"T10", # flake8-debugger
diff --git a/tests/integration/models/test_kimi_vl.py b/tests/integration/models/test_kimi_vl.py
index ce35d3799..333f0facd 100644
--- a/tests/integration/models/test_kimi_vl.py
+++ b/tests/integration/models/test_kimi_vl.py
@@ -53,7 +53,7 @@ def test_kimi_vl_official_weights():
with open(index_path) as f:
index = json.load(f)
- vision_keys = [k for k in index["weight_map"].keys() if "vision_tower" in k or "multi_modal_projector" in k]
+ vision_keys = [k for k in index["weight_map"] if "vision_tower" in k or "multi_modal_projector" in k]
shards = {index["weight_map"][k] for k in vision_keys}
state_dict = {}