Generate Beautiful Project Documentation from Python Source Code Automatically
Automatically generate a markdown summary of function docstrings from any Python source file using the AST module.
Python code
36 linesimport ast
import inspect
from pathlib import Path
def extract_docstrings_from_file(filepath):
"""Parse a Python file and collect function docstrings."""
source = Path(filepath).read_text()
tree = ast.parse(source)
docs = []
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
name = node.name
docstring = ast.get_docstring(node)
if docstring:
first_line = docstring.strip().split('\n')[0]
docs.append((name, first_line, node.lineno))
return docs
def generate_markdown_docs(filepath):
"""Produce a simple markdown summary from a Python file."""
docs = extract_docstrings_from_file(filepath)
if not docs:
return "# No documentation found"
lines = [f"# Documentation for `{Path(filepath).name}`\n"]
lines.append("| Function | Description | Line |")
lines.append("|----------|-------------|------|")
for name, desc, lineno in docs:
lines.append(f"| `{name}()` | {desc} | {lineno} |")
return "\n".join(lines)
if __name__ == "__main__":
# Example: document this script itself
current_file = __file__
print(generate_markdown_docs(current_file))
Output
# Documentation for `auto_docs.py`
| Function | Description | Line |
|----------|-------------|------|
| `extract_docstrings_from_file()` | Parse a Python file and collect function docstrings. | 5 |
| `generate_markdown_docs()` | Produce a simple markdown summary from a Python file. | 17 |
How it works
The ast.parse() call converts a Python source file into an abstract syntax tree. Walking this tree with ast.walk() lets you inspect every node; checking for ast.FunctionDef or ast.AsyncFunctionDef captures all function definitions. ast.get_docstring() retrieves the first expression statement if it's a string literal, and the function strips it to its first line for a compact table. The result is a clean markdown table ready for a README or documentation portal.
Common mistakes
- Forgetting that nested classes or methods (ast.ClassDef) aren't included—they need their own visitor logic.
- Calling `generate_markdown_docs()` on a non-Python file causes a syntax error in `ast.parse()`.
- Assuming docstrings exist on every function—the code gracefully skips missing ones, but users may expect all functions listed.
Variations
- Add a CLI argument parser to accept a file path or directory, then generate docs for all .py files recursively.
- Include class docstrings by checking for `ast.ClassDef` in the walk.
Real-world use cases
- Auto-generating a function reference for internal Python packages that lack formal documentation.
- Creating a quick summary table for onboarding contributors to a large codebase.
- Feeding extracted docstrings into a CI pipeline that updates project READMEs on every release.
Sponsored
More from Automation & scripting
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
- Automatically Log CPU, RAM, and Disk Usage Every Minute in Python easy
- Batch Rename Hundreds of Files in Python easy
Keep learning
Related tutorials and quizzes for this topic.