From a6335a5055a03104d97da3973db4defd5bdd7d82 Mon Sep 17 00:00:00 2001 From: Patrick Ogenstad Date: Tue, 9 Jul 2024 20:42:12 +0200 Subject: [PATCH] Simlify _verify_rules and redunce max-complexity=10 --- nornir/core/filter.py | 54 +++++++++++++++++++++++-------------------- pyproject.toml | 2 +- 2 files changed, 30 insertions(+), 26 deletions(-) diff --git a/nornir/core/filter.py b/nornir/core/filter.py index e9d37b7e..5c16c33b 100644 --- a/nornir/core/filter.py +++ b/nornir/core/filter.py @@ -68,39 +68,43 @@ def __eq__(self, other: object) -> bool: return self.__class__ == other.__class__ and self.filters == other.filters @staticmethod - def _verify_rules(data: Any, rule: List[str], value: Any) -> bool: - if len(rule) > 1: - try: - return F._verify_rules(data.get(rule[0], {}), rule[1:], value) - except AttributeError: - return False + def _verify_rule(data: Any, rule: str, value: Any) -> bool: + operator = "__{}__".format(rule) + if hasattr(data, operator): + return getattr(data, operator)(value) is True - elif len(rule) == 1: - operator = "__{}__".format(rule[0]) - if hasattr(data, operator): - return getattr(data, operator)(value) is True + if hasattr(data, rule): + if callable(getattr(data, rule)): + return bool(getattr(data, rule)(value)) + return bool(getattr(data, rule) == value) + + if rule == "in": + return bool(data in value) - if hasattr(data, rule[0]): - if callable(getattr(data, rule[0])): - return bool(getattr(data, rule[0])(value)) - return bool(getattr(data, rule[0]) == value) + if rule == "any": + if isinstance(data, list): + return any(x in data for x in value) + return any(x == data for x in value) - if rule == ["in"]: - return bool(data in value) + if rule == "all": + if isinstance(data, list): + return all(x in data for x in value) - if rule == ["any"]: - if isinstance(data, list): - return any(x in data for x in value) - return any(x == data for x in value) + # it doesn't make sense to check a single value meets more than one case + return False - if rule == ["all"]: - if isinstance(data, list): - return all(x in data for x in value) + return bool(data.get(rule) == value) - # it doesn't make sense to check a single value meets more than one case + @staticmethod + def _verify_rules(data: Any, rule: List[str], value: Any) -> bool: + if len(rule) > 1: + try: + return F._verify_rules(data.get(rule[0], {}), rule[1:], value) + except AttributeError: return False - return bool(data.get(rule[0]) == value) + elif len(rule) == 1: + return F._verify_rule(data, rule[0], value) else: raise Exception("I don't know how I got here:\n{}\n{}\n{}".format(data, rule, value)) diff --git a/pyproject.toml b/pyproject.toml index 8c8ae451..6d062557 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -191,7 +191,7 @@ skip-magic-trailing-comma = false line-ending = "auto" [tool.ruff.lint.mccabe] -max-complexity = 12 +max-complexity = 10 [tool.ruff.lint.pylint]