Variable Interpolation - status of PEP 215

Fredrik Lundh fredrik at pythonware.com
Thu Jun 20 03:50:24 EDT 2002


"Ganesan R" wrote:
> I am a relative newbie to Python. I have a reasonably good perl background
> (don't worry I am not about to start a language flame war :-), and one of
> the things I really miss is variable interpolation in strings.

now, given that Python is a real programming language, you can
get all the interpolation you'll ever need with a few lines of code
in a utility module.

just cut and paste (this works with Python 2.0 and newer):

import sre, sys

# match $$ and $var and ${var}
_dosub = sre.compile(r'\$(?:\$|(\w+)|\{([^}]*)\})').sub

def expandvars(string, vars):
    # expand $var and ${var}; leave unknowns as is
    def repl(m, vars=vars):
        if not m.lastindex:
            return "$"
        try:
            return vars[m.group(m.lastindex)]
        except (KeyError, NameError):
            return m.group(0)
    return _dosub(repl, string)

def replacevars(string, vars):
    # same as expandvars, but raises an exception if variable not known
    def repl(m, vars=vars):
        if not m.lastindex:
            return "$"
        return vars[m.group(m.lastindex)]
    return _dosub(repl, string)

def replacevars_from_scope(string):
    # same as replacevars, but gets the variables from caller's current scope
    frame = sys._getframe(1)
    mapping = frame.f_globals.copy()
    mapping.update(frame.f_locals)
    return replacevars(string, mapping)

# (etc)

#
# try it out...

s = '${name} was born in ${country}'
print replacevars(s, {'name': 'Guido', 'country': 'the Netherlands'})

name = 'Barry'
country = 'the USA'
print replacevars_from_scope(s)

# (etc)

# </F>





More information about the Python-list mailing list