Easy "here documents" ??

Fredrik Lundh fredrik at pythonware.com
Sun Dec 19 16:46:34 CET 2004

Jerry Sievers wrote:

> It gets uglier though if you want to do this from inside a function
> and have variables from more than one scope interpolated.  For that
> you need something that can treat a series of dicts as one.If there's
> built in functionality in Python for this, I haven't discovered it
> yet.

you use them all the time: plain old instance objects...

here's a rather horrid piece of code that turns a list of dictionaries
into a single object the automatically searches the dictionary chain
when you ask for attributes (use getattr for non-standard keys).

def flatten_dicts(*dicts):
    root = None
    for dict in dicts:
        class wrapper: pass
        if root:
            wrapper.__bases__ = (root,)
        wrapper.__dict__ = dict
        root = wrapper
    return wrapper()

obj = flatten_dicts(d1, d2, d3)


More information about the Python-list mailing list