Skip to main content

Automatically generate, validate, and measure Google-style Python docstrings. Deterministic AST-based docstring generator and validator with CI/CD integration, coverage reporting, and JSON output.

Project description

PyCodeCommenter — Python Docstring Generator & Validator

PyPI version Documentation Python Support License: MIT GitHub Stars

PyCodeCommenter is an open-source Python docstring generator and documentation validator. It automatically generates Google-style docstrings from Python AST, validates existing docstrings against real function signatures, measures documentation coverage, and integrates with CI/CD pipelines — all with zero network calls and zero AI dependency.

Install: pip install pycodecommenter · Python 3.8+ · MIT License


What PyCodeCommenter Does

Task Command
Generate missing docstrings pycodecommenter generate myfile.py --inplace
Validate docstrings vs code pycodecommenter validate myfile.py
Measure documentation coverage pycodecommenter coverage ./src
JSON output for downstream tools pycodecommenter validate myfile.py --output-format json

PyCodeCommenter solves documentation drift — the common Python project problem where code changes but docstrings don't. It catches undocumented parameters, missing Returns: sections, orphaned docstring entries, and mismatched type hints before they reach production.


Quick Start

pip install pycodecommenter

# Preview what will be added (safe, no writes)
pycodecommenter generate main.py --dry-run

# Apply docstrings in place
pycodecommenter generate main.py --inplace

# Validate accuracy
pycodecommenter validate main.py

# Check project coverage
pycodecommenter coverage ./src

Why PyCodeCommenter?

The Problem

  • Code changes quickly; docstrings lag behind and become stale.
  • No easy way to validate existing docstrings against real signatures.
  • AI tools generate inconsistent or hallucinated documentation.
  • Most Python projects have no coverage metric for documentation quality.

The Solution

PyCodeCommenter uses deterministic, AST-based analysis — not AI — to:

  • Generate structurally correct Google-style docstrings from your code's own AST.
  • Validate parameter names, type hints, exception documentation, and return values.
  • Measure and enforce documentation coverage across an entire project.
  • Export structured JSON reports for integration with any downstream tooling.

Features

Six Validation Checks

Every documented function is checked for:

  1. Signature Matching — every parameter in the function signature must appear in Args:, and vice versa.
  2. Type Consistency — type annotations must match documented types.
  3. Exception Documentationraise statements require a Raises: section (Google or Sphinx style).
  4. Return Documentationreturn <value> requires a Returns: section.
  5. Format Compliance — docstring must have a summary line; non-standard section headers are flagged.
  6. Content Quality — placeholder text (TODO, FIXME, Description of), short summaries, and duplicate descriptions are caught.

Decorator-Aware Validation (v2.2.0)

  • @property getter — return check fires as normal.
  • @property setter / deleter — return check is skipped (no false-positive warnings).
  • @classmethodcls is excluded from parameter checks.
  • @staticmethod — no self/cls stripping; all parameters validated.

Structured JSON Output (v2.2.0)

Both validate and coverage support --output-format json for machine-readable output:

pycodecommenter validate src/api.py --output-format json
{
  "file": "src/api.py",
  "stats": {
    "total": 3,
    "errors": 1,
    "warnings": 2,
    "info": 0,
    "coverage_percentage": 85.0
  },
  "issues": [
    {
      "line": 42,
      "severity": "ERROR",
      "check": "signature",
      "message": "Parameter 'timeout' is not documented in docstring"
    }
  ]
}

Modern Python Support

  • Python 3.8, 3.9, 3.10, 3.11, 3.12.
  • async def functions.
  • Complex type hints: Union, Optional, Generic, list[int], int | str.
  • PEP 604 unions, PEP 585 generics.

Coverage Reporting

  • Per-file coverage percentages.
  • Project-wide totals.
  • JSON, Markdown, and console output.
  • CI/CD integration with exit codes.

Usage Examples

Example 1: Generate Docstrings

from PyCodeCommenter import PyCodeCommenter

code = """
def calculate_discount(price: float, rate: float = 0.1) -> float:
    return price * (1 - rate)
"""

commenter = PyCodeCommenter().from_string(code)
print(commenter.get_patched_code())

Output:

def calculate_discount(price: float, rate: float = 0.1) -> float:
    """Calculate discount.

    Args:
        price (float): Price of the product.
        rate (float): Discount rate to apply. (default: 0.1)

    Returns:
        float: Discounted price after applying the rate.
    """
    return price * (1 - rate)

Example 2: Validate in CI/CD

import sys
from PyCodeCommenter import PyCodeCommenter

commenter = PyCodeCommenter().from_file("src/main.py")
report = commenter.validate()

if report.stats.errors > 0:
    report.print_summary()
    sys.exit(1)  # Fail the CI build

print(f"✓ Documentation validated: {report.stats.coverage_percentage:.1f}% coverage")

Example 3: Enforce Coverage Threshold

from PyCodeCommenter import CoverageAnalyzer

analyzer = CoverageAnalyzer()
project = analyzer.analyze_directory("./src", exclude_patterns=["tests"])

if project.total_coverage < 80.0:
    print(f"❌ Coverage {project.total_coverage:.1f}% is below the 80% threshold")
    project.print_report()
    sys.exit(1)

print(f"✓ Coverage {project.total_coverage:.1f}% meets the threshold")

Example 4: JSON Export

import json
from PyCodeCommenter import PyCodeCommenter

