Skip to content

Commit

Permalink
Simlify _verify_rules and redunce max-complexity=10
Browse files Browse the repository at this point in the history
  • Loading branch information
ogenstad committed Jul 9, 2024
1 parent faecd6c commit a6335a5
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 26 deletions.
54 changes: 29 additions & 25 deletions nornir/core/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down

0 comments on commit a6335a5

Please sign in to comment.