←back to thread

620 points tambourine_man | 1 comments | | HN request time: 0.215s | source
Show context
pansa2 ◴[] No.43750383[source]
> t-strings evaluate to a new type, `string.templatelib.Template`

> To support processing, `Template`s give developers access to the string and its interpolated values before* they are combined into a final string.*

Are there any use-cases where processing a Template involves something other than (i) process each value, then (ii) recombine the results and the string parts, in their original order, to produce a new string? In other words, is the `process_template` function ever going to be substantially different from this (based on `pig_latin` from the article)?

    def process_template(template: Template) -> str:
        result = []
        for item in template:
            if isinstance(item, str):
                result.append(item)
            else:
                result.append(process_value(item.value))
        return "".join(result)
I haven't seen any examples where the function would be different. But if there aren't any, it's strange that the design requires every Template processing function to include this boilerplate, instead of making, say, a `Template.process` method that accepts a `process_value` function.
replies(3): >>43750478 #>>43753470 #>>43757222 #
WorldMaker ◴[] No.43753470[source]
Templates don't even have to be processed into a string. The article shows an example where the Template is processed into an HTML mini-DOM. It's maybe not obvious because the DOM object is immediately stringified to show sample output, but you could imagine manipulating the DOM object in a few more steps before stringifying it, or maybe you are running in WASM in a browser and using that mini-DOM directly as a Virtual DOM passed to JS to work with.

Also, in addition to the other SQL example using "?" to fill in the "holes" for parameters in an SQL friendly way, some DBs also support named parameters, so the "hole" in the string form might be naively replaced with something like `f"@{item.expression}"` and that also forms the key in a dict to pass as parameters. (You'd want to make sure that the expression inside the template is useful as a parameter name, and not something more exotic like {1 + 3} or {thing for thing in some_list}, in which cases you are probably auto-assigning some other parameter name.)

replies(1): >>43754703 #
1. pauleveritt ◴[] No.43754703[source]
Nearly everything you just described is being worked on. It's amazing how accurately you have described it. We hope to demo and explain at PyCon US.