cjm-nbdev-docments


Namecjm-nbdev-docments JSON
Version 0.0.3 PyPI version JSON
download
home_pagehttps://github.com/cj-mills/cjm-nbdev-docments
SummaryTool for validating and updating documentation in nbdev projects for use with the fastcore.docments module.
upload_time2025-07-09 19:09:11
maintainerNone
docs_urlNone
authorChristian J. Mills
requires_python>=3.9
licenseApache Software License 2.0
keywords nbdev jupyter notebook python
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # cjm-nbdev-docments


<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

## Overview

`cjm-nbdev-docments` helps nbdev users adopt and maintain the
[fastcore.docments](https://fastcore.fast.ai/docments.html)
documentation style. Instead of traditional docstrings, `docments` uses
inline parameter documentation, making code more concise and readable.

### What is docments style?

Instead of this:

``` python
def add(x, y):
    """Add two numbers.
    
    Args:
        x: First number
        y: Second number
        
    Returns:
        Sum of x and y
    """
    return x + y
```

Docments style looks like this:

``` python
def add(
    x: int,  # First number
    y: int   # Second number  
) -> int:  # Sum of x and y
    "Add two numbers"
    return x + y
```

### Key Features

- **🔍 Comprehensive Scanning**: Automatically scans all exported
  functions and classes in your nbdev notebooks
- **✅ Compliance Checking**: Verifies that all parameters and return
  values have proper documentation
- **📊 Detailed Reports**: Generate text or JSON reports showing
  compliance status
- **🔧 Auto-fix Support**: Automatically add TODO placeholders for
  missing documentation
- **🔄 Docstring Conversion**: Convert existing Google/NumPy/Sphinx
  style docstrings to docments format
- **💻 CLI Interface**: Easy-to-use command-line tool integrated with
  nbdev workflow

## Installation

Install latest from the GitHub
[repository](https://github.com/cj-mills/cjm-nbdev-docments):

``` sh
$ pip install git+https://github.com/cj-mills/cjm-nbdev-docments.git
```

or from [conda](https://anaconda.org/cj-mills/cjm-nbdev-docments)

``` sh
$ conda install -c cj-mills cjm_nbdev_docments
```

or from [pypi](https://pypi.org/project/cjm-nbdev-docments/)

``` sh
$ pip install cjm_nbdev_docments
```

## Quick Start

### Basic Usage

Check your nbdev project for documentation compliance:

``` bash
# Check all notebooks in your project
nbdev-docments

# Get detailed report including compliant functions
nbdev-docments --verbose

# Save report to a file
nbdev-docments --output compliance-report.txt
```

### Auto-fixing Non-compliant Code

Automatically add TODO placeholders for missing documentation:

``` bash
# Preview what would be fixed
nbdev-docments --fix --dry-run

# Apply fixes
nbdev-docments --fix
```

### Converting Existing Docstrings

Convert traditional docstrings to docments format:

``` bash
# Convert Google/NumPy/Sphinx style docstrings
nbdev-docments --fix --convert-docstrings
```

## Detailed Usage Examples

### Checking a Single Function

You can check individual functions for compliance:

``` python
from cjm_nbdev_docments.core import check_function

def example_func(x, y):
    return x + y

check_function(example_func)
```

### Checking a Specific Notebook

Check a single notebook file:

``` python
from cjm_nbdev_docments.core import check_notebook

check_notebook("00_core.ipynb")
```

### Programmatic Usage

For integration into your own tools:

``` python
from cjm_nbdev_docments.report import check_project, generate_json_report

# Check entire project
results = check_project()

# Generate JSON report
report = generate_json_report(results)

# Process results programmatically
for notebook, data in report['by_notebook'].items():
    print(f"{notebook}: {len(data['non_compliant'])} issues")
```

## What Gets Checked?

The tool checks for:

1.  **Function/Method Documentation**:
    - Presence of a docstring
    - Documentation for each parameter (except `self`)
    - Documentation for return values (when return type is annotated)
2.  **Type Hints**:
    - Missing type annotations for parameters
    - Missing return type annotations
3.  **Class Documentation**:
    - Presence of class docstrings
4.  **TODO Tracking**:
    - Identifies documentation with TODO placeholders
    - Helps track documentation debt

## CLI Reference

    nbdev-docments [OPTIONS]

    Options:
      --nbs-path PATH           Path to notebooks directory (defaults to nbdev config)
      --format {text,json}      Output format (default: text)
      --output, -o PATH         Save report to file instead of printing
      --verbose, -v             Show compliant definitions in text report
      --quiet, -q               Only show summary (exit code indicates compliance)
      --todos-only              Show only functions with TODO placeholders
      --fix                     Auto-fix non-compliant functions by adding placeholder docs
      --convert-docstrings      Convert existing Google/NumPy/Sphinx docstrings to docments format
      --dry-run                 Show what would be fixed without making changes
      -h, --help                Show help message and exit

### Exit Codes

- `0`: All checked definitions are compliant
- `1`: One or more definitions are non-compliant

## Module Overview

Detailed documentation for each module in the project:

### Core (`00_core.ipynb`)

> Core functionality for checking docments compliance

#### Import

``` python
from cjm_nbdev_docments.core import (
    DocmentsCheckResult,
    extract_param_docs_from_func,
    extract_param_docs,
    check_return_doc,
    count_todos_in_docs,
    check_has_docstring_from_func,
    check_has_docstring,
    check_type_hints,
    check_params_documentation,
    determine_compliance,
    check_definition,
    check_notebook,
    check_function
)
```

#### Functions

``` python
def extract_param_docs_from_func(
    func: Callable    # Function object to extract docs from
) -> Dict[str, str]:  # Mapping of parameter names to their documentation
    "Extract parameter documentation from function object using fastcore.docments"
```

``` python
def extract_param_docs(
    source:str    # Function source code
) -> Dict[str, str]:  # Mapping of parameter names to their documentation
    "Extract parameter documentation from function source using docments style (fallback)"
```

``` python
def check_return_doc(
    source: str  # Function source code
) -> bool:  # Whether return is documented
    "Check if function has return documentation"
```

``` python
def count_todos_in_docs(
    source: str,  # Function/class source code
    name: str  # Name of the function/class for AST parsing
) -> Tuple[int, bool]:  # (todo_count, has_todos)
    "Count TODO placeholders only in documentation (docstring, param docs, return docs)"
```

``` python
def check_has_docstring_from_func(
    func: Callable  # Function object to check
) -> bool:  # Whether the function has a docstring
    "Check if a function has a docstring using fastcore.docments"
```

``` python
def check_has_docstring(
    source: str,  # Function/class source code
    name: str  # Name of the function/class
) -> bool:  # Whether the definition has a docstring
    "Check if a function/class has a docstring using AST parsing (fallback)"
```

``` python
def check_type_hints(
    definition: Dict[str, Any]  # Definition dict from scanner
) -> Tuple[Dict[str, bool], List[str], bool]:  # (params_with_type_hints, missing_type_hints, return_has_type_hint)
    "Check which parameters and return value have type hints"
```

``` python
def check_params_documentation(
    definition: Dict[str, Any],  # Definition dict from scanner
    source: str  # Function source code
) -> Tuple[Dict[str, bool], List[str], bool]:  # (params_documented, missing_params, return_documented)
    "Check parameter and return documentation for a function"
```

``` python
def determine_compliance(
    has_docstring: bool,  # Whether definition has a docstring
    params_documented: Dict[str, bool],  # Which params have documentation
    return_documented: bool  # Whether return is documented
) -> bool:  # Overall compliance status
    "Determine if a definition is compliant based on documentation checks"
```

``` python
def check_definition(
    definition: Dict[str, Any]  # Definition dict from scanner
) -> DocmentsCheckResult:  # Check result with compliance details
    "Check a function/class definition for docments compliance"
```

``` python
def check_notebook(
    nb_path: str  # Path to notebook file  
) -> None:  # Prints compliance report
    "Check a specific notebook for docments compliance"
```

``` python
def check_function(
    func:Callable          # Function object to check
) -> DocmentsCheckResult:  # Check result for the function
    "Check a single function for docments compliance"
```

#### Classes

``` python
@dataclass
class DocmentsCheckResult:
    "Result of checking a function/class for docments compliance"
    
    name: str  # Name of the function/class
    type: str  # Type (FunctionDef, ClassDef, etc.)
    notebook: str  # Source notebook
    has_docstring: bool  # Whether it has a docstring
    params_documented: Dict[str, bool]  # Which params have documentation
    return_documented: bool  # Whether return is documented
    missing_params: List[str]  # Parameters missing documentation
    is_compliant: bool  # Overall compliance status
    source: str  # Source code of the definition
    has_todos: bool = False  # Whether it contains TODO placeholders
    todo_count: int = 0  # Number of TODO placeholders found
    params_with_type_hints: Dict[str, bool]  # Which params have type hints
    return_has_type_hint: bool = False  # Whether return has type hint
    params_missing_type_hints: List[str]  # Parameters missing type hints
    
```

### Scanner (`01_scanner.ipynb`)

> Scan nbdev notebooks for exported functions and classes

#### Import

``` python
from cjm_nbdev_docments.scanner import (
    get_export_cells,
    extract_definitions,
    scan_notebook,
    scan_project
)
```

#### Functions

``` python
def get_export_cells(
    nb_path: Path    # Path to the notebook file
) -> List[Dict[str, Any]]:  # List of cells with export directives
    "Extract all code cells from a notebook that have export directives"
```

``` python
def extract_definitions(
    source: str  # Python source code
) -> List[Dict[str, Any]]:  # List of function/class definitions with metadata
    "Extract function and class definitions from source code"
```

``` python
def scan_notebook(
    nb_path: Path  # Path to the notebook to scan
) -> List[Dict[str, Any]]:  # List of exported definitions with metadata
    "Scan a notebook and extract all exported function/class definitions"
```

``` python
def scan_project(
    nbs_path: Optional[Path] = None,  # Path to notebooks directory (defaults to config.nbs_path)
    pattern: str = "*.ipynb"  # Pattern for notebook files to scan
) -> List[Dict[str, Any]]:  # All exported definitions found in the project
    "Scan all notebooks in a project for exported definitions"
```

### Report Generator (`02_report.ipynb`)

> Generate compliance reports for docments validation

#### Import

``` python
from cjm_nbdev_docments.report import (
    check_project,
    generate_text_report,
    generate_json_report
)
```

#### Functions

``` python
def check_project(
    nbs_path: Optional[Path] = None  # Path to notebooks directory
) -> List[DocmentsCheckResult]:  # List of check results for all definitions
    "Check all exported definitions in a project for docments compliance"
```

``` python
def _generate_summary_stats(
    results: List[DocmentsCheckResult]  # Check results to summarize
) -> List[str]:  # Lines of summary statistics
    "Generate summary statistics section of the report"
```

``` python
def _generate_non_compliant_section(
    results: List[DocmentsCheckResult],  # Check results
    by_notebook: Dict[str, List[DocmentsCheckResult]]  # Results grouped by notebook
) -> List[str]:  # Lines of non-compliant section
    "Generate non-compliant definitions section of the report"
```

``` python
def _generate_todos_section(
    results: List[DocmentsCheckResult],  # Check results
    by_notebook: Dict[str, List[DocmentsCheckResult]]  # Results grouped by notebook
) -> List[str]:  # Lines of TODOs section
    "Generate TODO placeholders section of the report"
```

``` python
def _generate_compliant_section(
    results: List[DocmentsCheckResult],  # Check results
    by_notebook: Dict[str, List[DocmentsCheckResult]]  # Results grouped by notebook
) -> List[str]:  # Lines of compliant section
    "Generate compliant definitions section of the report"
```

``` python
def generate_text_report(
    results: List[DocmentsCheckResult],  # Check results from check_project
    verbose: bool = False  # Include detailed information
) -> str:  # Formatted text report
    "Generate a human-readable text report of compliance results"
```

``` python
def generate_json_report(
    results: List[DocmentsCheckResult]  # Check results from check_project
) -> Dict[str, Any]:  # JSON-serializable report data
    "Generate a JSON report of compliance results"
```

### Auto-Fix (`03_autofix.ipynb`)

> Automatically add placeholder documentation to non-compliant functions

#### Import

``` python
from cjm_nbdev_docments.autofix import (
    find_signature_boundaries,
    split_parameters,
    parse_single_line_signature,
    generate_param_todo_comment,
    generate_return_todo_comment,
    build_fixed_single_line_function,
    fix_multi_line_signature,
    fix_class_definition,
    insert_function_docstring,
    fix_single_line_function,
    fix_multi_line_function,
    generate_fixed_source,
    fix_notebook,
    DocstringInfo,
    detect_docstring_style,
    parse_google_docstring,
    parse_numpy_docstring,
    parse_sphinx_docstring,
    extract_docstring_info,
    convert_to_docments_format,
    convert_single_line_to_docments,
    convert_multiline_to_docments,
    replace_docstring_in_body,
    generate_fixed_source_with_conversion,
    fix_notebook_with_conversion
)
```

#### Functions

``` python
@patch
def needs_fixing(
    self: DocmentsCheckResult
) -> bool:  # TODO: Add return description
    "Check if this definition needs any fixing"
```

``` python
@patch
def get_param_name(
    self: DocmentsCheckResult,
    param_str: str  # TODO: Add description
) -> str:  # TODO: Add return description
    "Extract parameter name from a parameter string"
```

``` python
@patch
def needs_param_fix(
    self: DocmentsCheckResult,
    param_name: str  # TODO: Add description
) -> bool:  # TODO: Add return description
    "Check if a parameter needs documentation or type hint fixes"
```

``` python
def find_signature_boundaries(
    lines: List[str]  # Source code lines
) -> tuple[int, int]:  # (def_line_idx, sig_end_idx) or (-1, -1) if not found
    "Find the start and end lines of a function signature"
```

``` python
def split_parameters(
    params_str: str  # Parameter string from function signature
) -> List[str]:  # List of individual parameter strings
    "Split a parameter string into individual parameters, handling nested types"
```

``` python
def parse_single_line_signature(
    sig_line: str  # Single-line function signature
) -> dict:  # Parsed components of the signature
    "Parse a single-line function signature into its components"
```

``` python
def generate_param_todo_comment(
    param_name: str,  # Parameter name
    result: DocmentsCheckResult,  # Check result with type hint and doc info
    existing_comment: str = ""  # Existing comment text (without #)
) -> str:  # TODO comment to add
    "Generate appropriate TODO comment for a parameter based on what's missing"
```

``` python
def generate_return_todo_comment(
    result: DocmentsCheckResult,  # Check result with type hint and doc info
    existing_comment: str = ""  # Existing comment text (without #)
) -> str:  # TODO comment to add
    "Generate appropriate TODO comment for return value based on what's missing"
```

``` python
def build_fixed_single_line_function(
    parsed: dict,  # Parsed signature components
    params: List[str],  # Individual parameter strings
    result: DocmentsCheckResult  # Check result with missing params info
) -> List[str]:  # Lines of fixed function signature
    "Build a fixed single-line function with documentation comments"
```

``` python
def fix_multi_line_signature(
    lines: List[str],  # All source lines
    def_line_idx: int,  # Start of function definition
    sig_end_idx: int,  # End of function signature
    result: DocmentsCheckResult  # Check result with missing params info
) -> List[str]:  # Fixed lines for the signature portion
    "Fix a multi-line function signature by adding parameter comments"
```

``` python
def fix_class_definition(
    result: DocmentsCheckResult  # Check result with non-compliant class
) -> str:  # Fixed source code with class docstring
    "Fix a class definition by adding a docstring if missing"
```

``` python
def insert_function_docstring(
    lines: List[str],  # Fixed function lines
    def_line_idx: int,  # Index of function definition line
    indent: str  # Base indentation for the function
) -> List[str]:  # Lines with docstring inserted
    "Insert a TODO docstring after the function signature"
```

``` python
def fix_single_line_function(
    lines: List[str],  # All source lines
    def_line_idx: int,  # Index of function definition line
    result: DocmentsCheckResult  # Check result with missing params info
) -> List[str]:  # Fixed lines for the function
    "Fix a single-line function signature by converting to multi-line with parameter comments"
```

``` python
def fix_multi_line_function(
    lines: List[str],  # All source lines
    def_line_idx: int,  # Start of function definition
    sig_end_idx: int,  # End of function signature
    result: DocmentsCheckResult  # Check result with missing params info
) -> List[str]:  # Fixed lines for the function
    "Fix a multi-line function signature by adding parameter comments"
```

``` python
def generate_fixed_source(
    result: DocmentsCheckResult  # Check result with non-compliant function
) -> str:  # Fixed source code with placeholder documentation
    "Generate fixed source code for a non-compliant function or class"
```

``` python
def fix_notebook(
    nb_path: Path,  # Path to notebook to fix
    dry_run: bool = False  # If True, show changes without saving
) -> Dict[str, Any]:  # Summary of changes made
    "Fix non-compliant functions in a notebook by adding placeholder documentation"
```

``` python
def detect_docstring_style(
    docstring: str  # Docstring text to analyze
) -> str:  # Detected style: 'google', 'numpy', 'sphinx', 'docments', or 'unknown'
    "Detect the style of a docstring"
```

``` python
def parse_google_docstring(
    docstring: str  # Google-style docstring text
) -> DocstringInfo:  # Parsed docstring information
    "Parse a Google-style docstring"
```

``` python
def parse_numpy_docstring(
    docstring: str  # NumPy-style docstring text
) -> DocstringInfo:  # Parsed docstring information
    "Parse a NumPy-style docstring"
```

``` python
def parse_sphinx_docstring(
    docstring: str  # Sphinx-style docstring text
) -> DocstringInfo:  # Parsed docstring information
    "Parse a Sphinx-style docstring"
```

``` python
def extract_docstring_info(
    source: str,  # Function source code
    name: str  # Function name
) -> Optional[DocstringInfo]:  # Extracted docstring information or None
    "Extract docstring information from function source code"
```

``` python
def convert_to_docments_format(
    source: str,  # Original function source code
    docstring_info: DocstringInfo,  # Extracted docstring information
    result: DocmentsCheckResult  # Check result with missing params info
) -> str:  # Converted source code in docments format
    "Convert function source to docments format using extracted docstring info"
```

``` python
def convert_single_line_to_docments(
    sig_line: str,  # Single-line function signature
    docstring_info: DocstringInfo,  # Extracted docstring information
    result: DocmentsCheckResult  # Check result with missing params info
) -> List[str]:  # Multi-line signature with docments comments
    "Convert single-line function signature to multi-line docments format"
```

``` python
def convert_multiline_to_docments(
    sig_lines: List[str],  # Multi-line function signature
    docstring_info: DocstringInfo,  # Extracted docstring information
    result: DocmentsCheckResult  # Check result with missing params info
) -> List[str]:  # Multi-line signature with docments comments
    "Convert multi-line function signature to docments format"
```

``` python
def replace_docstring_in_body(
    body_lines: List[str],  # Function body lines
    description: str,  # New description to use
    def_line: str  # Function definition line for indentation
) -> List[str]:  # Modified body lines
    "Replace the docstring in function body with a simple description"
```

``` python
def generate_fixed_source_with_conversion(
    result: DocmentsCheckResult  # Check result with non-compliant function
) -> str:  # Fixed source code with converted documentation
    "Generate fixed source code, converting existing docstrings to docments format if possible"
```

``` python
def fix_notebook_with_conversion(
    nb_path: Path,  # Path to notebook to fix
    dry_run: bool = False,  # If True, show changes without saving
    convert_docstrings: bool = True  # If True, convert existing docstrings to docments format
) -> Dict[str, Any]:  # Summary of changes made
    "Fix non-compliant functions in a notebook, optionally converting docstrings to docments format"
```

#### Classes

``` python
class DocstringInfo(NamedTuple):
    "Information extracted from a docstring"
```

### CLI Interface (`04_cli.ipynb`)

> Command-line interface for docments compliance checking

#### Import

``` python
from cjm_nbdev_docments.cli import (
    create_parser,
    handle_autofix,
    generate_report,
    output_report,
    main
)
```

#### Functions

``` python
def create_parser(
) -> argparse.ArgumentParser:  # TODO: Add return description
    "Create and configure the argument parser for docments CLI"
```

``` python
def handle_autofix(
    args: argparse.Namespace  # Parsed command line arguments
) -> int:  # Exit code
    "Handle auto-fix mode for non-compliant functions"
```

``` python
def generate_report(
    results: list,  # Check results from check_project
    format: str,  # Output format ("text" or "json")
    verbose: bool = False  # Whether to show compliant definitions
) -> str:  # Generated report as string
    "Generate a report in the specified format"
```

``` python
def output_report(
    report: str,  # Report content to output
    output_path: Optional[Path] = None,  # File path to save report to
    quiet: bool = False  # Whether to suppress output
) -> None:  # TODO: Add return description
    "Output the report to console or file"
```

``` python
def main(
    args: Optional[list] = None  # Command line arguments (for testing)
) -> int:  # Exit code (0 for success, 1 for non-compliance)
    "Main CLI entry point for docments checker"
```

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/cj-mills/cjm-nbdev-docments",
    "name": "cjm-nbdev-docments",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "nbdev jupyter notebook python",
    "author": "Christian J. Mills",
    "author_email": "9126128+cj-mills@users.noreply.github.com",
    "download_url": "https://files.pythonhosted.org/packages/8c/65/75238ed6f599133c6d48e61cf18e112635c3e952ea4c269bbe82802ba67f/cjm_nbdev_docments-0.0.3.tar.gz",
    "platform": null,
    "description": "# cjm-nbdev-docments\n\n\n<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->\n\n## Overview\n\n`cjm-nbdev-docments` helps nbdev users adopt and maintain the\n[fastcore.docments](https://fastcore.fast.ai/docments.html)\ndocumentation style. Instead of traditional docstrings, `docments` uses\ninline parameter documentation, making code more concise and readable.\n\n### What is docments style?\n\nInstead of this:\n\n``` python\ndef add(x, y):\n    \"\"\"Add two numbers.\n    \n    Args:\n        x: First number\n        y: Second number\n        \n    Returns:\n        Sum of x and y\n    \"\"\"\n    return x + y\n```\n\nDocments style looks like this:\n\n``` python\ndef add(\n    x: int,  # First number\n    y: int   # Second number  \n) -> int:  # Sum of x and y\n    \"Add two numbers\"\n    return x + y\n```\n\n### Key Features\n\n- **\ud83d\udd0d Comprehensive Scanning**: Automatically scans all exported\n  functions and classes in your nbdev notebooks\n- **\u2705 Compliance Checking**: Verifies that all parameters and return\n  values have proper documentation\n- **\ud83d\udcca Detailed Reports**: Generate text or JSON reports showing\n  compliance status\n- **\ud83d\udd27 Auto-fix Support**: Automatically add TODO placeholders for\n  missing documentation\n- **\ud83d\udd04 Docstring Conversion**: Convert existing Google/NumPy/Sphinx\n  style docstrings to docments format\n- **\ud83d\udcbb CLI Interface**: Easy-to-use command-line tool integrated with\n  nbdev workflow\n\n## Installation\n\nInstall latest from the GitHub\n[repository](https://github.com/cj-mills/cjm-nbdev-docments):\n\n``` sh\n$ pip install git+https://github.com/cj-mills/cjm-nbdev-docments.git\n```\n\nor from [conda](https://anaconda.org/cj-mills/cjm-nbdev-docments)\n\n``` sh\n$ conda install -c cj-mills cjm_nbdev_docments\n```\n\nor from [pypi](https://pypi.org/project/cjm-nbdev-docments/)\n\n``` sh\n$ pip install cjm_nbdev_docments\n```\n\n## Quick Start\n\n### Basic Usage\n\nCheck your nbdev project for documentation compliance:\n\n``` bash\n# Check all notebooks in your project\nnbdev-docments\n\n# Get detailed report including compliant functions\nnbdev-docments --verbose\n\n# Save report to a file\nnbdev-docments --output compliance-report.txt\n```\n\n### Auto-fixing Non-compliant Code\n\nAutomatically add TODO placeholders for missing documentation:\n\n``` bash\n# Preview what would be fixed\nnbdev-docments --fix --dry-run\n\n# Apply fixes\nnbdev-docments --fix\n```\n\n### Converting Existing Docstrings\n\nConvert traditional docstrings to docments format:\n\n``` bash\n# Convert Google/NumPy/Sphinx style docstrings\nnbdev-docments --fix --convert-docstrings\n```\n\n## Detailed Usage Examples\n\n### Checking a Single Function\n\nYou can check individual functions for compliance:\n\n``` python\nfrom cjm_nbdev_docments.core import check_function\n\ndef example_func(x, y):\n    return x + y\n\ncheck_function(example_func)\n```\n\n### Checking a Specific Notebook\n\nCheck a single notebook file:\n\n``` python\nfrom cjm_nbdev_docments.core import check_notebook\n\ncheck_notebook(\"00_core.ipynb\")\n```\n\n### Programmatic Usage\n\nFor integration into your own tools:\n\n``` python\nfrom cjm_nbdev_docments.report import check_project, generate_json_report\n\n# Check entire project\nresults = check_project()\n\n# Generate JSON report\nreport = generate_json_report(results)\n\n# Process results programmatically\nfor notebook, data in report['by_notebook'].items():\n    print(f\"{notebook}: {len(data['non_compliant'])} issues\")\n```\n\n## What Gets Checked?\n\nThe tool checks for:\n\n1.  **Function/Method Documentation**:\n    - Presence of a docstring\n    - Documentation for each parameter (except `self`)\n    - Documentation for return values (when return type is annotated)\n2.  **Type Hints**:\n    - Missing type annotations for parameters\n    - Missing return type annotations\n3.  **Class Documentation**:\n    - Presence of class docstrings\n4.  **TODO Tracking**:\n    - Identifies documentation with TODO placeholders\n    - Helps track documentation debt\n\n## CLI Reference\n\n    nbdev-docments [OPTIONS]\n\n    Options:\n      --nbs-path PATH           Path to notebooks directory (defaults to nbdev config)\n      --format {text,json}      Output format (default: text)\n      --output, -o PATH         Save report to file instead of printing\n      --verbose, -v             Show compliant definitions in text report\n      --quiet, -q               Only show summary (exit code indicates compliance)\n      --todos-only              Show only functions with TODO placeholders\n      --fix                     Auto-fix non-compliant functions by adding placeholder docs\n      --convert-docstrings      Convert existing Google/NumPy/Sphinx docstrings to docments format\n      --dry-run                 Show what would be fixed without making changes\n      -h, --help                Show help message and exit\n\n### Exit Codes\n\n- `0`: All checked definitions are compliant\n- `1`: One or more definitions are non-compliant\n\n## Module Overview\n\nDetailed documentation for each module in the project:\n\n### Core (`00_core.ipynb`)\n\n> Core functionality for checking docments compliance\n\n#### Import\n\n``` python\nfrom cjm_nbdev_docments.core import (\n    DocmentsCheckResult,\n    extract_param_docs_from_func,\n    extract_param_docs,\n    check_return_doc,\n    count_todos_in_docs,\n    check_has_docstring_from_func,\n    check_has_docstring,\n    check_type_hints,\n    check_params_documentation,\n    determine_compliance,\n    check_definition,\n    check_notebook,\n    check_function\n)\n```\n\n#### Functions\n\n``` python\ndef extract_param_docs_from_func(\n    func: Callable    # Function object to extract docs from\n) -> Dict[str, str]:  # Mapping of parameter names to their documentation\n    \"Extract parameter documentation from function object using fastcore.docments\"\n```\n\n``` python\ndef extract_param_docs(\n    source:str    # Function source code\n) -> Dict[str, str]:  # Mapping of parameter names to their documentation\n    \"Extract parameter documentation from function source using docments style (fallback)\"\n```\n\n``` python\ndef check_return_doc(\n    source: str  # Function source code\n) -> bool:  # Whether return is documented\n    \"Check if function has return documentation\"\n```\n\n``` python\ndef count_todos_in_docs(\n    source: str,  # Function/class source code\n    name: str  # Name of the function/class for AST parsing\n) -> Tuple[int, bool]:  # (todo_count, has_todos)\n    \"Count TODO placeholders only in documentation (docstring, param docs, return docs)\"\n```\n\n``` python\ndef check_has_docstring_from_func(\n    func: Callable  # Function object to check\n) -> bool:  # Whether the function has a docstring\n    \"Check if a function has a docstring using fastcore.docments\"\n```\n\n``` python\ndef check_has_docstring(\n    source: str,  # Function/class source code\n    name: str  # Name of the function/class\n) -> bool:  # Whether the definition has a docstring\n    \"Check if a function/class has a docstring using AST parsing (fallback)\"\n```\n\n``` python\ndef check_type_hints(\n    definition: Dict[str, Any]  # Definition dict from scanner\n) -> Tuple[Dict[str, bool], List[str], bool]:  # (params_with_type_hints, missing_type_hints, return_has_type_hint)\n    \"Check which parameters and return value have type hints\"\n```\n\n``` python\ndef check_params_documentation(\n    definition: Dict[str, Any],  # Definition dict from scanner\n    source: str  # Function source code\n) -> Tuple[Dict[str, bool], List[str], bool]:  # (params_documented, missing_params, return_documented)\n    \"Check parameter and return documentation for a function\"\n```\n\n``` python\ndef determine_compliance(\n    has_docstring: bool,  # Whether definition has a docstring\n    params_documented: Dict[str, bool],  # Which params have documentation\n    return_documented: bool  # Whether return is documented\n) -> bool:  # Overall compliance status\n    \"Determine if a definition is compliant based on documentation checks\"\n```\n\n``` python\ndef check_definition(\n    definition: Dict[str, Any]  # Definition dict from scanner\n) -> DocmentsCheckResult:  # Check result with compliance details\n    \"Check a function/class definition for docments compliance\"\n```\n\n``` python\ndef check_notebook(\n    nb_path: str  # Path to notebook file  \n) -> None:  # Prints compliance report\n    \"Check a specific notebook for docments compliance\"\n```\n\n``` python\ndef check_function(\n    func:Callable          # Function object to check\n) -> DocmentsCheckResult:  # Check result for the function\n    \"Check a single function for docments compliance\"\n```\n\n#### Classes\n\n``` python\n@dataclass\nclass DocmentsCheckResult:\n    \"Result of checking a function/class for docments compliance\"\n    \n    name: str  # Name of the function/class\n    type: str  # Type (FunctionDef, ClassDef, etc.)\n    notebook: str  # Source notebook\n    has_docstring: bool  # Whether it has a docstring\n    params_documented: Dict[str, bool]  # Which params have documentation\n    return_documented: bool  # Whether return is documented\n    missing_params: List[str]  # Parameters missing documentation\n    is_compliant: bool  # Overall compliance status\n    source: str  # Source code of the definition\n    has_todos: bool = False  # Whether it contains TODO placeholders\n    todo_count: int = 0  # Number of TODO placeholders found\n    params_with_type_hints: Dict[str, bool]  # Which params have type hints\n    return_has_type_hint: bool = False  # Whether return has type hint\n    params_missing_type_hints: List[str]  # Parameters missing type hints\n    \n```\n\n### Scanner (`01_scanner.ipynb`)\n\n> Scan nbdev notebooks for exported functions and classes\n\n#### Import\n\n``` python\nfrom cjm_nbdev_docments.scanner import (\n    get_export_cells,\n    extract_definitions,\n    scan_notebook,\n    scan_project\n)\n```\n\n#### Functions\n\n``` python\ndef get_export_cells(\n    nb_path: Path    # Path to the notebook file\n) -> List[Dict[str, Any]]:  # List of cells with export directives\n    \"Extract all code cells from a notebook that have export directives\"\n```\n\n``` python\ndef extract_definitions(\n    source: str  # Python source code\n) -> List[Dict[str, Any]]:  # List of function/class definitions with metadata\n    \"Extract function and class definitions from source code\"\n```\n\n``` python\ndef scan_notebook(\n    nb_path: Path  # Path to the notebook to scan\n) -> List[Dict[str, Any]]:  # List of exported definitions with metadata\n    \"Scan a notebook and extract all exported function/class definitions\"\n```\n\n``` python\ndef scan_project(\n    nbs_path: Optional[Path] = None,  # Path to notebooks directory (defaults to config.nbs_path)\n    pattern: str = \"*.ipynb\"  # Pattern for notebook files to scan\n) -> List[Dict[str, Any]]:  # All exported definitions found in the project\n    \"Scan all notebooks in a project for exported definitions\"\n```\n\n### Report Generator (`02_report.ipynb`)\n\n> Generate compliance reports for docments validation\n\n#### Import\n\n``` python\nfrom cjm_nbdev_docments.report import (\n    check_project,\n    generate_text_report,\n    generate_json_report\n)\n```\n\n#### Functions\n\n``` python\ndef check_project(\n    nbs_path: Optional[Path] = None  # Path to notebooks directory\n) -> List[DocmentsCheckResult]:  # List of check results for all definitions\n    \"Check all exported definitions in a project for docments compliance\"\n```\n\n``` python\ndef _generate_summary_stats(\n    results: List[DocmentsCheckResult]  # Check results to summarize\n) -> List[str]:  # Lines of summary statistics\n    \"Generate summary statistics section of the report\"\n```\n\n``` python\ndef _generate_non_compliant_section(\n    results: List[DocmentsCheckResult],  # Check results\n    by_notebook: Dict[str, List[DocmentsCheckResult]]  # Results grouped by notebook\n) -> List[str]:  # Lines of non-compliant section\n    \"Generate non-compliant definitions section of the report\"\n```\n\n``` python\ndef _generate_todos_section(\n    results: List[DocmentsCheckResult],  # Check results\n    by_notebook: Dict[str, List[DocmentsCheckResult]]  # Results grouped by notebook\n) -> List[str]:  # Lines of TODOs section\n    \"Generate TODO placeholders section of the report\"\n```\n\n``` python\ndef _generate_compliant_section(\n    results: List[DocmentsCheckResult],  # Check results\n    by_notebook: Dict[str, List[DocmentsCheckResult]]  # Results grouped by notebook\n) -> List[str]:  # Lines of compliant section\n    \"Generate compliant definitions section of the report\"\n```\n\n``` python\ndef generate_text_report(\n    results: List[DocmentsCheckResult],  # Check results from check_project\n    verbose: bool = False  # Include detailed information\n) -> str:  # Formatted text report\n    \"Generate a human-readable text report of compliance results\"\n```\n\n``` python\ndef generate_json_report(\n    results: List[DocmentsCheckResult]  # Check results from check_project\n) -> Dict[str, Any]:  # JSON-serializable report data\n    \"Generate a JSON report of compliance results\"\n```\n\n### Auto-Fix (`03_autofix.ipynb`)\n\n> Automatically add placeholder documentation to non-compliant functions\n\n#### Import\n\n``` python\nfrom cjm_nbdev_docments.autofix import (\n    find_signature_boundaries,\n    split_parameters,\n    parse_single_line_signature,\n    generate_param_todo_comment,\n    generate_return_todo_comment,\n    build_fixed_single_line_function,\n    fix_multi_line_signature,\n    fix_class_definition,\n    insert_function_docstring,\n    fix_single_line_function,\n    fix_multi_line_function,\n    generate_fixed_source,\n    fix_notebook,\n    DocstringInfo,\n    detect_docstring_style,\n    parse_google_docstring,\n    parse_numpy_docstring,\n    parse_sphinx_docstring,\n    extract_docstring_info,\n    convert_to_docments_format,\n    convert_single_line_to_docments,\n    convert_multiline_to_docments,\n    replace_docstring_in_body,\n    generate_fixed_source_with_conversion,\n    fix_notebook_with_conversion\n)\n```\n\n#### Functions\n\n``` python\n@patch\ndef needs_fixing(\n    self: DocmentsCheckResult\n) -> bool:  # TODO: Add return description\n    \"Check if this definition needs any fixing\"\n```\n\n``` python\n@patch\ndef get_param_name(\n    self: DocmentsCheckResult,\n    param_str: str  # TODO: Add description\n) -> str:  # TODO: Add return description\n    \"Extract parameter name from a parameter string\"\n```\n\n``` python\n@patch\ndef needs_param_fix(\n    self: DocmentsCheckResult,\n    param_name: str  # TODO: Add description\n) -> bool:  # TODO: Add return description\n    \"Check if a parameter needs documentation or type hint fixes\"\n```\n\n``` python\ndef find_signature_boundaries(\n    lines: List[str]  # Source code lines\n) -> tuple[int, int]:  # (def_line_idx, sig_end_idx) or (-1, -1) if not found\n    \"Find the start and end lines of a function signature\"\n```\n\n``` python\ndef split_parameters(\n    params_str: str  # Parameter string from function signature\n) -> List[str]:  # List of individual parameter strings\n    \"Split a parameter string into individual parameters, handling nested types\"\n```\n\n``` python\ndef parse_single_line_signature(\n    sig_line: str  # Single-line function signature\n) -> dict:  # Parsed components of the signature\n    \"Parse a single-line function signature into its components\"\n```\n\n``` python\ndef generate_param_todo_comment(\n    param_name: str,  # Parameter name\n    result: DocmentsCheckResult,  # Check result with type hint and doc info\n    existing_comment: str = \"\"  # Existing comment text (without #)\n) -> str:  # TODO comment to add\n    \"Generate appropriate TODO comment for a parameter based on what's missing\"\n```\n\n``` python\ndef generate_return_todo_comment(\n    result: DocmentsCheckResult,  # Check result with type hint and doc info\n    existing_comment: str = \"\"  # Existing comment text (without #)\n) -> str:  # TODO comment to add\n    \"Generate appropriate TODO comment for return value based on what's missing\"\n```\n\n``` python\ndef build_fixed_single_line_function(\n    parsed: dict,  # Parsed signature components\n    params: List[str],  # Individual parameter strings\n    result: DocmentsCheckResult  # Check result with missing params info\n) -> List[str]:  # Lines of fixed function signature\n    \"Build a fixed single-line function with documentation comments\"\n```\n\n``` python\ndef fix_multi_line_signature(\n    lines: List[str],  # All source lines\n    def_line_idx: int,  # Start of function definition\n    sig_end_idx: int,  # End of function signature\n    result: DocmentsCheckResult  # Check result with missing params info\n) -> List[str]:  # Fixed lines for the signature portion\n    \"Fix a multi-line function signature by adding parameter comments\"\n```\n\n``` python\ndef fix_class_definition(\n    result: DocmentsCheckResult  # Check result with non-compliant class\n) -> str:  # Fixed source code with class docstring\n    \"Fix a class definition by adding a docstring if missing\"\n```\n\n``` python\ndef insert_function_docstring(\n    lines: List[str],  # Fixed function lines\n    def_line_idx: int,  # Index of function definition line\n    indent: str  # Base indentation for the function\n) -> List[str]:  # Lines with docstring inserted\n    \"Insert a TODO docstring after the function signature\"\n```\n\n``` python\ndef fix_single_line_function(\n    lines: List[str],  # All source lines\n    def_line_idx: int,  # Index of function definition line\n    result: DocmentsCheckResult  # Check result with missing params info\n) -> List[str]:  # Fixed lines for the function\n    \"Fix a single-line function signature by converting to multi-line with parameter comments\"\n```\n\n``` python\ndef fix_multi_line_function(\n    lines: List[str],  # All source lines\n    def_line_idx: int,  # Start of function definition\n    sig_end_idx: int,  # End of function signature\n    result: DocmentsCheckResult  # Check result with missing params info\n) -> List[str]:  # Fixed lines for the function\n    \"Fix a multi-line function signature by adding parameter comments\"\n```\n\n``` python\ndef generate_fixed_source(\n    result: DocmentsCheckResult  # Check result with non-compliant function\n) -> str:  # Fixed source code with placeholder documentation\n    \"Generate fixed source code for a non-compliant function or class\"\n```\n\n``` python\ndef fix_notebook(\n    nb_path: Path,  # Path to notebook to fix\n    dry_run: bool = False  # If True, show changes without saving\n) -> Dict[str, Any]:  # Summary of changes made\n    \"Fix non-compliant functions in a notebook by adding placeholder documentation\"\n```\n\n``` python\ndef detect_docstring_style(\n    docstring: str  # Docstring text to analyze\n) -> str:  # Detected style: 'google', 'numpy', 'sphinx', 'docments', or 'unknown'\n    \"Detect the style of a docstring\"\n```\n\n``` python\ndef parse_google_docstring(\n    docstring: str  # Google-style docstring text\n) -> DocstringInfo:  # Parsed docstring information\n    \"Parse a Google-style docstring\"\n```\n\n``` python\ndef parse_numpy_docstring(\n    docstring: str  # NumPy-style docstring text\n) -> DocstringInfo:  # Parsed docstring information\n    \"Parse a NumPy-style docstring\"\n```\n\n``` python\ndef parse_sphinx_docstring(\n    docstring: str  # Sphinx-style docstring text\n) -> DocstringInfo:  # Parsed docstring information\n    \"Parse a Sphinx-style docstring\"\n```\n\n``` python\ndef extract_docstring_info(\n    source: str,  # Function source code\n    name: str  # Function name\n) -> Optional[DocstringInfo]:  # Extracted docstring information or None\n    \"Extract docstring information from function source code\"\n```\n\n``` python\ndef convert_to_docments_format(\n    source: str,  # Original function source code\n    docstring_info: DocstringInfo,  # Extracted docstring information\n    result: DocmentsCheckResult  # Check result with missing params info\n) -> str:  # Converted source code in docments format\n    \"Convert function source to docments format using extracted docstring info\"\n```\n\n``` python\ndef convert_single_line_to_docments(\n    sig_line: str,  # Single-line function signature\n    docstring_info: DocstringInfo,  # Extracted docstring information\n    result: DocmentsCheckResult  # Check result with missing params info\n) -> List[str]:  # Multi-line signature with docments comments\n    \"Convert single-line function signature to multi-line docments format\"\n```\n\n``` python\ndef convert_multiline_to_docments(\n    sig_lines: List[str],  # Multi-line function signature\n    docstring_info: DocstringInfo,  # Extracted docstring information\n    result: DocmentsCheckResult  # Check result with missing params info\n) -> List[str]:  # Multi-line signature with docments comments\n    \"Convert multi-line function signature to docments format\"\n```\n\n``` python\ndef replace_docstring_in_body(\n    body_lines: List[str],  # Function body lines\n    description: str,  # New description to use\n    def_line: str  # Function definition line for indentation\n) -> List[str]:  # Modified body lines\n    \"Replace the docstring in function body with a simple description\"\n```\n\n``` python\ndef generate_fixed_source_with_conversion(\n    result: DocmentsCheckResult  # Check result with non-compliant function\n) -> str:  # Fixed source code with converted documentation\n    \"Generate fixed source code, converting existing docstrings to docments format if possible\"\n```\n\n``` python\ndef fix_notebook_with_conversion(\n    nb_path: Path,  # Path to notebook to fix\n    dry_run: bool = False,  # If True, show changes without saving\n    convert_docstrings: bool = True  # If True, convert existing docstrings to docments format\n) -> Dict[str, Any]:  # Summary of changes made\n    \"Fix non-compliant functions in a notebook, optionally converting docstrings to docments format\"\n```\n\n#### Classes\n\n``` python\nclass DocstringInfo(NamedTuple):\n    \"Information extracted from a docstring\"\n```\n\n### CLI Interface (`04_cli.ipynb`)\n\n> Command-line interface for docments compliance checking\n\n#### Import\n\n``` python\nfrom cjm_nbdev_docments.cli import (\n    create_parser,\n    handle_autofix,\n    generate_report,\n    output_report,\n    main\n)\n```\n\n#### Functions\n\n``` python\ndef create_parser(\n) -> argparse.ArgumentParser:  # TODO: Add return description\n    \"Create and configure the argument parser for docments CLI\"\n```\n\n``` python\ndef handle_autofix(\n    args: argparse.Namespace  # Parsed command line arguments\n) -> int:  # Exit code\n    \"Handle auto-fix mode for non-compliant functions\"\n```\n\n``` python\ndef generate_report(\n    results: list,  # Check results from check_project\n    format: str,  # Output format (\"text\" or \"json\")\n    verbose: bool = False  # Whether to show compliant definitions\n) -> str:  # Generated report as string\n    \"Generate a report in the specified format\"\n```\n\n``` python\ndef output_report(\n    report: str,  # Report content to output\n    output_path: Optional[Path] = None,  # File path to save report to\n    quiet: bool = False  # Whether to suppress output\n) -> None:  # TODO: Add return description\n    \"Output the report to console or file\"\n```\n\n``` python\ndef main(\n    args: Optional[list] = None  # Command line arguments (for testing)\n) -> int:  # Exit code (0 for success, 1 for non-compliance)\n    \"Main CLI entry point for docments checker\"\n```\n",
    "bugtrack_url": null,
    "license": "Apache Software License 2.0",
    "summary": "Tool for validating and updating documentation in nbdev projects for use with the fastcore.docments module.",
    "version": "0.0.3",
    "project_urls": {
        "Homepage": "https://github.com/cj-mills/cjm-nbdev-docments"
    },
    "split_keywords": [
        "nbdev",
        "jupyter",
        "notebook",
        "python"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "21e74c8068a094444c7f9fad2cdb9d8afa89fad34d58815f917702e63aa985c6",
                "md5": "f78150bc7a698fc5e16d896cf9be752e",
                "sha256": "5e895f680e905d54d2f75af999a2c4d7a0c7a82b3043a3922f7fc7ee2e96afb5"
            },
            "downloads": -1,
            "filename": "cjm_nbdev_docments-0.0.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "f78150bc7a698fc5e16d896cf9be752e",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 31653,
            "upload_time": "2025-07-09T19:09:10",
            "upload_time_iso_8601": "2025-07-09T19:09:10.662443Z",
            "url": "https://files.pythonhosted.org/packages/21/e7/4c8068a094444c7f9fad2cdb9d8afa89fad34d58815f917702e63aa985c6/cjm_nbdev_docments-0.0.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "8c6575238ed6f599133c6d48e61cf18e112635c3e952ea4c269bbe82802ba67f",
                "md5": "ef0acb22c2e0eab8588dfe36c5a5ba98",
                "sha256": "05e96c0759d850f7b2fdb892624e883bd13850b8074e5dc77e1e5ecbc91ee531"
            },
            "downloads": -1,
            "filename": "cjm_nbdev_docments-0.0.3.tar.gz",
            "has_sig": false,
            "md5_digest": "ef0acb22c2e0eab8588dfe36c5a5ba98",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 34260,
            "upload_time": "2025-07-09T19:09:11",
            "upload_time_iso_8601": "2025-07-09T19:09:11.633987Z",
            "url": "https://files.pythonhosted.org/packages/8c/65/75238ed6f599133c6d48e61cf18e112635c3e952ea4c269bbe82802ba67f/cjm_nbdev_docments-0.0.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-07-09 19:09:11",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "cj-mills",
    "github_project": "cjm-nbdev-docments",
    "github_not_found": true,
    "lcname": "cjm-nbdev-docments"
}
        
Elapsed time: 0.43125s