[Python-ideas] Draft PEP on string interpolation

Paul Moore p.f.moore at gmail.com
Mon Aug 24 13:35:44 CEST 2015


On 24 August 2015 at 10:53, Nick Coghlan <ncoghlan at gmail.com> wrote:
>> 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.

I'm once again losing the thread of all the variations being proposed.

As a reality check, is the expectation that something like the
following will still be possible:

print(f"Iteration {n}: Duration {end-start} seconds")

This is as an improvement over the two current approaches:

print("Iteration {}: Duration {} seconds".format(n, end-start))
print("Iteration %s: Duration %s seconds" % (n, end-start))

because it's less verbose than the former, and less punctuation-heavy
(and old-fashioned ;-)) than the latter.

Explicit str() calls or temporary variables or anything like that are
no improvement over the current options. Of course they may offer more
advanced features, but let's not lose the 80% case for the sake of the
20% (that's actually more like 95-5, to be honest).

Paul


More information about the Python-ideas mailing list