Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

refactor: resolve and enforce Ruff SIM108 (#5615)

Alexa80fe2891e8c
diff --git a/docs/generate_examples.py b/docs/generate_examples.py
index 3b3bb8349..33cd556e9 100644
--- a/docs/generate_examples.py
+++ b/docs/generate_examples.py
@@ -468,10 +468,7 @@ def main():
img_in = img3.repeat(num_samples, 1, 1, 1)
if fn_name == "jpeg_codec_differentiable":
img_in = img_in[..., :176, :]
- if fn_name == "add_weighted":
- args_in = (img_in, args[0], img2, args[1], args[2])
- else:
- args_in = (img_in, *args)
+ args_in = (img_in, args[0], img2, args[1], args[2]) if fn_name == "add_weighted" else (img_in, *args)
# import function and apply
fn = getattr(mod, fn_name)
out = fn(*args_in)
diff --git a/docs/generate_export_support.py b/docs/generate_export_support.py
index 92cf71a82..1ae52f20f 100644
--- a/docs/generate_export_support.py
+++ b/docs/generate_export_support.py
@@ -154,11 +154,8 @@ def _escape(text: str) -> str:
def _operator_cell(case: dict) -> str:
op = case["operator"] or case["name"]
ref = case.get("ref")
- if ref:
- # ``~`` shows only the last component; the full path is in the link target.
- label = f":py:obj:`{op} <{ref}>`"
- else:
- label = f"``{op}``"
+ # ``~`` shows only the last component; the full path is in the link target.
+ label = f":py:obj:`{op} <{ref}>`" if ref else f"``{op}``"
if case.get("variant") and case["operator"]:
label += f" ``[{case['variant']}]``"
return label
diff --git a/docs/source/conf.py b/docs/source/conf.py
index 28b929ba2..82dbae1c1 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -302,10 +302,7 @@ html_baseurl = "https://kornia.readthedocs.io/en/latest/"
# Git ref that the "view/edit source" links and the ``linkcode`` extension point at.
rtd_version = os.environ.get("READTHEDOCS_VERSION")
-if rtd_version and rtd_version not in {"latest", "stable"}:
- code_ref = rtd_version
-else:
- code_ref = "main"
+code_ref = rtd_version if rtd_version and rtd_version not in {"latest", "stable"} else "main"
# Changing sidebar title to Kornia
html_title = "Kornia"
diff --git a/kornia/color/utils.py b/kornia/color/utils.py
index a9b909573..e6368780f 100644
--- a/kornia/color/utils.py
+++ b/kornia/color/utils.py
@@ -36,10 +36,7 @@ def _apply_linear_transformation(
Tensor with the same shape as ``image`` containing the transformed values.
"""
# Handle Integer inputs by casting to float safely
- if image.is_floating_point():
- image_compute = image
- else:
- image_compute = image.float()
+ image_compute = image if image.is_floating_point() else image.float()
# Match kernel dtype to the image (propagates float64 if needed)
kernel_compute = kernel.to(dtype=image_compute.dtype, device=image_compute.device)
diff --git a/kornia/contrib/extract_patches.py b/kornia/contrib/extract_patches.py
index cde3cb137..fb748936b 100644
--- a/kornia/contrib/extract_patches.py
+++ b/kornia/contrib/extract_patches.py
@@ -90,15 +90,9 @@ def compute_padding(
# it might be best to apply padding only to the far edges (right, bottom), so
# that fewer patches are affected by the padding.
# For now, just use the default padding
- if remainder_vertical != 0:
- vertical_padding = stride[0] - remainder_vertical
- else:
- vertical_padding = 0
+ vertical_padding = stride[0] - remainder_vertical if remainder_vertical != 0 else 0
- if remainder_horizontal != 0:
- horizontal_padding = stride[1] - remainder_horizontal
- else:
- horizontal_padding = 0
+ horizontal_padding = stride[1] - remainder_horizontal if remainder_horizontal != 0 else 0
if vertical_padding % 2 == 0:
top_padding = bottom_padding = vertical_padding // 2
diff --git a/kornia/contrib/super_resolution.py b/kornia/contrib/super_resolution.py
index 91cc96a0d..860367ea8 100644
--- a/kornia/contrib/super_resolution.py
+++ b/kornia/contrib/super_resolution.py
@@ -155,10 +155,7 @@ class SuperResolution(ModelBase[SuperResolutionConfig], ONNXExportMixin):
"""
output = self.pre_processor(images)
- if isinstance(output, (list, tuple)):
- images = output[0]
- else:
- images = output
+ images = output[0] if isinstance(output, (list, tuple)) else output
if isinstance(images, list):
out_images = [self.model(image[None])[0] for image in images]
else:
diff --git a/kornia/contrib/visual_prompter.py b/kornia/contrib/visual_prompter.py
index 65b639c0a..9b552e8cf 100644
--- a/kornia/contrib/visual_prompter.py
+++ b/kornia/contrib/visual_prompter.py
@@ -190,12 +190,7 @@ class VisualPrompter:
boxes = Boxes.from_tensor(boxes, mode="xyxy")
- if boxes.mode == "xyxy":
- boxes_xyxy = boxes
- else:
- boxes_xyxy = Boxes.from_tensor(boxes.to_tensor(mode="xyxy"), mode="xyxy")
-
- return boxes_xyxy
+ return boxes if boxes.mode == "xyxy" else Boxes.from_tensor(boxes.to_tensor(mode="xyxy"), mode="xyxy")
def _valid_masks(self, masks: torch.Tensor) -> torch.Tensor:
"""Validate the input masks shape."""
diff --git a/kornia/core/check.py b/kornia/core/check.py
index 1a5d3ab5e..3275f4dea 100644
--- a/kornia/core/check.py
+++ b/kornia/core/check.py
@@ -248,10 +248,7 @@ def KORNIA_CHECK(condition: bool, msg: Optional[str] = None, raises: bool = True
if not condition:
if raises:
- if msg is None:
- error_msg = "Validation condition failed"
- else:
- error_msg = msg
+ error_msg = "Validation condition failed" if msg is None else msg
raise BaseError(error_msg)
return False
return True
diff --git a/kornia/core/tensor_wrapper.py b/kornia/core/tensor_wrapper.py
index d36d4000d..00291c600 100644
--- a/kornia/core/tensor_wrapper.py
+++ b/kornia/core/tensor_wrapper.py
@@ -558,10 +558,7 @@ class TensorWrapper:
Returns:
Wrapped result of the operation.
"""
- if swap:
- args = (other, self)
- else:
- args = (self, other)
+ args = (other, self) if swap else (self, other)
return self.__torch_function__(func, (type(self),), args)
def __inplace_op__(self, func: Any, other: Any) -> Self:
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index 3954656d6..b41ec1292 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -199,7 +199,7 @@ def _inverse_3x3_closed_form(input: torch.Tensor) -> torch.Tensor:
"""
half = input.dtype in (torch.float16, torch.bfloat16)
x = input.float() if half else input
- if not _is_tracing_or_exporting():
+ if not _is_tracing_or_exporting(): # noqa: SIM108 - each branch documents its own capture path
# Eager: three fused ``cross`` ops beat nine scalar cofactor expressions and four
# stacks, because kernel launches dominate on matrices this small.
out = _inverse_3x3_cross(x)
@@ -441,10 +441,7 @@ def _torch_solve_cast(A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
"""
KORNIA_CHECK_IS_TENSOR(A, "A must be torch.Tensor")
KORNIA_CHECK_IS_TENSOR(B, "B must be torch.Tensor")
- if is_mps_tensor_safe(A):
- dtype = torch.float32
- else:
- dtype = torch.float64
+ dtype = torch.float32 if is_mps_tensor_safe(A) else torch.float64
out = torch.linalg.solve(A.to(dtype), B.to(dtype))
diff --git a/kornia/filters/filter.py b/kornia/filters/filter.py
index 5f5d89556..9d6c62504 100644
--- a/kornia/filters/filter.py
+++ b/kornia/filters/filter.py
@@ -199,12 +199,7 @@ def filter2d(
# convolve the tensor with the kernel.
output = F.conv2d(input, tmp_kernel, groups=tmp_kernel.size(0), padding=0, stride=1)
- if padding == "same":
- out = output.view(b, c, h, w)
- else:
- out = output.view(b, c, h - height + 1, w - width + 1)
-
- return out
+ return output.view(b, c, h, w) if padding == "same" else output.view(b, c, h - height + 1, w - width + 1)
def filter2d_separable(
diff --git a/kornia/filters/median.py b/kornia/filters/median.py
index 1bffb571b..5da8e0a04 100644
--- a/kornia/filters/median.py
+++ b/kornia/filters/median.py
@@ -204,11 +204,8 @@ def median_blur(input: torch.Tensor, kernel_size: tuple[int, int] | int, border_
features = features.view(b, c, ky * kx, h, w) # BxCx(K_h * K_w)xHxW
# compute the median along the feature axis
- if is_exporting():
- # ``median.dim`` has no ONNX lowering; a sort picks the same (lower-middle) element.
- median = features.sort(dim=2)[0][:, :, (ky * kx - 1) // 2]
- else:
- median = features.median(dim=2)[0]
+ # ``median.dim`` has no ONNX lowering, so while exporting a sort picks the same (lower-middle) element.
+ median = features.sort(dim=2)[0][:, :, (ky * kx - 1) // 2] if is_exporting() else features.median(dim=2)[0]
if invalid is not None:
median = median.masked_fill(invalid, float("nan"))
return median
diff --git a/kornia/geometry/line.py b/kornia/geometry/line.py
index 5876b1d23..b632989ba 100644
--- a/kornia/geometry/line.py
+++ b/kornia/geometry/line.py
@@ -421,11 +421,8 @@ def fit_line(points: torch.Tensor, weights: Optional[torch.Tensor] = None) -> Pa
A = work_points - mean
scale = A.abs().amax(dim=(-2, -1), keepdim=True)
A = A / torch.where(scale > 0, scale, torch.ones_like(scale))
- if weights is not None:
- # Scale the columns directly instead of allocating an N-by-N diagonal weight matrix.
- A = (A.transpose(-2, -1) * work_weights[..., None, :]) @ A
- else:
- A = A.transpose(-2, -1) @ A
+ # When weighted, scale the columns directly instead of allocating an N-by-N diagonal weight matrix.
+ A = (A.transpose(-2, -1) * work_weights[..., None, :]) @ A if weights is not None else A.transpose(-2, -1) @ A
# NOTE: not optimal for 2d points, but for now works for other dimensions
_, _, V = _torch_svd_cast(A)
diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.py
index 80ade00df..f7a9ff3db 100644
--- a/kornia/geometry/solvers/polynomial_solver.py
+++ b/kornia/geometry/solvers/polynomial_solver.py
@@ -965,10 +965,7 @@ def solve_quartic(coeffs: torch.Tensor) -> torch.Tensor:
compiling = torch.compiler.is_compiling()
# Evaluate Ferrari in double precision from the input coefficients, before forming a rounded resolvent.
# MPS has no float64 arithmetic; the copies remain differentiable.
- if coeffs.device.type == "mps":
- work = coeffs.cpu().double()
- else:
- work = coeffs.double()
+ work = coeffs.cpu().double() if coeffs.device.type == "mps" else coeffs.double()
zero_tol = 1e-12 if original_dtype == torch.float64 else 1e-6
# Selections, rounding-error bounds and conditioning choices below never carry a derivative;
# forming them without autograd leaves every gradient unchanged.
diff --git a/kornia/image/image_print.py b/kornia/image/image_print.py
index 3fc52927a..28b299156 100644
--- a/kornia/image/image_print.py
+++ b/kornia/image/image_print.py
@@ -343,10 +343,7 @@ def rgb2short(rgb: str) -> Tuple[str, str]:
if s <= part <= b:
s1 = abs(s - part)
b1 = abs(b - part)
- if s1 < b1:
- closest = s
- else:
- closest = b
+ closest = s if s1 < b1 else b
res.append(closest)
break
i += 1
diff --git a/kornia/image/utils.py b/kornia/image/utils.py
index ddeb14a60..eb47fe4ae 100644
--- a/kornia/image/utils.py
+++ b/kornia/image/utils.py
@@ -203,12 +203,9 @@ def tensor_to_image(tensor: torch.Tensor, keepdim: bool = False, force_contiguou
pass
elif len(input_shape) == 3:
# (C, H, W) -> (H, W, C)
- if input_shape[0] == 1:
- # Grayscale for proper plt.imshow needs to be (H,W); squeeze only the channel axis so that a unit H or W
- # of a 1-row or 1-column image survives.
- image = image.squeeze(0)
- else:
- image = image.permute(1, 2, 0)
+ # Grayscale for proper plt.imshow needs to be (H,W); squeeze only the channel axis so that a unit H or W
+ # of a 1-row or 1-column image survives.
+ image = image.squeeze(0) if input_shape[0] == 1 else image.permute(1, 2, 0)
elif len(input_shape) == 4:
# (B, C, H, W) -> (B, H, W, C)
image = image.permute(0, 2, 3, 1)
diff --git a/kornia/sensors/camera/projection_model.py b/kornia/sensors/camera/projection_model.py
index 3980f1a09..9683f9f02 100644
--- a/kornia/sensors/camera/projection_model.py
+++ b/kornia/sensors/camera/projection_model.py
@@ -60,11 +60,8 @@ class Z1Projection:
"""
xy = points.data[..., :2]
z = points.z
- if len(z.shape):
- uv = xy / z.unsqueeze(-1)
- else:
- # For scalar z, xy is 1-D, so no transpose needed
- uv = xy * 1 / z
+ # For scalar z, xy is 1-D, so no unsqueeze is needed
+ uv = xy / z.unsqueeze(-1) if len(z.shape) else xy * 1 / z
return Vector2(uv)
def unproject(self, points: Vector2, depth: torch.Tensor | float) -> Vector3:
diff --git a/pyproject.toml b/pyproject.toml
index 0941e3216..670dd73a9 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -231,6 +231,7 @@ select = [
"SIM102", # collapsible-if
"SIM103", # needless-bool
"SIM105", # suppressible-exception
+ "SIM108", # if-else-block-instead-of-if-exp
"SIM114", # if-with-same-arms
"SIM115", # open-file-with-context-handler
"SIM117", # multiple-with-statements
diff --git a/tests/losses/test_ssim.py b/tests/losses/test_ssim.py
index a30f922df..3ba6aa86d 100644
--- a/tests/losses/test_ssim.py
+++ b/tests/losses/test_ssim.py
@@ -48,10 +48,7 @@ class TestSSIMLoss(BaseTester):
loss = kornia.losses.ssim_loss(img, img, window_size, reduction=reduction_type)
- if reduction_type == "none":
- expected = torch.zeros_like(img)
- else:
- expected = torch.tensor(0.0, device=device, dtype=dtype)
+ expected = torch.zeros_like(img) if reduction_type == "none" else torch.tensor(0.0, device=device, dtype=dtype)
self.assert_close(loss, expected)
@@ -426,10 +423,7 @@ class TestSSIM3DLoss(BaseTester):
# Sanity test
img = torch.rand(shape, device=device, dtype=dtype)
actual = kornia.losses.ssim3d_loss(img, img, window_size, reduction=reduction_type)
- if reduction_type == "none":
- expected = torch.zeros_like(img)
- else:
- expected = torch.tensor(0.0, device=device, dtype=dtype)
+ expected = torch.zeros_like(img) if reduction_type == "none" else torch.tensor(0.0, device=device, dtype=dtype)
self.assert_close(actual, expected)