ast-comments

1.3.0 · active · verified Thu Apr 16

ast-comments is an extension to Python's built-in `ast` module that preserves comments in the Abstract Syntax Tree. It finds comments in source code and includes them as nodes in the parsed AST, which the standard `ast` module discards. The library is currently active, at version 1.3.0, and maintains a regular release cadence to support new Python features and address issues.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates parsing Python code to include comments in the AST, walking the tree to find `Comment` nodes, and unparsing it back to code. It also shows how to prepare the tree for Python's built-in `compile()` function by stripping comment nodes.

from ast_comments import parse, unparse, Comment, pre_compile_fixer
import ast

code = """\
def greet(name): # Function to greet a user
    # This is an inline comment
    message = f"Hello, {name}!" # Greeting message
    return message

# Call the function
result = greet("World")
"""

# Parse the code, preserving comments
tree = parse(code)

# You can now walk the tree and find Comment nodes
comments_found = []
for node in ast.walk(tree):
    if isinstance(node, Comment):
        comments_found.append(node.value)

print("Comments found:")
for comment in comments_found:
    print(f"- {comment}")

# Unparse the tree back to code (with comments)
# Note: formatting might differ from original, but comments are preserved
reconstructed_code = unparse(tree)
print("\nReconstructed code:")
print(reconstructed_code)

# To compile the AST, comment nodes must be removed first
fixed_tree = pre_compile_fixer(tree)
compiled_code = compile(fixed_tree, '<string>', 'exec')
# You can then exec(compiled_code) if needed

view raw JSON →