Skip to content

Instantly share code, notes, and snippets.

@ccaseiro
Forked from wilvk/actionable_dict.py
Created July 14, 2022 18:49
Show Gist options
  • Select an option

  • Save ccaseiro/2072e7fbef7e1a94e27d411e87dd5011 to your computer and use it in GitHub Desktop.

Select an option

Save ccaseiro/2072e7fbef7e1a94e27d411e87dd5011 to your computer and use it in GitHub Desktop.

Revisions

  1. @wilvk wilvk created this gist Dec 22, 2018.
    37 changes: 37 additions & 0 deletions actionable_dict.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    class ActionableDict(dict):

    parent = None

    def __init__(self, initial_dict, parent = None):
    self.parent = parent
    for key, value in initial_dict.items():
    if isinstance(value, dict):
    initial_dict[key] = ActionableDict(value, self)
    super().__init__(initial_dict)

    def __setitem__(self, item, value):
    if isinstance(value, dict):
    _value = ActionableDict(value, self)
    else:
    _value = value
    print("You are changing the value of {} to {}!!".format(item, _value))
    self._traverse_parents()
    super().__setitem__(item, _value)

    def _traverse_parents(self):
    test_item = self
    parent_keys = [ next(iter(self)) ]
    while(hasattr(test_item, 'parent') and test_item.parent != None):
    for key, value in test_item.parent.items():
    if value == test_item:
    parent_keys.append(key)
    test_item = test_item.parent
    print("parent keys: " + str(parent_keys[::-1]))

    if __name__ == "__main__":
    test = ActionableDict({'a': {'b': 6 }})
    print("---")
    test['b'] = { 'c': { 'd': 3} }
    print("---")
    test['b']['c']['d'] = 4
    print("resultant dict: " + str(test))