Make a best-effort conversion of a `template` instance to an AST.
(template)
| 628 | |
| 629 | |
| 630 | def _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 | |
| 651 | class _StringifierDict(dict): |
no test coverage detected
searching dependent graphs…