I'm working on a parser library for substituting strings in dictionaries, with things like globals etc. Wanting to get opinions on the direction I'm taking and where I can improve the script. This currently works
class DictParser(object):
def __init__(self, dictionary):
self.working_dict = dictionary
def __traverse(self, obj, callback=None):
if isinstance(obj, dict):
return {k: self.__traverse(v, callback) for k, v in obj.items()}
elif isinstance(obj, list):
return [self.__traverse(elem, callback) for elem in obj]
else:
if not callback:
return obj
else:
return callback(obj)
def replace_with_global_var(self, pattern):
pattern_variable = re.compile(pattern)
def substitute(x):
if x.group(1) in globals():
return globals()[x.group(1)]
else:
raise IndexError('Missing Global: %s' % x.group(1))
def transformer(item):
if isinstance(item, str):
return pattern_variable.sub(substitute, item)
else:
return item
self.working_dict = self.__traverse(self.working_dict, callback=transformer)
def retrieve(self):
return self.working_dict
Usage:
a = 'blah'
my_dict = {
'test': '((a))',
'another': 'my ((a)) test',
'nested': {
'child': 'here is ((a)) ((a))'
},
'boo': 1,
'test': False
}
d = DictParser(my_dict)
d.replace_with_global_var(r'\(\((.+?)\)\)')
print(d.retrieve())
This was a reasonably quick hack together, tried using repl so I could print the d variable directly but didn't quite work out.