Skip to content

Commit

Permalink
flat_dict_to_nested
Browse files Browse the repository at this point in the history
  • Loading branch information
sbromberger committed Mar 1, 2024
1 parent e8901ca commit 2896e6f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/clippy/backends/expression.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import json
from .serialization import ClippySerializable
from ..anydict import AnyDict
from ..utils import flat_dict_to_nested


from typing import Any

Expand Down Expand Up @@ -184,12 +186,19 @@ def _clear_subselectors(self):
delattr(self, subsel)
self.subselectors = set()

def _import_from_dict(self, d: AnyDict, merge: bool = False):
def _import_from_dict(self, flat_dict: AnyDict, merge: bool = False):
'''Imports subselectors from a dictionary.
If `merge = True`, do not clear subselectors first.'''
If `merge = True`, do not clear subselectors first.
Input dictionary has dot-delimited keys. This function uses
utils.flat_dict_to_nested to create the nested dictionary.
'''

d = flat_dict_to_nested(flat_dict)
# clear all children
if not merge:
self._clear_subselectors()

for name, subdict in d.items():
docstr = subdict.get('__doc__', '')
self._add_subselector(name, docstr)
Expand Down
26 changes: 26 additions & 0 deletions src/clippy/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""
Utility functions
"""

from .anydict import AnyDict
from .error import ClippyInvalidSelectorError


def flat_dict_to_nested(input_dict: AnyDict) -> AnyDict:
"""input dictionary has dot-delineated keys which are then parsed as subkeys.
That is: {'a.b.c': 5} becomes {'a': {'b': {'c': 5}}}
"""

output_dict: AnyDict = {}
for k, v in input_dict.items():
# k is dotted
if '.' not in k:
raise ClippyInvalidSelectorError("cannot set top-level selectors")

*path, last = k.split('.')
curr_nest = output_dict
for p in path:
curr_nest = output_dict.setdefault(p, {})

curr_nest[last] = v
return output_dict

0 comments on commit 2896e6f

Please sign in to comment.