On Mon, Aug 24, 2015 at 3:24 AM, Steven D'Aprano
On Sun, Aug 23, 2015 at 08:35:17PM -0400, Eric V. Smith wrote:
I think the string interpolation object is interesting. It's basically what Petr Viktorin and Chris Angelico discussed and suggested here: https://mail.python.org/pipermail/python-ideas/2015-August/035303.html.
Are you sure that's the right URL? It seems only barely relevant to me. It has Chris replying to Petr, but it's a vague suggestion of a "quantum string interpolation" (Chris' words) with no details. He asks:
"How hard would this be to implement? Something that isn't a string, retains all the necessary information, and then collapses to a string when someone looks at it?"
I looked ahead a dozen or two posts, and can't see any further discussion. Have I missed something?
Actually, it's I who missed something – replied from a phone, and sent the reply to Chris only instead of to the list. And that killed further discussion, it seems. My answer was:
Not too hard, but getting the exact semantics right could be tricky. It's probably something the language/stdlib should enable, rather than having it in the stdlib itself.
This seems roughly in line with what Guido was saying earlier. (Am I misrepresenting your words, Guido?) I thought a bit about what's bothering me with this idea, and I realized I just don't like that "quantum effect" – collapsing when something looks at a value. All the parts up to that point sound OK, it's the str() that seems too magical to me. We could require a more explicit function, not just str(), to format the string:
t0=1; t1=2; n=3 template = i"Peeled {n} onions in {t1-t0:.2f}s" str(template) types.InterpolationTemplate(template="Peeled {n} onions in {t1-t0:.2f}s", fields=(('Peeled', 0, 'n', '', ''), ...), values=(3, 1)) format_template(template) # (or make it a method?) 'Peeled 3 onions in 1s'
This no longer feels "too magic" to me, and it would allow some experimentation before (if ever) InterpolationTemplate grows a more convenient str(). Compared to f-strings, all this is doing is exposing the intermediate structure. (What the "i" really stands for is "internal".) Now f-strings would be just i-strings with a default formatter applied. And, InterpolationTemplate should only allow attribute access (i.e. it shouldn't be structseq). That way the internal structure can be changed later, and the "old" attributes can be synthetized on access.