FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

GH-132661: Add ``string.templatelib.convert()`` by AA-Turner · Pull Request #135217 · python/cpython · GitHub

/ cpython Public
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .py  (2) All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
17 changes: 12 additions & 5 deletions Lib/string/templatelib.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -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

Expand Down
22 changes: 21 additions & 1 deletion Lib/test/test_string/test_templatelib.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -156,5 +156,25 @@ def test_exhausted(self):
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()
Loading

Back | FazBrowse Home | New Git URL