astcheck - Check Python ASTs against templates

0.4.0 · active · verified Fri Apr 17

astcheck is a Python library designed to check Abstract Syntax Trees (ASTs) against structured templates. It's particularly useful for testing AST transformations, linters, or any code that processes Python ASTs. The current version is 0.4.0, with releases occurring periodically to address minor improvements and Python version compatibility.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to parse Python code into an AST, define a template AST using `ast.parse` and `astcheck.NAME` placeholders, and then use `is_ast_match` to check for structural similarity. It also shows `assert_ast_equal` for strict comparisons and `match_ast` for extracting matched nodes.

import ast
from astcheck import is_ast_match, assert_ast_equal, NAME

# The target AST node to check
code_to_check = """x = 1 + y"""
node = ast.parse(code_to_check)

# Define a template AST using ast.parse() and astcheck placeholders
template = ast.parse("""some_var = 1 + another_var""")

# Using is_ast_match to check if the target AST matches the template structure
is_match = is_ast_match(node, template, some_var=NAME, another_var=NAME)
assert is_match, "The AST structure should match the template!"

print(f"AST '{code_to_check.strip()}' matches template: {is_match}")

# Using assert_ast_equal for a stricter comparison (all non-placeholder nodes must be identical)
# For exact matching, often you wouldn't use NAME placeholders
strict_template = ast.parse("""x = 1 + y""")
assert_ast_equal(node, strict_template)
print("Strict AST comparison successful.")

# Example with extracted matches (if using match_ast instead of is_ast_match)
from astcheck import match_ast, N_INT
match_result = match_ast(node, ast.parse("var_name = LITERAL + OTHER_VAR"), var_name=NAME, LITERAL=N_INT, OTHER_VAR=NAME)
assert match_result is not None
print(f"Extracted variable name: {match_result['var_name'].id}")
print(f"Extracted literal value: {match_result['LITERAL'].value}")

view raw JSON →