Skip to main content

Automatically generate, validate, and maintain Google-style docstrings for Python code

Project description

PyCodeCommenter 🚀

PyPI version Python Support License: MIT GitHub

The Python documentation tool that developers actually want to use.

PyCodeCommenter automatically generates, validates, and maintains Google-style docstrings for your Python code. Unlike AI-based tools, it provides deterministic, rule-based validation that catches documentation issues AI might miss.

Why PyCodeCommenter?

The Problem

  • AI tools generate inconsistent documentation
  • No way to validate existing docstrings against code
  • Documentation drift as code evolves
  • No coverage metrics for documentation quality

The Solution

  • Generate professional docstrings automatically
  • Validate existing docs against actual code signatures
  • Track documentation coverage across projects
  • Integrate with CI/CD pipelines

Terminal Usage

# Generate docstrings for a file
pycodecommenter generate main.py -i

# Validate documentation
pycodecommenter validate main.py

# Check project coverage
pycodecommenter coverage .

Features

Comprehensive Validation

Six types of validation checks:

  • Signature Matching: Params in code match docstring
  • Type Consistency: Type hints match documented types
  • Exception Documentation: Raised exceptions are documented
  • Return Documentation: Return values properly documented
  • Format Compliance: Follows Google-style guidelines
  • Content Quality: No placeholders or TODOs

Coverage Reporting

  • Per-file coverage metrics
  • Project-wide statistics
  • Export to JSON, Markdown, or console
  • CI/CD integration ready

Modern Python Support

  • Python 3.8+ support
  • Async functions (async def)
  • Complex type hints (Union, Optional, Generic)
  • PEP 604 unions (int | str)
  • PEP 585 generics (list[int])

Developer-Friendly

  • Beautiful console output
  • Actionable error messages
  • Multiple export formats
  • Fast AST-based analysis (no API calls)

Usage Examples

Example 1: Basic Generation

from PyCodeCommenter import PyCodeCommenter

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

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

Output:

def calculate_discount(price: float, rate: float = 0.1) -> float:
    """Calculate discount.
    
    Calculates the discount.
    
    Args:
        price (float): Price of the object.
        rate (float): Rate of the object. (default: 0.1)
    
    Returns:
        float: Description of the return value.
    """
    return price * (1 - rate)

Example 2: Validation in CI/CD

# validate_docs.py
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 CI build

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

Example 3: Coverage Enforcement

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}% below threshold 80%")
    project.print_report()
    sys.exit(1)

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

Example 4: Export Reports

import json
from PyCodeCommenter import PyCodeCommenter

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

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

# Markdown export
with open("validation_report.md", "w") as f:
    f.write(report.to_markdown())

Configuration

Create .pycodecommenter.yaml in your project root:

style: google  # or 'numpy', 'sphinx'
validation:
  level: strict  # or 'moderate', 'lenient'
  check_types: true
  check_exceptions: true
coverage:
  threshold: 80
  fail_below: true
exclude:
  - "*/tests/*"
  - "*/migrations/*"
  - "*/__pycache__/*"

Use Cases

For Individual Developers

  • Generate documentation for new functions quickly
  • Validate docs before committing
  • Track documentation coverage

For Teams

  • Enforce documentation standards in CI/CD
  • Prevent PRs with undocumented code
  • Maintain consistent documentation style

For Open Source Projects

  • Welcome contributors with clear doc requirements
  • Automated documentation checks in PRs
  • Public coverage badges

Integration

Pre-commit Hook

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

GitHub Actions

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

on: [push, pull_request]

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Set up Python
        uses: actions/setup-python@v2
        with:
          python-version: '3.9'
      - name: Install dependencies
        run: pip install pycodecommenter
      - name: Validate documentation
        run: pycodecommenter validate .

Documentation

  • User Guide - Comprehensive usage guide
  • API Reference - Complete API documentation
  • Configuration - Configuration options
  • Contributing - How to contribute

Known Limitations

  • Does not support Python 2.x (EOL)
  • Match statements (Python 3.10+) have basic support
  • Complex decorators may affect docstring placement

Roadmap

  • VS Code extension
  • Smart docstring updates (preserve human content)
  • AI-powered generation (optional)
  • NumPy and Sphinx style support
  • GitHub Action for automated PRs

License

MIT License - see LICENSE file for details.

Contributing

Contributions welcome! Please read CONTRIBUTING.md first.

Show Your Support

If PyCodeCommenter helped you, please star the repo! It helps others discover the project.

Contact

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.0.3.tar.gz (23.6 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.0.3-py3-none-any.whl (23.7 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: pycodecommenter-2.0.3.tar.gz
  • Upload date:
  • Size: 23.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.10

File hashes

Hashes for pycodecommenter-2.0.3.tar.gz
Algorithm Hash digest
SHA256 0c43dd235c6c92a210a303688b1fa9d77d145b1f8f1332574018f9a6d24af6ce
MD5 7178232f96c8f91e086c2e34d61852e6
BLAKE2b-256 272d47410e21331886a6c72f4241f8e60640019404a6a798430a079879c38fba

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for pycodecommenter-2.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 6a94d36dc8132cbc8bfaa1e59a699d5803c006382f7a3981f40cc03e11f4689b
MD5 48613c58db2f241fd49fb68943ba8bcd
BLAKE2b-256 7982cd4cf26fbb0ddba056dba3df4eec9cd699248dfe7be7f623d84d993c2725

See more details on using hashes here.

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