]> git.ipfire.org Git - thirdparty/knot-resolver.git/commitdiff
python: applied code simplification improvements
authorAleš Mrázek <ales.mrazek@nic.cz>
Sat, 10 Jan 2026 21:32:06 +0000 (22:32 +0100)
committerAleš Mrázek <ales.mrazek@nic.cz>
Mon, 12 Jan 2026 13:47:51 +0000 (14:47 +0100)
python/knot_resolver/client/client.py
python/knot_resolver/client/command.py
python/knot_resolver/client/commands/migrate.py
python/knot_resolver/datamodel/types/files.py
python/knot_resolver/manager/config_store.py
python/knot_resolver/manager/manager.py
python/knot_resolver/utils/modeling/base_schema.py

index 55b8f0e98dad5cca589e6c02df477fda620a43cd..f9c3c07ee7f91ef26c3e86699c0105bde2118ea4 100644 (file)
@@ -30,10 +30,7 @@ class KresClient:
         white = "\033[38;5;255m"
         reset = "\033[0;0m"
 
-        if self.path:
-            prompt = f"{bolt}[{self.prompt} {white}{self.path}{reset}{bolt}]"
-        else:
-            prompt = f"{bolt}{self.prompt}"
+        prompt = f"{bolt}[{self.prompt} {white}{self.path}{reset}{bolt}]" if self.path else f"{bolt}{self.prompt}"
         return f"{prompt}> {reset}"
 
     def interactive(self) -> None:
index 7a679885af451a62024913b420205d736ec30502..62e5e0c8cc823a0f45c5e1d83b8cad6405116123 100644 (file)
@@ -119,7 +119,7 @@ def comp_get_words(args: List[str], parser: argparse.ArgumentParser) -> CompWord
 
         # if action is SubParserAction
         if isinstance(action, argparse._SubParsersAction):  # noqa: SLF001
-            subparser: Optional[argparse.ArgumentParser] = action.choices[arg] if arg in action.choices else None
+            subparser: Optional[argparse.ArgumentParser] = action.choices.get(arg, None)
 
             command = get_subparser_command(subparser) if subparser else None
             if command and subparser:
index 48899931adc09981f1a0fcc70154fb669d1640e1..b870d63cdb7392ef3442dd99ee7b79faf19c319e 100644 (file)
@@ -33,9 +33,7 @@ def _add(config: Dict[str, Any], path: str, val: Any, rewrite: bool = False) ->
 
     current = config
     for key in keys[1:-1]:
-        if key not in current:
-            current[key] = {}
-        elif key in current and not isinstance(current[key], dict):
+        if key not in current or key in current and not isinstance(current[key], dict):
             current[key] = {}
         current = current[key]
 
index aaf2b27e6a8badd8c937b00ecd1a5f59454c0c37..bc42b2504386ca6994261458f7775b70716a0db1 100644 (file)
@@ -34,10 +34,7 @@ class UncheckedPath(BaseValueType):
         if isinstance(source_value, str):
             # we do not load global validation context if the path is absolute
             # this prevents errors when constructing defaults in the schema
-            if source_value.startswith("/"):
-                resolve_root = Path("/")
-            else:
-                resolve_root = get_resolve_root()
+            resolve_root = Path("/") if source_value.startswith("/") else get_resolve_root()
 
             self._raw_value: str = source_value
             if self._parents:
@@ -197,11 +194,7 @@ def _check_permission(dest_path: Path, perm_mode: _PermissionMode) -> bool:
 
     # __iter__ for class enum.Flag added in python3.11
     # 'for perm in perm_mode:' fails for <=python3.11
-    for perm in _PermissionMode:
-        if perm in perm_mode:
-            if not accessible(perm):
-                return False
-    return True
+    return all(not (perm in perm_mode and not accessible(perm)) for perm in _PermissionMode)
 
 
 class ReadableFile(File):
index 15af1767c7108301eec4d80db11b085b98a33248..d249d81b5a8ca46eec3933198904676dfec0d7df 100644 (file)
@@ -66,9 +66,7 @@ def only_on_no_changes_update(selector: Callable[[KresConfig], Any]) -> Callable
             nonlocal original_value
             if not original_value_set:
                 original_value_set = True
-            elif original_value == selector(config):
-                await orig_func(config, force)
-            elif force:
+            elif original_value == selector(config) or force:
                 await orig_func(config, force)
             original_value = selector(config)
 
@@ -88,9 +86,7 @@ def only_on_real_changes_update(selector: Callable[[KresConfig], Any]) -> Callab
             if not original_value_set:
                 original_value_set = True
                 await orig_func(config, force)
-            elif original_value != selector(config):
-                await orig_func(config, force)
-            elif force:
+            elif original_value != selector(config) or force:
                 await orig_func(config, force)
             original_value = selector(config)
 
index 090d9ac16fe40901fa6a87c18401881ca15685f6..ce5919e4cdd59d097a829d9a4294d95ee2bedc4d 100644 (file)
@@ -37,13 +37,12 @@ class _FixCounter:
         self._timestamp = time.time()
 
     def try_decrease(self) -> None:
-        if time.time() - self._timestamp > FIX_COUNTER_DECREASE_INTERVAL_SEC:
-            if self._counter > 0:
-                logger.info(
-                    f"Enough time has passed since last detected instability, decreasing fix attempt counter to {self._counter}"
-                )
-                self._counter -= 1
-                self._timestamp = time.time()
+        if time.time() - self._timestamp > FIX_COUNTER_DECREASE_INTERVAL_SEC and self._counter > 0:
+            logger.info(
+                f"Enough time has passed since last detected instability, decreasing fix attempt counter to {self._counter}"
+            )
+            self._counter -= 1
+            self._timestamp = time.time()
 
     def __str__(self) -> str:
         return str(self._counter)
index a90c6ee73c6192dea31fbececb3271f2cf315b85..29080999a7fe7174e658ae53697c4e15e75bccb0 100644 (file)
@@ -591,10 +591,7 @@ class ObjectMapper:
                 return func(_create_untouchable("obj"), source)
             raise RuntimeError("Transformation function has wrong number of arguments")
         except ValueError as e:
-            if len(e.args) > 0 and isinstance(e.args[0], str):
-                msg = e.args[0]
-            else:
-                msg = "Failed to validate value type"
+            msg = e.args[0] if len(e.args) > 0 and isinstance(e.args[0], str) else "Failed to validate value type"
             raise DataValidationError(msg, object_path) from e
 
     def object_constructor(self, obj: Any, source: Union["BaseSchema", Dict[Any, Any]], object_path: str) -> None:
@@ -738,11 +735,7 @@ class BaseSchema(Serializable):
             return False
 
         annot = get_annotations(cls)
-        for name in annot.keys():
-            if getattr(self, name) != getattr(o, name):
-                return False
-
-        return True
+        return all(getattr(self, name) == getattr(o, name) for name in annot)
 
     @classmethod
     def json_schema(