Python Glossary Русский

all Python 3astfunction

ast.parse()

helper functions

Parses source code into a tree of AST nodes without running it. The starting point of any code analysis: a linter, a solution checker, counting constructs.

Syntax

ast.parse(source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None)

A successful parse does not mean the code is valid: ast.parse('return 1') and ast.parse('yield x') succeed, while compile() of the same tree raises SyntaxError, because parse does no scope checks. The mode matters: mode='exec' gives a Module whose body is a list of statements, mode='eval' gives an Expression with a single expression body. Comments never reach the tree (except '# type:' with type_comments=True).

Examples

import ast
tree = ast.parse('total = price * 2')
print(type(tree).__name__, len(tree.body))  # → Module 1
print(type(tree.body[0]).__name__)  # → Assign
expr = ast.parse('price * 2', mode='eval')
print(type(expr).__name__, type(expr.body).__name__)  # → Expression BinOp
import ast
tree = ast.parse('return 42')  # разбор проходит: parse не проверяет области видимости
print(type(tree.body[0]).__name__)  # → Return
try:
    compile(tree, '<ast>', 'exec')
except SyntaxError as e:
    print(type(e).__name__, e.msg)  # → SyntaxError 'return' outside function

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy