Search code examples
pythonpython-sphinxautodoc

Collect warnings and let Sphinx raise them


I am using autodoc-process-docstring to check for undocumented members

def warn_undocumented_members(app, what, name, obj, options, lines):
    if what in MEMBERS_TO_WARN and not lines:
        sys.stderr.write("<autodoc> WARNING: {} is undocumented: {}\n".format(what, name))

app.connect('autodoc-process-docstring', warn_undocumented_members)

Is there any possibility to bubble up the warnings in Sphinx?

I looked into the app object but could not find anything satisfying. The only thing I found is raising a SphinxError in the if clause, but this is stopping the build instead of collecting all warnings. Also this is not respecting the -W flag of sphinx-build (I always have a hard error).


Solution

  • Sphinx components pass warnings through the logging facility, for which Sphinx defines custom adapters in sphinx.util.logging. If you use the loggers provided there, Sphinx will treat your warnings the same as its own and respect the -W flag that turns them into errors.

    import sphinx
    logger = sphinx.util.logging.getLogger('sphinx.ext.autodoc')
    
    def warn_undocumented_members(app, what, name, obj, options, lines):
        if what in MEMBERS_TO_WARN and not lines:
            logger.warning(f'{what} is undocumented: {name}', type='autodoc')
    
    def setup(app):
        app.connect('autodoc-process-docstring', warn_undocumented_members)