recursively expanding $references in dictionaries

Alia Khouri alia_khouri at
Sun Jul 22 21:28:25 EDT 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: and cheetah templates (http://



<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)
                targetDict[key] = value
    recurse(_tree, tree)
    return _tree

config  = '''
  name: appname
  copyright: 2007

  src: /src/$
# from yml dict tree to obj tree
root = getTree(yaml.load(config))
print root
assert ==['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