gast: Generic Python AST

0.7.0 · active · verified Sun Mar 29

gast provides a compatibility layer between the Abstract Syntax Trees (AST) of various Python versions (including Python 2 and Python 3), offering a homogeneous API compatible with the standard library `ast` module. It abstracts away version-specific differences in the AST structure, making it easier to write tools that work across multiple Python versions. The library is currently at version 0.7.0 and remains actively maintained.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to parse Python code into a `gast` AST, convert a `gast` AST to a standard `ast` module AST, and convert a standard `ast` to a `gast` AST. The `gast.dump` function is used for easy inspection of the GAST structure.

import gast
import ast

code = """def foo(x):
    return x + 1"""

# Parse code into a GAST (Generic AST) node
gast_tree = gast.parse(code)
print("GAST Tree (using gast.dump):\n" + gast.dump(gast_tree))

# Convert the GAST tree to a standard AST tree for the current Python version
std_ast_tree = gast.gast_to_ast(gast_tree)
print("\nStandard AST Tree (from GAST, using ast.dump):\n" + ast.dump(std_ast_tree))

# Example of converting a standard AST to a GAST tree
std_ast_input = ast.parse("a = 'hello'")
gast_from_std = gast.ast_to_gast(std_ast_input)
print("\nGAST Tree (from standard AST input, using gast.dump):\n" + gast.dump(gast_from_std))

view raw JSON →