←back to thread

620 points tambourine_man | 1 comments | | HN request time: 0.219s | 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 #
1. zahlman ◴[] No.43757222[source]
>But if there aren't any, it's strange that the design requires every Template processing function to include this boilerplate

Other replies gave examples of other use cases. But the neat thing about Python is that you don't need to "include this boilerplate" for the common cases. It can be wrapped up in a decorator (which could be included in `templatelib`). Or, as you say, in a method on the Template class.

I think I'd implement it as a generator, calling `process_value` (defaulting to `str`) on the Interpolations, so that the caller can still do more with the results (or just `''.join` them).

But these are separate considerations; nothing prevents implementing them later, or indeed adding them to the implementation before the 3.14 release.