[Python-ideas] template strings
Yury Selivanov
yselivanov.ml at gmail.com
Wed Aug 19 22:28:58 CEST 2015
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.
Yury
More information about the Python-ideas
mailing list