]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
GH-132661: Add ``string.templatelib.convert()`` (#135217)
authorAdam Turner <9087854+AA-Turner@users.noreply.github.com>
Tue, 15 Jul 2025 09:56:42 +0000 (10:56 +0100)
committerGitHub <noreply@github.com>
Tue, 15 Jul 2025 09:56:42 +0000 (11:56 +0200)
Lib/string/templatelib.py
Lib/test/test_string/test_templatelib.py

index 14b40e1e36e30b308ed3e410380a211e23c5b9f3..8164872432ad09ecabaf1aceb343e6bc4a097f7d 100644 (file)
@@ -1,15 +1,22 @@
 """Support for template string literals (t-strings)."""
 
-__all__ = [
-    "Interpolation",
-    "Template",
-]
-
 t = t"{0}"
 Template = type(t)
 Interpolation = type(t.interpolations[0])
 del t
 
+def convert(obj, /, conversion):
+    """Convert *obj* using formatted string literal semantics."""
+    if conversion is None:
+        return obj
+    if conversion == 'r':
+        return repr(obj)
+    if conversion == 's':
+        return str(obj)
+    if conversion == 'a':
+        return ascii(obj)
+    raise ValueError(f'invalid conversion specifier: {conversion}')
+
 def _template_unpickle(*args):
     import itertools
 
index adaf590e64dad6ebf135ef612ac78850f242e5c6..1c86717155fd5aba5423263ae89c3592ba569c91 100644 (file)
@@ -1,7 +1,7 @@
 import pickle
 import unittest
 from collections.abc import Iterator, Iterable
-from string.templatelib import Template, Interpolation
+from string.templatelib import Template, Interpolation, convert
 
 from test.test_string._support import TStringBaseCase, fstring
 
@@ -169,5 +169,25 @@ class TemplateIterTests(unittest.TestCase):
         self.assertRaises(StopIteration, next, template_iter)
 
 
+class TestFunctions(unittest.TestCase):
+    def test_convert(self):
+        from fractions import Fraction
+
+        for obj in ('CafĂ©', None, 3.14, Fraction(1, 2)):
+            with self.subTest(f'{obj=}'):
+                self.assertEqual(convert(obj, None), obj)
+                self.assertEqual(convert(obj, 's'), str(obj))
+                self.assertEqual(convert(obj, 'r'), repr(obj))
+                self.assertEqual(convert(obj, 'a'), ascii(obj))
+
+                # Invalid conversion specifier
+                with self.assertRaises(ValueError):
+                    convert(obj, 'z')
+                with self.assertRaises(ValueError):
+                    convert(obj, 1)
+                with self.assertRaises(ValueError):
+                    convert(obj, object())
+
+
 if __name__ == '__main__':
     unittest.main()