将sphinx autodoc用于fabfile

Mat*_*tin 6 python fabric python-sphinx autodoc

是否可以使用Sphinx autodoc从函数docstrings生成我的fabfile文档?

例如,对于包含setup_development我尝试过的任务的fabfile :

.. automodule::fabfile
   :members:
   .. autofunction:: setup_development
Run Code Online (Sandbox Code Playgroud)

但没有产生任何东西.

fabfile片段:

@task
def setup_development(remote='origin', branch='development'):
    """Setup your development environment.

    * Checkout development branch & pull updates from remote
    * Install required python packages
    * Symlink development settings
    * Sync and migrate database
    * Build HTML Documentation and open in web browser

    Args:
        remote: Name of remote git repository. Default: 'origin'.
        branch: Name of your development branch. Default: 'development'.
    """
    <code>
Run Code Online (Sandbox Code Playgroud)

mzj*_*zjn 1

通过使用模块文档中找到的decorator_apply配方,我能够生成带有保留函数签名的完整文档。decorator

""" myfabfile.py """

from fabric.api import task as origtask
from decorator import FunctionMaker

def decorator_apply(dec, func):
    return FunctionMaker.create(
        func, 'return decorated(%(signature)s)',
        dict(decorated=dec(func)), __wrapped__=func)

def task(func):
    return decorator_apply(origtask, func)

@task
def setup_development(remote='origin', branch='development'):
    """Setup your development environment.

    * Checkout development branch & pull updates from remote
    * Install required python packages
    * Symlink development settings
    * Sync and migrate database
    * Build HTML Documentation and open in web browser

    :param remote: Name of remote git repository.
    :param branch: Name of your development branch.
    """
    pass
Run Code Online (Sandbox Code Playgroud)

这是我使用的简单 ReST 源:

.. automodule:: myfabfile
   :members:
Run Code Online (Sandbox Code Playgroud)

一些评论:

@taskshahjapan 提交的答案解释了如何在一般情况下保留文档字符串,但它没有解决装饰器是在外部库中定义的事实。

无论如何,事实证明,对于用 . 修饰的函数,文档字符串会自动保留@task。以下是__init__Fabrictasks.WrappedCallableTask类的方法中:

if hasattr(callable, '__doc__'):
    self.__doc__ = callable.__doc__
Run Code Online (Sandbox Code Playgroud)

所以这已经可以正常工作了(.. autofunction::需要明确的)。为了确保保留函数签名,decorator可以按如上所示使用该模块。


更新

该模块的使用decorator破坏了 Fabric 的工作方式(参见评论)。所以这可能终究是不可行的。作为替代方案,我建议使用以下修改后的 reST 标记:

.. automodule:: myfabfile2
   :members: 

   .. autofunction:: setup_development(remote='origin', branch='development')
Run Code Online (Sandbox Code Playgroud)

也就是说,您必须包含完整的函数签名。这也是 Sphinx 文档中建议的内容(请参阅“如果方法的签名被装饰器隐藏,这很有用。”)