From ea3b6e955f89a4cfe00c49c3c22229a2b72fd168 Mon Sep 17 00:00:00 2001 From: allegroai <> Date: Sun, 13 Feb 2022 19:32:22 +0200 Subject: [PATCH] Optimize nested_get() --- apiserver/bll/project/project_bll.py | 8 ++++---- apiserver/utilities/dicts.py | 7 ++----- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/apiserver/bll/project/project_bll.py b/apiserver/bll/project/project_bll.py index fc6d634..6846608 100644 --- a/apiserver/bll/project/project_bll.py +++ b/apiserver/bll/project/project_bll.py @@ -499,8 +499,8 @@ class ProjectBLL: ) -> Dict[str, dict]: return { section: { - status: nested_get(a, (section, status), 0) - + nested_get(b, (section, status), 0) + status: nested_get(a, (section, status), default=0) + + nested_get(b, (section, status), default=0) for status in set(a.get(section, {})) | set(b.get(section, {})) } for section in set(a) | set(b) @@ -535,9 +535,9 @@ class ProjectBLL: def get_status_counts(project_id, section): return { - "total_runtime": nested_get(runtime, (project_id, section), 0), + "total_runtime": nested_get(runtime, (project_id, section), default=0), "status_count": nested_get( - status_count, (project_id, section), default_counts + status_count, (project_id, section), default=default_counts ), } diff --git a/apiserver/utilities/dicts.py b/apiserver/utilities/dicts.py index cb5e55a..8d6cc2d 100644 --- a/apiserver/utilities/dicts.py +++ b/apiserver/utilities/dicts.py @@ -37,15 +37,12 @@ def deep_merge(source: dict, override: dict) -> dict: def nested_get( dictionary: Mapping, - path: Union[Sequence[str], str], + path: Sequence[str], default: Optional[Union[Any, Callable]] = None, ) -> Any: - if isinstance(path, str): - path = [path] - node = dictionary for key in path: - if key not in node: + if not node or key not in node: if callable(default): return default() return default