Skip to content

Instantly share code, notes, and snippets.

@monperrus
Created March 16, 2025 10:30
Show Gist options
  • Save monperrus/dc7428b4612910c80dd7dbefd69a8866 to your computer and use it in GitHub Desktop.
Save monperrus/dc7428b4612910c80dd7dbefd69a8866 to your computer and use it in GitHub Desktop.
write a python program that parses another python program, summarizes the full file, replace the module docstring and rewrite the program
import ast
import astor
class DocstringReplacer(ast.NodeTransformer):
"""AST Node Transformer to replace module docstring."""
def visit_Module(self, node):
"""Visit Module node and replace docstring."""
# Replace docstring
node.body[0] = ast.Assign(
targets=,
value=ast.Str(s='New module docstring')
)
# Continue with default visitation
return self.generic_visit(node)
def parse_and_rewrite_python_program(filename):
"""Parse Python program, replace docstring, and rewrite the program."""
# Parse Python source code into AST
with open(filename, 'r') as source:
tree = ast.parse(source.read())
# Replace docstring
DocstringReplacer().visit(tree)
# Rewrite the Python program
with open(filename, 'w') as source:
source.write(astor.to_source(tree))
if __name__ == "__main__":
parse_and_rewrite_python_program('test.py')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment