3 ms·
> If a single interpolation is expensive to evaluate, it can be explicitly wrapped in a lambda in the template string literal I’m having trouble understanding
by mortar 1y ago
> If a single interpolation is expensive to evaluate, it can be explicitly wrapped in a lambda in the template string literal
I’m having trouble understanding this - Can someone please help out with an example use case for this? It seems like before with an f string we had instant evaluation, now with a t string we control the evaluation, why would we further delay evaluation - Is it just to utilise running a function on a string first (i.e. save a foo = process(bar) line?)
- smitty1e 1y agoSo that you can calculate the string in A.py and then use it over in B.py .
- cstrahan 1y ago> It seems like before with an f string we had instant evaluation, now with a t string we control the evaluation You don't completely control the evaluation. From the PEP: > Template strings are evaluated eagerly from left to right, just like f-strings. This means that interpolations are evaluated immediately when the template string is processed, not deferred or wrapped in lambdas. If one of the things you are interpolating is, as a silly example, an invocation of a slow recursive fibonacci function, the template string expression itself (resulting in a Template object) will take a long while to evaluate.
- mortar 1y ago> the template string expression itself (resulting in a Template object) will take a long while to evaluate Are you saying that calling: template = t”{fib_slow()}” Will immediately run the function, as opposed to when the __str__ is called (or is it because of __repr__?) - Apparent I might just have to sit down with the code and grok it that way, but thanks for helping me understand!
- davepeck 1y agoYes, fib_slow() will be evaluated immediately, just like it would be if you were using an f-string.
- zahlman 1y agoYes. Just like with f-strings, the call to `fib_slow()` is extracted at compile-time, and occurs eagerly at run-time. What t-strings offer over f-strings is the ability to control how the final string is put together from the calculated results. And the t-string doesn't have `__str__` - you have to explicitly pass it to a named formatting function to get a string. (There is `__repr__, but that's for debugging, of course.) So you can potentially reuse the same Template instance (created from the t-string) multiple times in different contexts to format the same information different ways.
- mortar 1y agoAwesome, that makes sense now - thanks all!