gast: Generic Python AST
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
- breaking For Python 3.8 and later, several `ast` node types like `ast.Num`, `ast.Str`, `ast.Bytes`, `ast.Ellipsis`, and `ast.NamedConstant` are replaced by `gast.Constant` in `gast` ASTs (since `gast >= 0.3.0`). Code that directly inspects or creates these specific node types must be updated to use `gast.Constant` for cross-version compatibility.
- gotcha The representation of certain AST nodes changes in Python 3.9+. For instance, `ast.arg` nodes are represented as `ast.Name` with an `ast.Param` context, and `ExceptHandler.name` is an `ast.Name` with an `ast.Store` context instead of a simple string.
- gotcha The interpretation of literals like `None`, `True`, and `False` differs between Python 2 and Python 3. In Python 3, they are parsed as `gast.Constant`, while in Python 2, they are parsed as `gast.Name`.
- gotcha While `gast` provides an API compatible with `ast`, directly importing or using classes from the standard `ast` module when you intend to work with `gast`'s cross-version AST can lead to unexpected behavior or `AttributeError` if the underlying `ast` module's structure for that node differs from `gast`'s harmonized representation.
- gotcha The `_field_types` attribute, which exists for each AST class in standard `ast` modules, is always empty in `gast` for Python versions before 3.10. Relying on this field for introspection might yield incomplete information on older Python versions.
Install
-
pip install gast
Imports
- gast
import gast
- Node
from gast import Name, Constant
- parse
gast.parse(code)
Quickstart
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))