[Python-ideas] Draft PEP on string interpolation

Nick Coghlan ncoghlan at gmail.com
Sat Aug 22 12:09:22 CEST 2015


On 22 August 2015 at 15:52, Mike Miller <python-ideas at mgmiller.net> wrote:
> Hi,
>
> I'm not sure that's the case any more, after reading the threads here this
> week there are numerous difficulties with trying to reconcile both use
> cases, and didn't get the feeling anyone has an elegant solution to them.
>
> We could implement f'' and (i'', aka t'') using either syntax of course,
> parsing variables from the string, but choosing translation with
> str.format() seems to cause several more issues than (string.Template() and
> a bit of inconsistency does).
>
> Which syntax would you rather have for translation?  (Knowing that you might
> give a different answer for standard interpolation.)

I just pushed a major rewrite of PEP 501 based on the discussions
since the initial version of that and PEP 498 went online:
https://www.python.org/dev/peps/pep-0501/

It switches to using a magic method and explicitly named interpolator
in interpolation expressions, with "!str" being the interpolator
reference for default string formatting. From a motivation
perspective, while i18n remains a consideration, more easily
addressing the risk of code injection attacks against naive use of
string interpolation when generating database queries, shell commands
or HTML pages now provides a stronger motivation making the
interpolation semantics extensible.

Writing a custom interpolator (including for i18n) becomes as simple as doing:

    @interpolator
    def my_interpolator(raw_template, parsed_fields, field_values):
        ...

While using it then looks like:

    result = !my_interpolator "This has $values $mixed into it"

(Similar to yield, it is proposed that interpolation expressions would
require parentheses when embedded inside a larger expression)

Cheers,
Nick.


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


More information about the Python-ideas mailing list