beanbag_docutils.sphinx.ext.autodoc_utils

Sphinx extension to add utilities for autodoc.

This enhances autodoc support for Beanbag’s docstring format and to allow for excluding content from docs.

Beanbag’s Docstrings

By setting napoleon_beanbag_docstring = True in conf.py, and turning off napoleon_google_docstring, Beanbag’s docstring format can be used.

This works just like the Google docstring format, but with a few additions:

  • A new Context: section to describe what happens within the context of a context manager (including the variable).

  • New Model Attributes: and Option Args: sections for defining the attributes on a model or the options in a dictionary when using JavaScript.

  • New Deprecated:, Version Added:, and Version Changed: sections for defining version-related information.

  • Parsing improvements to allow for wrapping argument types across lines, which is useful when you have long module paths that won’t fit on one line.

This requires the sphinx.ext.napoleon module to be loaded.

Excluding Content

A module can define top-level __autodoc_excludes__ or __deprecated__ lists. These are in the same format as __all__, in that they take a list of strings for top-level classes, functions, and variables. Anything listed here will be excluded from any autodoc code.

__autodoc_excludes__ is particularly handy when documenting an __init__.py that imports contents from a submodule and re-exports it in __all__. In this case, autodoc would normally output documentation both in __init__.py and the submodule, but that can be avoided by setting:

__autodoc_excludes = __all__

Excludes can also be defined globally, filtered by the type of object the docstring would belong to. See the documentation for autodoc-skip-member for more information. You can configure this in conf.py by doing:

autodoc_excludes = {
    # Applies to modules, classes, and anything else.
    '*': [
        '__annotations__',
        '__dict__',
        '__doc__',
        '__module__',
        '__weakref__',
    ],
    'class': [
        # Useful for Django models.
        'DoesNotExist',
        'MultipleObjectsReturned',
        'objects',

        # Useful forms.
        'base_fields',
        'media',
    ],
}

That’s just an example, but a useful one for Django users.

By default, autodoc_excludes is set to:

autodoc_excludes = {
    # Applies to modules, classes, and anything else.
    '*': [
        '__dict__',
        '__doc__',
        '__module__',
        '__weakref__',
    ],
}

If overriding, you can set '__defaults__': True to merge your changes in with these defaults.

Changed in version 2.0: Changed from a default of an empty dictionary, and added the __defaults__ option.

Better Documentation for Inherited TypedDicts

Added in version 3.0.

When a TypedDict inherits from another, the actual MRO is flattened, leaving any attributes that come from the parent classes without docstrings/comments in the generated documentation. Including autodoc_utils will automatically fix these to scan the original base classes when docs are missing for some members.

This uses __orig_bases__, which was added for TypedDict in Python 3.11. If using this with older versions of Python, typing_extensions.TypedDict should be used instead.

Setup

Changed in version 2.0: Improved setup by enabling other default extensions and options when enabling this extension.

To use this, add the extension in conf.py:

extensions = [
    ...
    'beanbag_docutils.sphinx.ext.autodoc_utils',
    ...
]

This will automatically enable the sphinx.ext.autodoc, sphinx.ext.intersphinx, and sphinx.ext.napoleon extensions, and enable the following autodoc options:

autodoc_member_order = 'bysource'
autoclass_content = 'class'
autodoc_default_options = {
    'members': True,
    'special-members': True,
    'undoc-members': True,
    'show-inheritance': True,
}

These default options can be turned off by setting use_beanbag_autodoc_defaults=False.

Configuration

autodoc_excludes

Optional global exclusions to apply, as shown above.

napoleon_beanbag_docstring

Set whether the Beanbag docstring format should be used.

This is the default as of beanbag-docutils 2.0.

use_beanbag_autodoc_defaults

Set whether autodoc defaults should be used.

Added in version 2.0.

Functions

_filter_members(app, what, name, obj, skip, ...)

Filter members out of the documentation.

_on_config_inited(app, config)

Override default configuration settings for Napoleon.

_process_docstring(app, what, name, obj, ...)

Process a docstring.

_replace_config_default(config, name, ...)

Replace a default Sphinx configuration value.

setup(app)

Set up the Sphinx extension.

Classes

BeanbagAttributeDocumenter(directive, name)

An AttributeDocumenter that handles docstrings for inherited TypedDicts.

BeanbagClassDocumenter(*args)

A ClassDocumenter that handles docstrings for inherited TypedDicts.

BeanbagDocstring(*args, **kwargs)

Docstring parser for the Beanbag documentation.

ReturnsSectionOptions

Options for registering a "Returns"-like section.

class beanbag_docutils.sphinx.ext.autodoc_utils.BeanbagAttributeDocumenter(directive: DocumenterBridge, name: str, indent: str = '')

Bases: AttributeDocumenter

An AttributeDocumenter that handles docstrings for inherited TypedDicts.

Added in version 3.0.

get_attribute_comment(parent: Any, attrname: str) list[str] | None

Return the comment for the attribute.

Parameters:
  • parent (type) – The parent class of the attribute.

  • attrname (str) – The name of the attribute.

Returns:

The docstring/doc comment of the attribute, split into lines.

Return type:

list of str

class beanbag_docutils.sphinx.ext.autodoc_utils.BeanbagClassDocumenter(*args: Any)

