Optimize nested_get()

This commit is contained in:
allegroai 2022-02-13 19:32:22 +02:00
parent 843450bb9b
commit ea3b6e955f
2 changed files with 6 additions and 9 deletions

View File

@ -499,8 +499,8 @@ class ProjectBLL:
) -> Dict[str, dict]: ) -> Dict[str, dict]:
return { return {
section: { section: {
status: nested_get(a, (section, status), 0) status: nested_get(a, (section, status), default=0)
+ nested_get(b, (section, status), 0) + nested_get(b, (section, status), default=0)
for status in set(a.get(section, {})) | set(b.get(section, {})) for status in set(a.get(section, {})) | set(b.get(section, {}))
} }
for section in set(a) | set(b) for section in set(a) | set(b)
@ -535,9 +535,9 @@ class ProjectBLL:
def get_status_counts(project_id, section): def get_status_counts(project_id, section):
return { 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": nested_get(
status_count, (project_id, section), default_counts status_count, (project_id, section), default=default_counts
), ),
} }

View File

@ -37,15 +37,12 @@ def deep_merge(source: dict, override: dict) -> dict:
def nested_get( def nested_get(
dictionary: Mapping, dictionary: Mapping,
path: Union[Sequence[str], str], path: Sequence[str],
default: Optional[Union[Any, Callable]] = None, default: Optional[Union[Any, Callable]] = None,
) -> Any: ) -> Any:
if isinstance(path, str):
path = [path]
node = dictionary node = dictionary
for key in path: for key in path:
if key not in node: if not node or key not in node:
if callable(default): if callable(default):
return default() return default()
return default return default