Skip to content

Commit 628dc27

Browse files
committed
Add Template / Interpolation formatting to pprint
1 parent 84914ad commit 628dc27

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

Lib/pprint.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -566,6 +566,29 @@ def _pprint_user_string(self, object, stream, indent, allowance, context, level)
566566

567567
_dispatch[_collections.UserString.__repr__] = _pprint_user_string
568568

569+
def _pprint_template(self, object, stream, indent, allowance, context, level):
570+
cls_name = object.__class__.__name__
571+
indent += len(cls_name) + 1
572+
items = (("strings", object.strings),
573+
("interpolations", object.interpolations))
574+
stream.write(cls_name + '(')
575+
self._format_namespace_items(items, stream, indent, allowance, context, level)
576+
stream.write(')')
577+
578+
def _pprint_interpolation(self, object, stream, indent, allowance, context, level):
579+
cls_name = object.__class__.__name__
580+
indent += len(cls_name)
581+
items = (object.value, object.expression,
582+
object.conversion, object.format_spec)
583+
stream.write(cls_name + '(')
584+
self._format_items(items, stream, indent, allowance, context, level)
585+
stream.write(')')
586+
587+
t = t"{0}"
588+
_dispatch[type(t).__repr__] = _pprint_template
589+
_dispatch[type(t.interpolations[0]).__repr__] = _pprint_interpolation
590+
del t
591+
569592
def _safe_repr(self, object, context, maxlevels, level):
570593
# Return triple (repr_string, isreadable, isrecursive).
571594
typ = type(object)

Lib/test/test_pprint.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1130,6 +1130,38 @@ def test_user_string(self):
11301130
'jumped over a '
11311131
'lazy dog'}""")
11321132

1133+
def test_template(self):
1134+
d = t""
1135+
self.assertEqual(pprint.pformat(d),
1136+
"Template(strings=('',), interpolations=())")
1137+
self.assertEqual(pprint.pformat(d), repr(d))
1138+
self.assertEqual(pprint.pformat(d, width=1),
1139+
"""\
1140+
Template(strings=('',),
1141+
interpolations=())""")
1142+
name = "World"
1143+
d = t"Hello {name}"
1144+
self.assertEqual(pprint.pformat(d),
1145+
"""\
1146+
Template(strings=('Hello ', ''),
1147+
interpolations=(Interpolation('World', 'name', None, ''),))""")
1148+
ver = {3.13: False, 3.14: True}
1149+
d = t"Hello { {"name": "Python", "version": ver}!s:z}!"
1150+
self.assertEqual(pprint.pformat(d, width=1),
1151+
"""\
1152+
Template(strings=('Hello ',
1153+
'!'),
1154+
interpolations=(Interpolation({'name': 'Python',
1155+
'version': {3.13: False,
1156+
3.14: True}},
1157+
' '
1158+
'{"name": '
1159+
'"Python", '
1160+
'"version": '
1161+
'ver}',
1162+
's',
1163+
'z'),))""")
1164+
11331165

11341166
class DottedPrettyPrinter(pprint.PrettyPrinter):
11351167

0 commit comments

Comments
 (0)