MkAutodoc Plugin
Automatic documentation generation from code structure.
Core Attributes
Plugin Name
mkautodoc
Repository
Configuration
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
- Enable the plugin in
mkdocs.yml - Organize your code with proper docstrings
- Build documentation
The plugin automatically: - Scans source directories - Generates documentation pages - Creates navigation structure - Extracts docstrings
Project Structure
project/
├── src/
│ ├── __init__.py
│ ├── core.py
│ ├── utils.py
│ └── models/
│ ├── __init__.py
│ └── user.py
├── docs/
│ └── index.md
└── mkdocs.yml
Generated Documentation
MkAutodoc creates:
docs/
├── index.md
└── api/
├── index.md
├── core.md
├── utils.md
└── models/
├── index.md
└── user.md
Code Example
Well-Documented Code
"""
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:
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
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
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
src/
├── core/ # Core functionality
├── utils/ # Utility functions
├── models/ # Data models
├── services/ # Business logic
└── api/ # API endpoints
4. Module-Level Documentation
"""
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:
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
def func(arg1, arg2):
"""
Summary line.
Args:
arg1: Description
arg2: Description
Returns:
Description
Raises:
ValueError: When something is wrong
"""
NumPy Style
def func(arg1, arg2):
"""
Summary line.
Parameters
----------
arg1 : type
Description
arg2 : type
Description
Returns
-------
type
Description
"""
Sphinx Style
def func(arg1, arg2):
"""
Summary line.
:param arg1: Description
:param arg2: Description
:return: Description
:raises ValueError: When something is wrong
"""
Tips
- Use consistent docstring style across project
- Include examples in docstrings
- Document all public APIs
- Use meaningful type hints
- Keep modules focused and organized
- Add module-level documentation
- Cross-reference related functions
- Update docs when code changes