[Python-Dev] PEP 292, Simpler String Substitutions

Fredrik Lundh fredrik@pythonware.com
Wed, 19 Jun 2002 12:01:36 +0200


duncan wrote:

> What I really don't understand is why there is such pressure to get an =

> alternative interpolation added as methods to str & unicode rather =
than=20
> just adding an interpolation module to the library?
> e.g.
>=20
> from interpolation import sub
> def birth(self, name):
>     country =3D self.countryOfOrigin['name']
>     return sub('${name} was born in ${country}', vars())

that's too easy, of course ;-)

especially since someone has already added such a method, a
long time ago (os.path.expandvars).

and there's already an interpolation engine in there; barry's loop,
join and format stuff can replaced with a simple callback, and a
call to sre.sub with the right pattern:

    def sub(string, mapping):
        def repl(m, mapping=3Dmapping):
            return mapping[m.group(m.lastindex)]
        return sre.sub(A_PATTERN, repl, string)

(if you like lambdas, you can turn this into a one-liner)

maybe it would be sufficient to add a number of "right patterns"
to the standard library...

</F>