Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes

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.

Medium Python 3.9+ Jun 28, 2026 Automation & scripting 16 views 0 copies

Python code

36 lines
Python 3.9+
import 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

stdout
# 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

  1. Add a CLI argument parser to accept a file path or directory, then generate docs for all .py files recursively.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.