Trivial string substitution/parser

Duncan Booth duncan.booth at invalid.invalid
Mon Jun 18 09:53:52 CEST 2007

Josiah Carlson <josiah.carlson at> wrote:

> Samuel wrote:
>> On Sun, 17 Jun 2007 11:00:58 +0000, Duncan Booth wrote:
>>> The elegant and lazy way would be to change your specification so
>>> that $ characters are escaped by $$ not by backslashes. Then you can
>>> write: 
>>>>>> from string import Template
>>>>>> ...
>> Thanks, however, turns out my specification of the problem was 
>> incomplete: In addition, the variable names are not known at
>> compilation time.
> You mean at edit-time.
> >>> t.substitute(variable1="hello", variable2="world")
> Can be replaced by...
> >>> t.substitute(**vars)
> per the standard **kwargs passing semantics.

You don't even need to do that. substitute will accept a dictionary as a 
positional argument:


If you use both forms then the keyword arguments take priority.

Also, of course, vars just needs to be something which quacks like a dict: 
it can do whatever it needs to do such as looking up a database or querying 
a server to generate the value only when it needs it, or even evaluating 
the name as an expression; in the OP's case it could call get_variable.

Anyway, the question seems to be moot since the OP's definition of 'elegant 
and lazy' includes regular expressions and reinvented wheels.

... and in another message Graham Breed wrote:
>     def get_variable(varname):
>         return globals()[varname]

Doesn't the mere thought of creating global variables with unknown names 
make you shudder?

More information about the Python-list mailing list