←back to thread

620 points tambourine_man | 1 comments | | HN request time: 0.228s | source
Show context
haberman ◴[] No.43753017[source]
TL;DR: like f-strings, all {foo} expressions in the t-string are evaluated immediately, but instead of immediately concatenating everything into a single result string, the t-string evaluation returns a Template object that keeps the interpolation results and the surrounding strings separate. This lets subsequent logic decide whether the interpolation results need any special escaping before concatenating them with the strings around them.

In other words, t-strings are basically f-strings where the final concatenation is delayed. And indeed, you can trivially implement f-strings using t-strings by performing a simple, non-escaped concatenation step: https://peps.python.org/pep-0750/#example-implementing-f-str...

    f'...' -> str

    t'...' -> Template
    foo(t: Template) -> str
replies(1): >>43753056 #
dheera ◴[] No.43753056[source]
> This lets subsequent logic decide whether the interpolation results need any special escaping before concatenating them with the strings around them

This sounds like unnecessary fluff in what was supposed to be a simple language. I'm worried Python is turning into C++42 with 65535 ways to do one simple thing.

Why not just:

    f'SELECT * FROM `{esc(table)}` WHERE name = "{esc(name)}"'
Nice and simple.
replies(2): >>43753199 #>>43753265 #
pansa2 ◴[] No.43753199[source]
While your code is a valid alternative way to implement @haberman's description, the feature is actually much more flexible.

The "subsequent logic" has full access to the interpolation results and strings. Not only can it escape the results, it can do whatever it wants to them. It can also do whatever it wants to the strings, and then combine everything in any way it likes - it's not even necessary that the final result is a string.

replies(1): >>43754734 #
1. pauleveritt ◴[] No.43754734[source]
The other PEP example shows generating HTML attributes from a passed-in dictionary. HTML has a number of places where this is helpful, if you have original data.