[Python-ideas] template strings

Yury Selivanov yselivanov.ml at gmail.com
Mon Aug 17 22:13:14 CEST 2015


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).


Some use cases
--------------

1. i18n and PEP 501

Pros:

- No global __interpolate__ builtin (hard to have more than one i18n lib 
in one
project)

- Easy to restrict the exact interpolation syntax:

    class T:
        def __format_str__(self, string, values_map):
            for name in values_map:
                if not name.isidentifier():
                    raise ValueError('i18n string only support ...')
            ...
    _ = T()

    _'spam: {spam and ham}' # will raise a ValueError

    -'spam: {ham}' # will be interpolated

- Can have more than one i18n lib:

a.py:

    from lib1 import _
    print(_'...')

b.py:

    from gettext import gettext as _
    print(_'...')


2. SQL queries

Being able to write

    db.query(db'SELECT * FROM users WHERE name = {name} AND ...')

instead of

     db.query('SELECT * FROM users WHERE name = {} AND ...', name)

3. Automatic HTML escaping (see [2] for __markup__ protocol, for instance):

     name = '<script>'
     html'<b>{name}</b>'

will produce

     '<b><script></b>'


Thanks,
Yury


[1] 
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings
[2] http://genshi.edgewall.org



More information about the Python-ideas mailing list