| 1 |
"""Support for template string literals (t-strings).""" |
| 2 |
|
| 3 |
t = t"{0}" |
| 4 |
Template = type(t) |
| 5 |
Interpolation = type(t.interpolations[0]) |
| 6 |
del t |
| 7 |
|
| 8 |
def convert(obj, /, conversion): |
| 9 |
"""Convert *obj* using formatted string literal semantics.""" |
| 10 |
if conversion is None: |
| 11 |
return obj |
| 12 |
if conversion == 'r': |
| 13 |
return repr(obj) |
| 14 |
if conversion == 's': |
| 15 |
return str(obj) |
| 16 |
if conversion == 'a': |
| 17 |
return ascii(obj) |
| 18 |
raise ValueError(f'invalid conversion specifier: {conversion}') |
| 19 |
|
| 20 |
def _template_unpickle(*args): |
| 21 |
import itertools |
| 22 |
|
| 23 |
if len(args) != 2: |
| 24 |
raise ValueError('Template expects tuple of length 2 to unpickle') |
| 25 |
|
| 26 |
strings, interpolations = args |
| 27 |
parts = [] |
| 28 |
for string, interpolation in itertools.zip_longest(strings, interpolations): |
| 29 |
if string is not None: |
| 30 |
parts.append(string) |
| 31 |
if interpolation is not None: |
| 32 |
parts.append(interpolation) |
| 33 |
return Template(*parts) |