In an existing python script I use vivification for work with dictionary of dictionaries.
class AutoVivification(dict):
"""Implementation of perl's autovivification feature."""
def __init__(self, *args, **kwargs):
super(AutoVivification, self).__init__(*args, **kwargs)
self.vivify = True
self.root = self
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
if not self.root.vivify:
raise
value = self[item] = type(self)()
value.root = self.root
return value
def unvivify(self):
self.vivify = False
def revivify(self):
self.vivify = True
def upgrade(self):
self.root = self
I would like apply this class for each dictionary in a dictionary of dictionaries. I thought to something like that:
def upvivification(dico):
"""Upgrade to the last autovivification version."""
if isinstance(dico, dict):
dico = AutoVivification(dico)
for k in dico:
if isinstance(dico[k], dict):
upvivification(dico[k])
But, indeed it is not working because the scope of this change is in the function and not global ... I do not see how to recursively make this change ...