MCPcopy Index your code
hub / github.com/python/cpython / _template_to_ast

Function _template_to_ast

Lib/annotationlib.py:630–648  ·  view source on GitHub ↗

Make a best-effort conversion of a `template` instance to an AST.

(template)

Source from the content-addressed store, hash-verified

628
629
630def _template_to_ast(template):
631 """Make a best-effort conversion of a `template` instance to an AST."""
632 # gh-138558: Not all Template instances can be represented as t-string
633 # literals. Return the most accurate AST we can. See issue for details.
634
635 # If any expr is empty or whitespace only, we cannot convert to a literal.
636 if any(part.expression.strip() == "" for part in template.interpolations):
637 return _template_to_ast_constructor(template)
638
639 try:
640 # Wrap in parens to allow whitespace inside interpolation curly braces
641 parsed = tuple(
642 ast.parse(f"({part.expression})", mode="eval").body
643 for part in template.interpolations
644 )
645 except SyntaxError:
646 return _template_to_ast_constructor(template)
647
648 return _template_to_ast_literal(template, parsed)
649
650
651class _StringifierDict(dict):

Callers 3

__convert_to_astMethod · 0.85
_stringify_singleFunction · 0.85
type_reprFunction · 0.85

Calls 5

_template_to_ast_literalFunction · 0.85
anyFunction · 0.70
stripMethod · 0.45
parseMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…