recursively expanding $references in dictionaries

Alia Khouri alia_khouri at yahoo.com
Mon Jul 23 03:28:25 CEST 2007


Ok. I've reached a nice little conclusion here. Time to go to bed, but
before that I thought I'd share the results (-;

I can now read a yaml file which natively produces a dict tree and
convert it into an object tree with attribute read/write access, dump
that back into a readable yaml string, and then expand references
within that using cheetah in a very nifty self-referential way.*

(see: http://pyyaml.org/wiki/PyYAML) and cheetah templates (http://
www.cheetahtemplate.org/)

Enjoy!


AK


<code below>

from Cheetah.Template import Template
from pprint import pprint
import yaml

class Object(dict):
    def __getattr__(self, name):
        if name in self: return self[name]
        #~ if name in self.__dict__: return getattr(self, name)
    def __setattr__(self, name, value):
        self[name] = value

def getTree(tree, to_dict=False):
    _tree = Object() if not to_dict else dict()
    def recurse(targetDict, sourceDict):
        for key, value in sourceDict.items():
            if isinstance(value, dict):
                value = Object(value) if not to_dict else dict(value)
                new_target = targetDict.setdefault(key, value)
                recurse(new_target, value)
            else:
                targetDict[key] = value
    recurse(_tree, tree)
    return _tree


config  = '''
app:
  name: appname
  copyright: me.org 2007

dir:
  src: /src/$app.name
'''
# from yml dict tree to obj tree
root = getTree(yaml.load(config))
print root
print
assert root.app.name == root.app['name']
root.app.name = "the_monster"

# from obj tree to dict tree
root = getTree(root, to_dict=True)

# from dict tree to yaml string
s = yaml.dump(root)
print s

# use cheetah templates to expand references
print str(Template(s, searchList=[root]))




More information about the Python-list mailing list