Easy "here documents" ??

Jerry Sievers jerry at jerrysievers.com
Sun Dec 19 16:28:13 CET 2004

jimhill at swcp.com (Jim Hill) writes:

> I've done some Googling around on this and it seems like creating a here
> document is a bit tricky with Python.  Trivial via triple-quoted strings
> if there's no need for variable interpolation but requiring a long, long
> formatted arglist via (%s,%s,%s,ad infinitum) if there is.  So my
> question is:
> Is there a way to produce a very long multiline string of output with
> variables' values inserted without having to resort to this wacky
> """v = %s"""%(variable)
> business?

Hmmmmmm, by using the %(varname)[dsf...] with vars(), locals(),
globals(), someDict, et al, a little messy but not terribly difficult.

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

To wit;

# feed this thing with one or more dicts, in order of decreasing
#search priority.
class multiDict:
    def __init__(self, *dicts):
        self.dicts = dicts
    def __getitem__(self, key):
        for dict in self.dicts:
            if dict.has_key(key):
                return dict[key]

globalvar = 100

def foo():
    localvar = 200

    print """
""" % multiDict(globals(), locals())



Now all else that we need to make this pretty would be macros, a la
cpp m4 or similar

define(`VARS', `multiDict(locals(), globals())')

print "..." % VARS

You get the idea.

Jerry Sievers   305 854-3001 (home)     WWW ECommerce Consultant
                305 321-1144 (mobile	http://www.JerrySievers.com/

More information about the Python-list mailing list