Box of handy tools for Sphinx providing comprehensive extensions and enhancements for documentation generation.
Modern Python feature documentation including Protocol, TypedDict, namedtuple, generics, and enhanced type hint processing. These extensions enable Sphinx to automatically document advanced Python typing features introduced in Python 3.5+ that aren't fully supported by standard autodoc.
Automatic documentation for typing.Protocol classes with proper method signature extraction and inheritance handling.
class ProtocolDocumenter(ClassDocumenter):
"""Autodocumenter for typing.Protocol classes."""
objtype = 'protocol'
directivetype = 'protocol'
priority = ClassDocumenter.priority + 1
@classmethod
def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: Any) -> bool:
"""Check if member can be documented as Protocol."""
def add_content(self, more_content: Optional[StringList], no_docstring: bool = False) -> None:
"""Add Protocol-specific content including method signatures."""
def get_object_members(self, want_all: bool) -> Tuple[bool, List[Tuple[str, Any]]]:
"""Get Protocol members including abstract methods."""Usage in code:
from typing import Protocol
class Drawable(Protocol):
def draw(self) -> None:
"""Draw the object."""
...In documentation:
.. autoprotocol:: mymodule.Drawable
:members:Specialized documenter for typing.TypedDict classes showing keys, types, and totality.
class TypedDictDocumenter(ClassDocumenter):
"""Autodocumenter for TypedDict classes."""
objtype = 'typeddict'
directivetype = 'class'
priority = ClassDocumenter.priority + 1
@classmethod
def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: Any) -> bool:
"""Check if member is a TypedDict."""
def add_content(self, more_content: Optional[StringList], no_docstring: bool = False) -> None:
"""Add TypedDict keys and type information."""
def get_type_comment(self, obj: Any) -> Optional[str]:
"""Get type comment for TypedDict keys."""Usage in code:
from typing import TypedDict
class PersonDict(TypedDict):
name: str
age: int
email: strIn documentation:
.. autotypeddict:: mymodule.PersonDictEnhanced documentation for collections.namedtuple and typing.NamedTuple classes.
class NamedTupleDocumenter(ClassDocumenter):
"""Autodocumenter for namedtuple classes."""
objtype = 'namedtuple'
directivetype = 'class'
priority = ClassDocumenter.priority + 1
@classmethod
def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: Any) -> bool:
"""Check if member is a namedtuple."""
def add_content(self, more_content: Optional[StringList], no_docstring: bool = False) -> None:
"""Add namedtuple fields and type information."""
def document_members(self, all_members: bool = False) -> None:
"""Document namedtuple fields as attributes."""Usage in code:
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
def distance_from_origin(self) -> float:
return (self.x ** 2 + self.y ** 2) ** 0.5In documentation:
.. autonamedtuple:: mymodule.Point
:members:Pretty printing and documentation for generic type aliases.
class PrettyGenericAliasDocumenter(DataDocumenter):
"""Enhanced documentation for generic aliases like List[str], Dict[str, int]."""
objtype = 'genericalias'
directivetype = 'data'
priority = DataDocumenter.priority + 1
@classmethod
def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: Any) -> bool:
"""Check if member is a generic alias."""
def add_content(self, more_content: Optional[StringList], no_docstring: bool = False) -> None:
"""Add pretty-printed generic alias information."""
def format_signature(self, **kwargs: Any) -> str:
"""Format generic alias signature."""Improved type hint formatting and cross-referencing in documentation.
def format_annotation(annotation: Any, config: Config) -> str:
"""
Format type annotation for documentation.
Args:
annotation: Type annotation object
config: Sphinx configuration
Returns:
Formatted annotation string with proper cross-references
"""
def stringify_typehint(annotation: Any, mode: str = 'fully-qualified') -> str:
"""
Convert type hint to string representation.
Args:
annotation: Type annotation to stringify
mode: Formatting mode ('fully-qualified', 'smart', 'short')
Returns:
String representation of type hint
"""
def process_docstring(app: Sphinx, what: str, name: str, obj: Any, options: Any, lines: List[str]) -> None:
"""Process docstring to enhance type information."""Enhanced documentation for module-level variables and class attributes.
class VariableDocumenter(DataDocumenter):
"""Enhanced documenter for variables with type annotation support."""
def add_content(self, more_content: Optional[StringList], no_docstring: bool = False) -> None:
"""Add variable type and value information."""
def get_type_annotation(self) -> Optional[str]:
"""Get type annotation for variable."""
def format_signature(self, **kwargs: Any) -> str:
"""Format variable signature with type information."""Automatic source code links for documented objects.
def add_source_links(app: Sphinx, what: str, name: str, obj: Any, options: Any, lines: List[str]) -> None:
"""
Add source code links to documented objects.
Args:
app: Sphinx application
what: Type of object being documented
name: Object name
obj: Object being documented
options: Autodoc options
lines: Documentation lines
"""
class SourceLinkMixin:
"""Mixin class for adding source links to autodocumenters."""
def add_source_link(self) -> None:
"""Add source link to documentation."""Enhanced support for documenting TypeVar declarations.
def process_typevars(app: Sphinx, what: str, name: str, obj: Any, options: Any, lines: List[str]) -> None:
"""
Process TypeVar declarations in documentation.
Args:
app: Sphinx application
what: Type of object
name: Object name
obj: Object being documented
options: Autodoc options
lines: Documentation lines
"""
class TypeVarDocumenter(DataDocumenter):
"""Specialized documenter for TypeVar objects."""
objtype = 'typevar'
directivetype = 'data'Documentation support for @overload decorated functions.
def process_overloads(app: Sphinx, what: str, name: str, obj: Any, options: Any, lines: List[str]) -> None:
"""
Process function overloads for documentation.
Args:
app: Sphinx application
what: Type of object
name: Object name
obj: Function with overloads
options: Autodoc options
lines: Documentation lines
"""
class OverloadDocumenter(FunctionDocumenter):
"""Documenter that handles overloaded functions."""
def format_signature(self, **kwargs: Any) -> str:
"""Format all overload signatures."""Enhanced documentation for classes with generic base classes.
class GenericBasesClassDocumenter(ClassDocumenter):
"""Documenter that properly handles generic base classes."""
def format_bases(self) -> Optional[str]:
"""Format generic base classes with proper type parameters."""
def get_type_params(self) -> List[str]:
"""Get type parameters from generic bases."""Enhanced autodoc extensions add several configuration options:
# Type hint processing
all_typevars = True
no_unbound_typevars = False
typehints_fully_qualified = False
typehints_use_signature = True
# Source links
source_link_target = "github" # "github" or "docs"
source_link_pattern = "https://github.com/{username}/{repository}/blob/{revision}/{path}#L{lineno}"
# Overload handling
overloads_location = "bottom" # "top", "bottom", or "signature"
# Generic alias formatting
generic_alias_formatting = "pretty"The enhanced autodoc extensions include proper error handling:
class AutodocProcessingError(Exception):
"""Base exception for autodoc processing errors."""
class TypeHintError(AutodocProcessingError):
"""Raised when type hint processing fails."""
class GenericAliasError(AutodocProcessingError):
"""Raised when generic alias processing fails."""Install with Tessl CLI
npx tessl i tessl/pypi-sphinx-toolbox