[Python-ideas] template strings

Yury Selivanov yselivanov.ml at gmail.com
Thu Aug 20 03:38:10 CEST 2015
On 2015-08-19 4:28 PM, Yury Selivanov wrote:
> On 2015-08-19 3:11 PM, Eric V. Smith wrote:
>> On 08/19/2015 02:11 PM, Eric V. Smith wrote:
>>> On 08/17/2015 04:13 PM, Yury Selivanov wrote:
>>>> In ECMAScript 6 there is a concept of Template Strings [1]. What if 
>>>> we add
>>>> something similar in Python?
>>>>
>>>> Some key ideas
>>>> --------------
>>>>
>>>> 1. Template Strings (TS) will be built on top of PEP 498 machinery (if
>>>> accepted).
>>>>
>>>> 2. The syntax will match the following:
>>>>
>>>>      {python identifier}{optional whitespace}{string literal}
>>>>
>>>> where "python identifier" can be any valid python name *except* r, 
>>>> u, b,
>>>> or f.
>>>>
>>>> Some examples of valid TS:
>>>>
>>>>     ##
>>>>     _'foo {bar}'
>>>>
>>>>     ##
>>>>     sql = db.escape
>>>>     sql """
>>>>        SELECT ... FROM ...
>>>>     """
>>>>
>>>>     ##
>>>>     from framework import html
>>>>     html"""
>>>>        <div class="caption">
>>>>          {caption}
>>>>        </div>
>>>>     """
>>>>
>>>> 3. A special magic method will be added: __format_str__(string,
>>>> values_map).
>>>>
>>>> For instance,
>>>>
>>>>      b = 10
>>>>      print(_'something { b+1 }')
>>>>
>>>> will be equivalent to
>>>>
>>>>      b = 10
>>>>      print(_.__format_str__('something { b+1 }', {' b+1 ': b + 1}))
>>>>
>>>> (or however PEP 498 will be implemented).
>>> I'm not convinced this is a great idea. It's almost like it wants to be
>>> a way to pass in ASTs to functions, but only for the limited case of
>>> f-string expressions. Maybe that's as far as we'll ever want to go, and
>>> this is good enough.
>>>
>>> As you say, it would allow easy implementation of i18n on top of PEP 
>>> 498.
>>>
>>> If we do go this route, we should reserve some names for Python's own
>>> use in the lexer. For example, if this proposal were in place before we
>>> added bytes strings, there would be no easy way to add them.
>> Also, how would this interact with raw strings? For PEP 498, I have:
>>>>> f'\n{0}'
>> '\n0'
>>>>> fr'\n{0}'
>> '\\n0'
>>
>> How would you have raw template strings?
>
> I don't think we can have raw template strings
> (and template byte strings, fwiw).  It's a separate
> concept, not composable with other string types.
>


Actually, we can approach raw strings and even bytes by
checking what methods are available on the object, i.e.:

     res = o'foo \n{bar}'

will be semantically equivalent to:

     try:
         meth = o.__format_rstr__
     except AttributeError:
         res = o.__format_str__('foo \n{bar}', bar=bar)
     else:
         res = meth('foo \\n{bar}', bar=bar)

Yury


More information about the Python-ideas mailing list