[Python-ideas] Draft PEP on string interpolation

Nick Coghlan ncoghlan at gmail.com
Sun Aug 23 06:09:58 CEST 2015


On 23 August 2015 at 11:37, Nick Coghlan <ncoghlan at gmail.com> wrote:
> However, I'm now coming full circle back to the idea of making this a
> string prefix, so that would instead look like:
>
>     subprocess.call($"echo $filename")
>
> The trick would be to make interpolation lazy *by default* (preserving
> the triple of the raw template string, the parsed fields, and the
> expression values), and put the default rendering in the resulting
> object's *__str__* method.

Indeed, after working through this latest change, I ended up back
where I started from a syntactic perspective, with a proposal for
i(nterpolated)-strings rather than f(ormatted)-strings:
https://www.python.org/dev/peps/pep-0501/

With appropriate modifications to subprocess.call, the proposal would
then enable us to write a *safe* shell command interpolation as:

    subprocess.call(i"echo $filename")

The essential change relative to PEP 498 is to make it so that i"echo
$filename" doesn't produce a string directly. Rather, it would produce
an interpolation template as a first class object, holding:

* a reference to the raw template
* a compile time constant tuple-of-tuples describing the parsed fields
* a tuple with the calculated field values

The default rendering semantics would then live in
types.InterpolationTemplate.__str__, rather than being applied
implicitly at the point of definition.

The same underlying approach could also be used with the "{}"
substitution field syntax proposed in PEP 498, but I have some
concrete reasons for continuing to prefer $-based substitution:

* it makes the case of interpolating in single variables with str() as
simple as possible
* it's consistent with JavaScript/ES6 and Python+JavaScript is a more
common combination than Python+C#
* other common templating formats (including Django, Jinja2 and
Mozilla's l20n) collide on "{" and "}", but not on "$"
* it allows the raw template string to be more readily extracted and
used in an i18n message catalog

Regards,
Nick.

P.S. I vaguely recall seeing questions/suggestions along these lines
in the previous discussion threads, but don't recall the details. If
anyone did make a suggestion like this, please let me know, and I can
add your name to the Acknowledgements section.

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


More information about the Python-ideas mailing list