Bases: ClassDocumenter

A ClassDocumenter that handles docstrings for inherited TypedDicts.

When a TypedDict inherits from another, the MRO is flattened so the class inherits directly from dict, making it so Sphinx can’t find docstrings/comments for attributes that come from parent classes. This class will iterate up the __orig_bases__ chain in order to find docstrings in parent classes.

The docstrings are returned here (in case any custom templates are using the loaded member data), and also cached in _found_docstrings, which is used by BeanbagAttributeDocumenter to actually output the documentation for the attributes.

Added in version 3.0.

get_object_members(want_all: bool) tuple[bool, list[ObjectMember]]

Get members for the class.

Parameters:

want_all (bool) – Whether to get all members for the class.

Returns:

A 2-tuple of:

Tuple:
  • 0 (bool) – Whether to check if the item is actually in the module. In effect this will always be False.

  • 1 (list of sphinx.ext.autodoc.ObjectMember) – The list of members to document.

Return type:

tuple

class beanbag_docutils.sphinx.ext.autodoc_utils.BeanbagDocstring(*args, **kwargs)

Bases: GoogleDocstring

Docstring parser for the Beanbag documentation.

This is based on the Google docstring format used by Napoleon, but with a few additions:

  • Support for describing contexts in a context manager (using the Context: section, which works like Returns or Yields).

  • Model Attributes: and Option Args: argument sections.

  • Parsing improvements for arguments to allow for wrapping across lines, for long module paths.

COMMA_RE = re.compile(',\\s*')
MAX_PARTIAL_TYPED_ARG_LINES = 3
__init__(*args, **kwargs) None

Initialize the parser.

Parameters:
  • *args (tuple) – Positional arguments for the parent.

  • **kwargs (dict) – Keyword arguments for the parent.

consume_lines(num_lines: int) None

Consume the specified number of lines.

This will ensure that these lines are not processed any further.

Added in version 1.9.

Parameters:

num_lines (int, optional) – The number of lines to consume.

extra_fields_sections: Sequence[tuple[str, str]] = [('keys', 'Keys'), ('model attributes', 'Model Attributes'), ('option args', 'Option Args'), ('tuple', 'Tuple')]
extra_returns_sections: Sequence[tuple[str, str, ReturnsSectionOptions]] = [('context', 'Context', {}), ('type', 'Type', {'require_type': True})]
extra_version_info_sections: Sequence[tuple[str, str]] = [('deprecated', 'deprecated'), ('version added', 'versionadded'), ('version changed', 'versionchanged')]
make_type_reference(type_str: str) str

Create references to types in a type string.

This will parse the string, separating out a type from zero or more suffixes (like , optional).

The type will be further parsed into a space-separated tokens. Each of those will be set as a reference, allowing Sphinx to try to link it. The exceptions are the words “of” and “or”, which we use to list optional types.

The suffixes are each formatted with emphasis.

Added in version 2.0.

Parameters:

type_str (str) – The string to parse and create references from.

Returns:

The new string.

Return type:

str

partial_typed_arg_end_re = re.compile('\\s*(.+?)\\s*\\):$')
partial_typed_arg_start_re = re.compile('\\s*(.+?)\\s*\\(\\s*(.*[^\\s]+)\\s*[^:)]*$')
peek_lines(num_lines: int = 1) list[str]

Return the specified number of lines without consuming them.

Added in version 1.9.

Parameters:

num_lines (int, optional) – The number of lines to return.

Returns:

The resulting lines.

Return type:

list of str

queue_line(line: str) None

Queue a line for processing.

This will place the line at the beginning of the processing queue.

Added in version 1.9.

Parameters:

line (str) – The line to queue.

register_fields_section(keyword: str, label: str) None

Register a fields section with the given keyword and label.

Parameters:
  • keyword (str) – The keyword used in the docs.

  • label (str) – The label outputted in the section.

register_returns_section(keyword: str, label: str, options: ReturnsSectionOptions | None = None) None

Register a Returns-like section with the given keyword and label.

Parameters:
  • keyword (str) – The keyword used in the docs.

  • label (str) – The label outputted in the section.

  • options (ReturnsSectionOptions, optional) –

    Options for the registration.

    Added in version 2.0.

register_version_info_section(keyword: str, admonition: str) None

Register a version section with the given keyword and admonition.

Parameters:
  • keyword (str) – The keyword used in the docs.

  • admonition (str) – The admonition to use for the section.

class beanbag_docutils.sphinx.ext.autodoc_utils.ReturnsSectionOptions

Bases: TypedDict

Options for registering a “Returns”-like section.

Added in version 3.0.

__optional_keys__ = frozenset({})
__orig_bases__ = (<function TypedDict>,)
__required_keys__ = frozenset({'require_type'})
__total__ = True
require_type: NotRequired[bool]

Whether the type is required, and assumed to be the first line.

beanbag_docutils.sphinx.ext.autodoc_utils.setup(app: Sphinx) ExtensionMetadata

Set up the Sphinx extension.

This sets up the configuration and event handlers needed for enhancing auto-doc support.

Parameters:

app (sphinx.application.Sphinx) – The Sphinx application to register configuration and listen to events on.