Easy "here documents" ??

Scott David Daniels Scott.Daniels at Acm.Org
Sun Dec 19 17:51:33 EST 2004


Nick Craig-Wood wrote:
> 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
>    >>> 

And if you enjoy building insecure stuff, try:

     def fix(text, globals_=None, locals=None, quote='"'):
         d = (globals_ or locals or globals()).copy()
         source = text.split(quote)
         source[1::2] = (str(eval(expr, d, locals or d))
			 for expr in source[1::2])
         return ''.join(source)


     amount = 1
     cost = 2.0
     what = 'potato'
     print fix("""I'll have "amount" "what"s
            for "'$%.2f' % cost"s please""", locals())


--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list