Skip to content

Commit 5b969fd

Browse files
authored
GH-132661: Add string.templatelib.convert() (#135217)
1 parent c89a66f commit 5b969fd

File tree

2 files changed

+33
-6
lines changed

2 files changed

+33
-6
lines changed

Lib/string/templatelib.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,22 @@
11
"""Support for template string literals (t-strings)."""
22

3-
__all__ = [
4-
"Interpolation",
5-
"Template",
6-
]
7-
83
t = t"{0}"
94
Template = type(t)
105
Interpolation = type(t.interpolations[0])
116
del t
127

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+
1320
def _template_unpickle(*args):
1421
import itertools
1522

Lib/test/test_string/test_templatelib.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import pickle
22
import unittest
33
from collections.abc import Iterator, Iterable
4-
from string.templatelib import Template, Interpolation
4+
from string.templatelib import Template, Interpolation, convert
55

66
from test.test_string._support import TStringBaseCase, fstring
77

@@ -169,5 +169,25 @@ def test_exhausted(self):
169169
self.assertRaises(StopIteration, next, template_iter)
170170

171171

172+
class TestFunctions(unittest.TestCase):
173+
def test_convert(self):
174+
from fractions import Fraction
175+
176+
for obj in ('Café', None, 3.14, Fraction(1, 2)):
177+
with self.subTest(f'{obj=}'):
178+
self.assertEqual(convert(obj, None), obj)
179+
self.assertEqual(convert(obj, 's'), str(obj))
180+
self.assertEqual(convert(obj, 'r'), repr(obj))
181+
self.assertEqual(convert(obj, 'a'), ascii(obj))
182+
183+
# Invalid conversion specifier
184+
with self.assertRaises(ValueError):
185+
convert(obj, 'z')
186+
with self.assertRaises(ValueError):
187+
convert(obj, 1)
188+
with self.assertRaises(ValueError):
189+
convert(obj, object())
190+
191+
172192
if __name__ == '__main__':
173193
unittest.main()

0 commit comments

Comments
 (0)