CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-sphinx-automodapi

Sphinx extension for auto-generating API documentation for entire modules

Pending
Overview
Eval results
Files

autodoc-enhancements.mddocs/

Autodoc Enhancements

Enhancements to Sphinx's autodoc functionality that improve attribute documentation, particularly for complex class hierarchies and metaclass properties. These enhancements are essential for properly documenting advanced Python class patterns.

Capabilities

Enhanced Attribute Access

Improved attribute getter for type objects (classes) that handles metaclass properties correctly, ensuring that class-level properties are documented properly rather than being overshadowed by metaclass implementations.

def type_object_attrgetter(obj: type, attr: str, *defargs) -> object:
    """
    Enhanced attrgetter for type objects that handles metaclass properties.
    
    This function provides improved attribute access for classes that can handle
    class attributes implemented as properties on a metaclass. Unlike regular
    getattr(), this function returns the property object defined on the class
    rather than resolving metaclass properties.
    
    Parameters:
    - obj: The class object to get the attribute from
    - attr: Name of the attribute to retrieve
    - *defargs: Default arguments if attribute is not found
    
    Returns:
    - object: The requested attribute, preferring class-defined properties
             over metaclass properties
    
    Raises:
    - AttributeError: If attribute is not found and no default provided
    """

Usage Example

from sphinx_automodapi.autodoc_enhancements import type_object_attrgetter

class Meta(type):
    @property
    def foo(cls):
        return 'metaclass foo'

class MyClass(metaclass=Meta):
    @property
    def foo(self):
        """Docstring for MyClass.foo property."""
        return 'instance foo'

# Regular getattr returns metaclass property value
regular_result = getattr(MyClass, 'foo')  # 'metaclass foo'

# Enhanced getter returns the class property object
enhanced_result = type_object_attrgetter(MyClass, 'foo')  # <property object>
docstring = enhanced_result.__doc__  # 'Docstring for MyClass.foo property.'

Dataclass Support

Enhanced attribute access includes special handling for dataclass fields, allowing proper documentation of dataclass attributes even when they don't have default values.

# Dataclass field handling is built into type_object_attrgetter
# When AttributeError occurs, checks for dataclass fields:
# - Detects if obj is a dataclass using dataclasses.is_dataclass()
# - Looks up attribute in obj.__dataclass_fields__
# - Returns field.default if available

Integration with Sphinx

Setup Function

def setup(app: Sphinx) -> dict[str, bool]:
    """
    Set up autodoc enhancements with Sphinx.
    
    Registers the enhanced attribute getter and configures autodoc
    to use improved attribute access for type objects.
    
    Parameters:
    - app: Sphinx application instance
    
    Returns:
    - dict: Parallel processing compatibility flags
    
    Actions performed:
    - Sets up sphinx.ext.autodoc extension as dependency
    - Registers type_object_attrgetter for type objects
    - Configures AttributeDocumenter
    - Manages warning suppression during setup
    """

Attribute Documenter Configuration

The setup process includes configuration of Sphinx's AttributeDocumenter to work properly with the enhanced attribute access:

# Internal setup details:
app.add_autodoc_attrgetter(type, type_object_attrgetter)
app.add_autodocumenter(AttributeDocumenter)

Implementation Details

Method Resolution Order (MRO) Handling

The enhanced attribute getter uses Python's Method Resolution Order to find the correct attribute definition:

  1. MRO Traversal: Searches through obj.__mro__ to find where the attribute is defined
  2. Property Detection: Checks if the attribute in base.__dict__[attr] is a property
  3. Direct Return: Returns the property object directly for documentation purposes
  4. Fallback: Uses regular getattr() for non-property attributes

Metaclass Property Handling

The key improvement addresses a common issue in Python class documentation:

  • Problem: getattr(cls, 'property_name') resolves metaclass properties, hiding class properties
  • Solution: Direct __dict__ access finds class-defined properties before metaclass resolution
  • Benefit: Autodoc can properly document class properties with their actual docstrings

Dataclass Integration

Special handling for dataclass fields ensures comprehensive attribute documentation:

# Dataclass field resolution logic:
if dataclasses.is_dataclass(obj) and attr in obj.__dataclass_fields__:
    return obj.__dataclass_fields__[attr].default

Type Definitions

# Type hints used in the module
from typing import Any
from sphinx.application import Sphinx

# Internal constants
class_types = (type,)
MethodDescriptorType = type(type.__subclasses__)

Use Cases

Complex Class Hierarchies

When documenting frameworks or libraries with sophisticated class hierarchies where properties are defined at multiple levels.

Metaclass-Heavy Code

Essential for documenting code that makes extensive use of metaclasses, such as ORMs, validation frameworks, or DSL implementations.

Dataclass Documentation

Improves documentation quality for dataclass-heavy codebases by ensuring all fields are properly documented even when they lack explicit defaults.

Compatibility

The enhancements are designed to:

  • Work transparently with existing Sphinx autodoc functionality
  • Maintain backward compatibility with standard attribute access
  • Integrate seamlessly with other sphinx-automodapi components
  • Support parallel documentation generation

The module serves as a foundation for other sphinx-automodapi components, providing the enhanced attribute access needed for comprehensive API documentation generation.

Install with Tessl CLI

npx tessl i tessl/pypi-sphinx-automodapi

docs

autodoc-enhancements.md

configuration.md

directives.md

index.md

smart-resolution.md

utilities.md

tile.json