Skip to content

Commit 2b794d9

Browse files
committed
Add new annotationlib tests and ensure they pass
1 parent f866029 commit 2b794d9

2 files changed

Lines changed: 20 additions & 2 deletions

File tree

Lib/annotationlib.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -609,7 +609,9 @@ def _template_to_ast_literal(template, parsed):
609609
str=part.expression,
610610
value=parsed[interp_count],
611611
conversion=ord(part.conversion) if part.conversion else -1,
612-
format_spec=part.format_spec or None, # "" -> None
612+
format_spec=ast.Constant(value=part.format_spec)
613+
if part.format_spec
614+
else None,
613615
)
614616
values.append(interp)
615617
interp_count += 1

Lib/test/test_annotationlib.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import functools
88
import itertools
99
import pickle
10-
from string.templatelib import Template
10+
from string.templatelib import Template, Interpolation
1111
import typing
1212
import unittest
1313
from annotationlib import (
@@ -282,6 +282,7 @@ def f(
282282
a: t"a{b}c{d}e{f}g",
283283
b: t"{a:{1}}",
284284
c: t"{a | b * c}",
285+
gh138558: t"{ 0}",
285286
): pass
286287

287288
annos = get_annotations(f, format=Format.STRING)
@@ -293,6 +294,7 @@ def f(
293294
# interpolations in the format spec are eagerly evaluated so we can't recover the source
294295
"b": "t'{a:1}'",
295296
"c": "t'{a | b * c}'",
297+
"gh138558": "t'{ 0}'",
296298
})
297299

298300
def g(
@@ -1350,6 +1352,20 @@ def nested():
13501352
self.assertEqual(type_repr("1"), "'1'")
13511353
self.assertEqual(type_repr(Format.VALUE), repr(Format.VALUE))
13521354
self.assertEqual(type_repr(MyClass()), "my repr")
1355+
# gh138558 tests
1356+
self.assertEqual(type_repr(t'''{ 0
1357+
& 1
1358+
| 2
1359+
}'''), 't"""{ 0\n & 1\n | 2}"""')
1360+
self.assertEqual(
1361+
type_repr(Template("hi", Interpolation(42, "42"))), "t'hi{42}'"
1362+
)
1363+
self.assertEqual(
1364+
type_repr(Template("hi", Interpolation(42))),
1365+
"Template('hi', Interpolation(42, '', None, ''))",
1366+
)
1367+
# gh138558: perhaps in the future, we can improve this behavior:
1368+
self.assertEqual(type_repr(Template(Interpolation(42, "99"))), "t'{99}'")
13531369

13541370

13551371
class TestAnnotationsToString(unittest.TestCase):

0 commit comments

Comments
 (0)