Skip to content

MkAutodoc Plugin

Automatic documentation generation from code structure.

Core Attributes

Plugin Name

mkautodoc

Installation

Bash
pip install mkautodoc

Configuration

YAML
plugins:
  - mkautodoc:
      enabled: true

What It Does

MkAutodoc automatically generates documentation by scanning your codebase and extracting: - Module structure - Class definitions - Function signatures - Docstrings - Type hints

Works alongside MkDocstrings for comprehensive API documentation.

Usage

Basic Setup

  1. Enable the plugin in mkdocs.yml
  2. Organize your code with proper docstrings
  3. Build documentation

The plugin automatically: - Scans source directories - Generates documentation pages - Creates navigation structure - Extracts docstrings

Project Structure

Text Only
project/
├── src/
│   ├── __init__.py
│   ├── core.py
│   ├── utils.py
│   └── models/
│       ├── __init__.py
│       └── user.py
├── docs/
│   └── index.md
└── mkdocs.yml

Generated Documentation

MkAutodoc creates:

Text Only
docs/
├── index.md
└── api/
    ├── index.md
    ├── core.md
    ├── utils.md
    └── models/
        ├── index.md
        └── user.md

Code Example

Well-Documented Code

Python
"""
Core module for user management.

This module provides functionality for creating, updating,
and managing user accounts.
"""

from typing import Optional, List
from datetime import datetime


class User:
    """
    Represents a user in the system.

    Attributes:
        id: Unique user identifier
        username: User's username
        email: User's email address
        created_at: Account creation timestamp
    """

    def __init__(
        self,
        username: str,
        email: str,
        id: Optional[int] = None
    ):
        """
        Initialize a new user.

        Args:
            username: The user's username
            email: The user's email address
            id: Optional user ID (auto-generated if not provided)
        """
        self.id = id
        self.username = username
        self.email = email
        self.created_at = datetime.now()

    def update_email(self, new_email: str) -> bool:
        """
        Update the user's email address.

        Args:
            new_email: The new email address

        Returns:
            True if update successful, False otherwise

        Raises:
            ValueError: If email format is invalid
        """
        if not self._validate_email(new_email):
            raise ValueError("Invalid email format")
        self.email = new_email
        return True

    @staticmethod
    def _validate_email(email: str) -> bool:
        """Validate email format."""
        return "@" in email and "." in email


def get_user_by_id(user_id: int) -> Optional[User]:
    """
    Retrieve a user by their ID.

    Args:
        user_id: The ID of the user to retrieve

    Returns:
        User object if found, None otherwise

    Examples:
        >>> user = get_user_by_id(1)
        >>> print(user.username)
        'john_doe'
    """
    # Implementation here
    pass


def list_users(limit: int = 10, offset: int = 0) -> List[User]:
    """
    List users with pagination.

    Args:
        limit: Maximum number of users to return
        offset: Number of users to skip

    Returns:
        List of User objects
    """
    # Implementation here
    pass

Generated Output

MkAutodoc generates documentation that includes: - Module overview - Class documentation - Method signatures with type hints - Parameter descriptions - Return value documentation - Usage examples - Cross-references

Integration with MkDocstrings

Use both plugins together:

YAML
plugins:
  - mkautodoc:
      enabled: true
  - mkdocstrings:
      handlers:
        python:
          options:
            show_source: true

MkAutodoc: Generates structure and navigation MkDocstrings: Renders detailed API documentation

Best Practices

1. Write Comprehensive Docstrings

Python
def calculate_total(
    items: List[float],
    tax_rate: float = 0.1,
    discount: float = 0.0
) -> float:
    """
    Calculate total price with tax and discount.

    This function computes the total price by summing all items,
    applying a discount, and adding tax.

    Args:
        items: List of item prices
        tax_rate: Tax rate as decimal (default: 0.1 for 10%)
        discount: Discount amount to subtract (default: 0.0)

    Returns:
        Final total price including tax and discount

    Raises:
        ValueError: If tax_rate is negative
        ValueError: If discount is greater than subtotal

    Examples:
        >>> calculate_total([10.0, 20.0, 30.0])
        66.0
        >>> calculate_total([10.0, 20.0], tax_rate=0.2)
        36.0
        >>> calculate_total([100.0], discount=10.0)
        99.0

    Note:
        Tax is applied after discount is subtracted.
    """
    if tax_rate < 0:
        raise ValueError("Tax rate cannot be negative")

    subtotal = sum(items)

    if discount > subtotal:
        raise ValueError("Discount cannot exceed subtotal")

    total = (subtotal - discount) * (1 + tax_rate)
    return total

2. Use Type Hints

Python
from typing import Dict, List, Optional, Union

def process_data(
    data: Dict[str, List[int]],
    key: str,
    default: Optional[int] = None
) -> Union[List[int], int]:
    """Process data dictionary."""
    return data.get(key, default)

3. Organize Code Logically

Text Only
src/
├── core/           # Core functionality
├── utils/          # Utility functions
├── models/         # Data models
├── services/       # Business logic
└── api/            # API endpoints

4. Module-Level Documentation

Python
"""
Authentication Module

This module handles user authentication and authorization.
It provides functions for login, logout, token validation,
and permission checking.

Example:
    >>> from myapp.auth import login
    >>> user = login(username="admin", password="secret")
    >>> print(user.is_authenticated)
    True

Note:
    All authentication functions require a valid database
    connection to be established.
"""

5. Private vs Public API

Mark private members:

Python
def public_function():
    """This appears in documentation."""
    pass

def _private_function():
    """This is filtered out (by convention)."""
    pass

Configuration Options

enabled

Enable or disable the plugin: true or false

src_dirs

List of source directories to scan

ignore_patterns

File patterns to exclude from documentation

include_private

Include private members (starting with _)

Docstring Styles

MkAutodoc supports multiple styles:

Google Style

Python
def func(arg1, arg2):
    """
    Summary line.

    Args:
        arg1: Description
        arg2: Description

    Returns:
        Description

    Raises:
        ValueError: When something is wrong
    """

NumPy Style

Python
def func(arg1, arg2):
    """
    Summary line.

    Parameters
    ----------
    arg1 : type
        Description
    arg2 : type
        Description

    Returns
    -------
    type
        Description
    """

Sphinx Style

Python
def func(arg1, arg2):
    """
    Summary line.

    :param arg1: Description
    :param arg2: Description
    :return: Description
    :raises ValueError: When something is wrong
    """

Tips

  1. Use consistent docstring style across project
  2. Include examples in docstrings
  3. Document all public APIs
  4. Use meaningful type hints
  5. Keep modules focused and organized
  6. Add module-level documentation
  7. Cross-reference related functions
  8. Update docs when code changes