yet another recipe on string interpolation

Michele Simionato michele.simionato at gmail.com
Thu Nov 4 01:19:43 EST 2004


I was playing with string.Template in Python 2.4 and I came out with the
following recipe:

import sys
from string import Template

def merge(*dictionaries):
    """Merge from right (i.e. the rightmost dictionary has the precedence)."""
    merg = {}
    for d in dictionaries:
        merg.update(d)
    return merg

def interp(s, dic = None):
    if dic is None: dic = {} 
    caller = sys._getframe(1)
    return Template(s) % merge(caller.f_globals, caller.f_locals, dic)

language="Python"
print interp("My favorite language is $language.")

Do you have any comments? Suggestions for improvements?

  Michele Simionato



More information about the Python-list mailing list