We have str.format(), so where is str.template()?

We have:

what = "answer"
value = 42
f"The {what} is {value}."
==> 'The answer is 42.'

And we have:

values = { "what": "answer", "value": 42 }
"The {what} is {value}".format(values)
==> 'The answer is 42.'

We also have:

what = "answer"
value = 42
t"The {what} is {value}."
==> Template(strings=('The ', ' is ', '.'), interpolations=(Interpolation('answer', 'what', None, ''), Interpolation(42, 'value', None, '')))

But I have not been able to find any way to do something like:

values = { "what": "answer", "value": 42 }
"The {what} is {value}".template(values)
==> Template(strings=('The ', ' is ', '.'), interpolations=(Interpolation('answer', 'what', None, ''), Interpolation(42, 'value', None, '')))

The only way around this that has occurred to me is, frankly, pretty ugly (I generally dislike eval):

def template(source, vars):
    return eval('t' + repr(source), globals={}, locals=vars)

This all seems like a most un-Pythonic lack of orthogonality. I have done some searching and there does not seem to be any discussion about this (at least, none I could find).

Is there a good reason for not having a str.tempate() method? If not, I would like to propose adding one (and am willing to type up a formal PEP to this end).

2 Likes

The python solution is to copy the above function. IMO this is complex enough that it should be in string.templatelib, but I don’t think there is a common enough usecase for this to be a method on string objects.

2 Likes

str.format was added several versions before f-strings. The latter has mostly replaced use of the former. I suspect that str.template would never be used much. Strict orthogonality by itself is not required in python design.

FWIW I personally still use str.format quite a bit as a built-in, configurable string template for systems that can’t easily install third-party modules such as jinja2. Neither f-string nor t-string can serve as an actual template (which is a bit sad for t-string because of its name). It’s also great as a mapper function for rendering a list of dicts into formatted strings.

That said, I’m -0 on the OP’s proposal until the OP can provide good real-world use cases for it because I can’t think of a good one either.

1 Like