commenter = PyCodeCommenter().from_file("mycode.py")
report = commenter.validate()

with open("validation_report.json", "w") as f:
    json.dump(report.to_dict(), f, indent=2)

CI/CD Integration

GitHub Actions

# .github/workflows/docs.yml
name: Documentation Check

on: [push, pull_request]

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.12'
      - run: pip install pycodecommenter
      - run: pycodecommenter validate src/

Pre-commit Hook

# .pre-commit-config.yaml
repos:
  - repo: local
    hooks:
      - id: validate-docstrings
        name: Validate Docstrings
        entry: pycodecommenter validate
        language: system
        types: [python]

Frequently Asked Questions

What is PyCodeCommenter? PyCodeCommenter is a Python command-line tool and library for automatically generating Google-style docstrings and validating existing docstrings against real function signatures.

How do I install PyCodeCommenter? Run pip install pycodecommenter. Python 3.8 or later is required.

Does PyCodeCommenter use AI or LLMs? No. PyCodeCommenter is fully deterministic. It uses Python's built-in ast module to parse code and generate documentation. There are no API calls, no network requests, and no rate limits.

Does PyCodeCommenter overwrite my hand-written docstrings? No. Existing summaries, parameter descriptions, and return descriptions are preserved and merged. Only missing sections are filled in automatically.

What docstring styles does PyCodeCommenter support? PyCodeCommenter generates Google-style docstrings. It can parse both Google-style and Sphinx-style (:param:, :returns:, :raises:) as input.

Can I use PyCodeCommenter in CI/CD? Yes. The validate subcommand exits with code 1 when any ERROR-level issue is found, making it suitable for blocking CI builds. The --output-format json flag enables integration with any downstream tooling.

What is documentation drift? Documentation drift is when code is updated but the corresponding docstrings are not. Parameters get added or renamed, return types change, and exceptions get added — but the docstring stays the same. PyCodeCommenter detects and fixes this.

How does PyCodeCommenter measure documentation coverage? Coverage is (documented_functions + documented_classes) / (total_functions + total_classes) × 100. A function counts as documented if its first body statement is a non-empty string literal.


Configuration

Create .pycodecommenter.yaml in your project root:

style: google
validation:
  level: strict
  check_types: true
  check_exceptions: true
coverage:
  threshold: 80
  fail_below: true
exclude:
  - "*/tests/*"
  - "*/migrations/*"
  - "*/__pycache__/*"

Documentation

Full documentation: https://amosquety.github.io/PyCodeCommenter/


Supported Platforms & Environments

  • OS: Linux, macOS, Windows
  • Python: 3.8, 3.9, 3.10, 3.11, 3.12
  • Environments: local, CI/CD (GitHub Actions, GitLab CI, Jenkins), pre-commit hooks
  • Dependencies: stdlib only (no third-party runtime dependencies beyond ruamel.yaml for config)

Known Limitations

  • Python 2.x is not supported (EOL).
  • match statements (Python 3.10+) have basic support.
  • NumPy-style docstrings are not parsed as input.

Roadmap

  • VS Code extension
  • Smart docstring updates that preserve human-written content
  • Optional AI-powered description generation
  • NumPy and full Sphinx style support
  • GitHub Action for automated documentation PRs
  • --fail-below flag for coverage threshold enforcement in CLI

Creator

PyCodeCommenter was created and is actively maintained by Nabasa Amos (Amos Quety), a software engineer focused on developer tooling, documentation automation, and software quality.


License

MIT License — see LICENSE for details.

Contributing

Contributions are welcome. Please read CONTRIBUTING.md before submitting a pull request.

Issues & Discussions


If PyCodeCommenter is useful in your workflow, a ⭐ on GitHub helps other Python developers discover it.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pycodecommenter-2.2.0.tar.gz (89.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pycodecommenter-2.2.0-py3-none-any.whl (31.1 kB view details)

Uploaded Python 3

File details

Details for the file pycodecommenter-2.2.0.tar.gz.

File metadata

  • Download URL: pycodecommenter-2.2.0.tar.gz
  • Upload date:
  • Size: 89.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for pycodecommenter-2.2.0.tar.gz
Algorithm Hash digest
SHA256 64c8240f9c0f5bc43ab5d9753746e265da2301d548794bc0c339bc56788a76b1
MD5 e67e6460c7f45736e86ac437a581dc5f
BLAKE2b-256 b367ac3329bf6594a4a2dd3edf9c5277916a3251ce6d57af09b9a4beaa867517

See more details on using hashes here.

Provenance

The following attestation bundles were made for pycodecommenter-2.2.0.tar.gz:

Publisher: publish.yml on AmosQuety/PyCodeCommenter

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file pycodecommenter-2.2.0-py3-none-any.whl.

File metadata

  • Download URL: pycodecommenter-2.2.0-py3-none-any.whl
  • Upload date:
  • Size: 31.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for pycodecommenter-2.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e305051626bea49298ae9eebb29969e79b90e5d2605d8e8fc4e569fa4d651257
MD5 2b3f2b4a85ee9cafd1e03584f88b82dd
BLAKE2b-256 f2ab8a5744d63434e4ec10eb6005ebc9a5e8d009325a41a3344ed33df23c23a8

See more details on using hashes here.

Provenance

The following attestation bundles were made for pycodecommenter-2.2.0-py3-none-any.whl:

Publisher: publish.yml on AmosQuety/PyCodeCommenter

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page