by kstrauser · 1y ago · 0 comments
>>> template = 'Hello, {name}'
>>> template.format(name='Bob')
'Hello, Bob'
Until this, there wasn't a way to use f-strings formatting without interpolating the results at that moment: >>> template = f'Hello, {name}'
Traceback (most recent call last):
File "<python-input-5>", line 1, in <module>
template = f'Hello, {name}'
^^^^
NameError: name 'name' is not defined
It was annoying being able to use f-strings almost everywhere, but str.format in enough odd corners that you have to put up with it.The point of evaluation of the expressions is the same.
>>> template = t'Hello, {name}'
is still an error if you haven't defined name.BUT the result of a t-string is not a string; it is a Template which has two attributes:
strings: ["Hello, ", ""]
interpolations: [name]
So you can then operate on the parts separately (HTML escape, pass to SQL driver, etc.).There is an observation that you can use `lambda` inside to delay evaluation of an interpolation, but I think this lambda captures any variables it uses from the context.
Actually lambda works fine here
>>> name = 'Sue'
>>> template = lambda name: f'Hello {name}'
>>> template('Bob')
'Hello Bob'Bummer. This could have been so useful:
statement_endpoint: Final = "/api/v2/accounts/{iban}/statement"
(Though str.format isn’t really that bad here either.)There are a lot of existing workarounds in the discussions if you are interested enough in using it, such as using lambdas and t-strings together.
statement_endpoint: Final = "/api/v2/accounts/{iban}/statement".format
(it's likely that typecheckers suck at this like they suck at everything else though)That's correct, they don't. Evaluation of t-string expressions is immediate, just like with f-strings.
Since we have the full generality of Python at our disposal, a typical solution is to simply wrap your t-string in a function or a lambda.
(An early version of the PEP had tools for deferred evaluation but these were dropped for being too complex, particularly for a first cut.)
Kinda messy PEP, IMO, I'm less excited by it than I'd like to be. The goal is clear, but the whole design feels backwards.
def my_template(name: str) -> Template:
return t"Hello, {name}" >>> template = lambda name: f'Hello {name}'
>>> template('Bob')