Skip to content

Instantly share code, notes, and snippets.

@CodeByAidan
Last active December 2, 2025 19:47
Show Gist options
  • Select an option

  • Save CodeByAidan/bd6090e61133af26d7a86426dc22e68c to your computer and use it in GitHub Desktop.

Select an option

Save CodeByAidan/bd6090e61133af26d7a86426dc22e68c to your computer and use it in GitHub Desktop.
Simple script using ast, astor, and black to remove docstrings and comments from any python file.
import ast
import astor # `pip install astor`
from black import FileMode, format_str # `pip install black`
class DocstringRemover(ast.NodeTransformer):
def visit(self, node: ast.AST) -> ast.AST:
if isinstance(node, (ast.FunctionDef, ast.ClassDef, ast.Module)):
if (
node.body
and isinstance(node.body[0], ast.Expr)
and isinstance(node.body[0].value, ast.Constant)
):
node.body.pop(0)
self.generic_visit(node)
return node
def remove_docstrings(source_code: str) -> str:
tree = ast.parse(source_code)
remover = DocstringRemover()
tree = remover.visit(tree)
return format_str(astor.to_source(tree), mode=FileMode())
if __name__ == "__main__":
source_code = '''
def foo():
"""This is a docstring."""
print("Hello, world!")
class Bar:
"""This is a class docstring."""
def baz(self):
"""This is a method docstring."""
print("Hello, Bar!") # This is a comment.
'''
cleaned_code: str = remove_docstrings(source_code)
print(cleaned_code)
# or use a file:
# with open("sets.py", "r", encoding="utf-8") as input_file:
# source_code = input_file.read()
# cleaned_code: str = remove_docstrings(source_code)
# with open("sets.py", "w", encoding="utf-8") as output_file:
# output_file.write(cleaned_code)
def foo():
print("Hello, world!")
class Bar:
def baz(self):
print("Hello, Bar!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment