From: Aleš Mrázek Date: Sat, 10 Jan 2026 21:32:06 +0000 (+0100) Subject: python: applied code simplification improvements X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=31e30dedbf92d95f833357989f7b973f229daa1a;p=thirdparty%2Fknot-resolver.git python: applied code simplification improvements --- diff --git a/python/knot_resolver/client/client.py b/python/knot_resolver/client/client.py index 55b8f0e98..f9c3c07ee 100644 --- a/python/knot_resolver/client/client.py +++ b/python/knot_resolver/client/client.py @@ -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: diff --git a/python/knot_resolver/client/command.py b/python/knot_resolver/client/command.py index 7a679885a..62e5e0c8c 100644 --- a/python/knot_resolver/client/command.py +++ b/python/knot_resolver/client/command.py @@ -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: diff --git a/python/knot_resolver/client/commands/migrate.py b/python/knot_resolver/client/commands/migrate.py index 48899931a..b870d63cd 100644 --- a/python/knot_resolver/client/commands/migrate.py +++ b/python/knot_resolver/client/commands/migrate.py @@ -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] diff --git a/python/knot_resolver/datamodel/types/files.py b/python/knot_resolver/datamodel/types/files.py index aaf2b27e6..bc42b2504 100644 --- a/python/knot_resolver/datamodel/types/files.py +++ b/python/knot_resolver/datamodel/types/files.py @@ -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): diff --git a/python/knot_resolver/manager/config_store.py b/python/knot_resolver/manager/config_store.py index 15af1767c..d249d81b5 100644 --- a/python/knot_resolver/manager/config_store.py +++ b/python/knot_resolver/manager/config_store.py @@ -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) diff --git a/python/knot_resolver/manager/manager.py b/python/knot_resolver/manager/manager.py index 090d9ac16..ce5919e4c 100644 --- a/python/knot_resolver/manager/manager.py +++ b/python/knot_resolver/manager/manager.py @@ -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) diff --git a/python/knot_resolver/utils/modeling/base_schema.py b/python/knot_resolver/utils/modeling/base_schema.py index a90c6ee73..29080999a 100644 --- a/python/knot_resolver/utils/modeling/base_schema.py +++ b/python/knot_resolver/utils/modeling/base_schema.py @@ -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(