In the case you have got a string template that you do not want to fill with all variables at once, but you know you are going to put all of them in before printing it, there is a solution since Python 3.3.
The keyword is format_map. In the example of the official documentation there is almost this case, but not entirely, so here is my solution:
class Default(dict):
def __missing__(self, key):
return "{%s}" % key
You create a class that is derived from the dictionary that returns a string that is like a format string. To use less curly braces and to have the difference a bit clearer, I used the fprint style syntax.
Now you can use format_map
to fill in only some variables.
>>> template_string = '{name} was born in {country}'
>>> template_string = template_string.format_map(Default(name='Guido'))
>>> template_string
'Guido was born in {country}'
And later on
>>> template_string = template_string.format_map(Default(country='the Netherlands'))
>>> template_string
'Guido was born in the Netherlands'
.