Making the Click command decorator behave well for Sphinx auto-docs
This tip applies to decorated functions in general where the decorator happens to not correctly handle the docstring, thus breaking the autodoc features in Sphinx. It just happens that I had this particular problem with the command decorator in Click.
Click is Armin Ronacher's excellent Python library for creating command-line interfaces in Python. You can check out Click here: http://click.pocoo.org.
I love Click, but in a project I'm working on I want the auto-generated Sphinx documentation to include the docs for my CLI commands. As-is, Sphinx will generate docs for Click's built-in Command class, because that is what command-decorated functions end up being. To fix this, Click's command decorator needs to attach the __doc__
of the original function to the decorated. I handled this by making my own command decorator that is nearly identical to Click's:
from click.core import Command
from click.decorators import _make_command
def command(name=None, cls=None, **attrs):
if cls is None:
cls = Command
def decorator(f):
r = _make_command(f, name, attrs, cls)
r.__doc__ = f.__doc__
return r
return decorator
Use this decorator just like the one in Click. The only difference is the r.__doc__ = f.__doc__
part.
You will still need to be a bit explicit to get Sphinx to generate the docs for your decorated functions. You can either use .. autofunction::
directives for your commands explicitly, or, you can use the more general :imported-members:
directive and include :excluded-members:
for imported things you don't want documented.
Written by Scott Bradley
Related protips
1 Response
This //almost// works for me, but not quite. It preserves the docstring, but not the arguments.
WARNING: error while formatting arguments for myapplication.cli.foo: 'Command' object has no attribute '__bases__'
Looking at the docs for bonfire, this doesn't seem to be a problem for you. Any idea what I am missing?
Click==3.3
Sphinx==1.2.3