Skip to content

Commit 8fb8420

Browse files
committed
Fix and test one last interesting edge case in annotationlib
1 parent 395b392 commit 8fb8420

File tree

2 files changed

+8
-6
lines changed

2 files changed

+8
-6
lines changed

Lib/annotationlib.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -578,11 +578,7 @@ def _template_to_ast_constructor(template):
578578
]
579579
)
580580
args.append(interp)
581-
return ast.Call(
582-
func=ast.Name(id="Template"),
583-
args=args,
584-
keywords=[],
585-
)
581+
return ast.Call(func=ast.Name(id="Template"), args=args, keywords=[])
586582

587583

588584
def _template_to_ast_literal(template, parsed):
@@ -611,7 +607,9 @@ def _template_to_ast(template):
611607
"""Make a best-effort conversion of a `template` instance to an AST."""
612608
# gh-138558: Not all Template instances can be represented as t-string
613609
# literals. Return the most accurate AST we can. See issue for details.
614-
if any(part.expression == "" for part in template.interpolations):
610+
611+
# If any expr is empty or whitespace only, we cannot convert to a literal.
612+
if any(not part.expression.strip() for part in template.interpolations):
615613
return _template_to_ast_constructor(template)
616614

617615
try:

Lib/test/test_annotationlib.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1364,6 +1364,10 @@ def nested():
13641364
type_repr(Template("hi", Interpolation(42))),
13651365
"Template('hi', Interpolation(42, '', None, ''))",
13661366
)
1367+
self.assertEqual(
1368+
type_repr(Template("hi", Interpolation(42, " "))),
1369+
"Template('hi', Interpolation(42, ' ', None, ''))",
1370+
)
13671371
# gh138558: perhaps in the future, we can improve this behavior:
13681372
self.assertEqual(type_repr(Template(Interpolation(42, "99"))), "t'{99}'")
13691373

0 commit comments

Comments
 (0)