Easy "here documents" ??

Nick Craig-Wood nick at craig-wood.com
Sun Dec 19 18:30:02 CET 2004

Jim Hill <jimhill at swcp.com> wrote:
>  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)

I prefer this

   >>> amount = 1
   >>> cost = 2.0
   >>> what = 'potato'
   >>> print """\
   ... I'll have %(amount)s %(what)s
   ... for $%(cost)s please""" % locals()
   I'll have 1 potato
   for $2.0 please

Its almost as neat as perl / shell here documents and emacs parses """
strings properly too ;-)

Note the \ after the triple quote so the first line is flush on the
left, and the locals() statement.  You can use globals() or a
dictionary you might have lying around instead which is much more
flexible than perl.  You can even pass self.__dict__ if you are in a
class method so you can access attributes.

   >>> class A: pass
   >>> a=A()
   >>> a.amount=10
   >>> a.what="rutabaga"
   >>> a.cost=17.5
   >>> print """\
   ... I'll have %(amount)s %(what)s
   ... for $%(cost)s please""" % a.__dict__
   I'll have 10 rutabaga
   for $17.5 please

Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick

More information about the Python-list mailing list