Python Glossary Русский

Python 3.9+astfunction

ast.unparse()

helper functions

Turns an AST back into a string of source code. Needed after editing a tree to see or save the resulting code.

Syntax

ast.unparse(ast_obj)

It returns equivalent code, not the original: comments are lost (they are not in the tree), formatting and redundant parentheses are normalised, string quotes may change. So parse → unparse is no tool for careful file edits; use a formatting-preserving tool such as libcst. Added in 3.9; a very deep expression raises RecursionError.

Examples

import ast
src = "x = (1)  # счётчик\nif x :\n    y = \"a\""
print(ast.unparse(ast.parse(src)))  # → x = 1 / if x: / y = 'a'
import ast
tree = ast.parse('a + b', mode='eval')
tree.body.op = ast.Mult()
print(ast.unparse(tree))  # → a * b

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy