CodeBlanks Logo Icon CodeBlanks

ast.parse

Learn to build an AST with ast.parse.

What is ast.parse?

ast.parse turns a source code string into an abstract syntax tree (AST). Each node in the tree represents a syntax element: a statement, an expression, a name, a constant.

For example ast.parse("x = 1 + 2") returns a Module node; its .body list contains an Assign statement. You can walk and analyse this tree, transform it or recompile it. ASTs are the foundation of linters, code generators and teaching tools.

AST nodes

AST nodes are defined as classes in the ast module. Assign is for assignment, BinOp for binary operations, Name for variable names, Constant for literal values.

You can learn a node's type with type(node).__name__. You access sub-fields with a dot: node.targets, node.value. To understand the tree ast.dump(tree) shows the full structure as a string. This is very handy for debugging.

Practice Build a tree with ast.parse

Import the module with import ast. Build the tree with ast.parse("x = 1 + 2"). Get the first statement with tree.body[0]. Print the node type name with type(node).__name__.

Starter code

main.py
# parse the code and find the first statement
# print its type name

Sample solution

main.py
import ast

tree = ast.parse("x = 1 + 2")
node = tree.body[0]
print(type(node).__name__)

Expected output

Assign

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does ast.parse return?

main.py
import ast
tree = ast.parse("x = 1")
  • A list
  • A string
  • A Module node Correct answer
  • An error

Explanation: ast.parse returns a Module node; .body lists the statements.

2 Complete the ast.parse call

Question
tree = ____("x = 1 + 2")
Answer
tree = ast.parse("x = 1 + 2")

Explanation: ast.parse turns a code string into a tree.

3 Match AST concepts

Term Meaning
ast.parse Parses code into a tree
Module Root node
body Statement list
Assign Assignment statement

All lessons in Expert