[Python-ideas] Draft PEP on string interpolation

Nick Coghlan ncoghlan at gmail.com
Mon Aug 24 11:53:59 CEST 2015


On 24 August 2015 at 17:28, Petr Viktorin <encukou at gmail.com> wrote:
> 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().

Another option would be to put the default rendering in __format__,
and let __str__ fall through to __repr__. That way str(template)
wouldn't render the template, but format(template) would.

> 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.

Yeah, that's fair. I added the __iter__ to make some of the examples
prettier, but it probably isn't worth the loss of future flexibility.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list