6

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

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

.. automodule::fabfile
   :members:
   .. autofunction:: setup_development

但是什么也没有产生。

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>
4

2 回答 2

3

这是因为您在函数上应用了装饰器setup_development

您需要如下更新您的task功能,functools.wraps

from functools import wraps

def task(calling_func):
    @wraps(calling_func)
    def wrapper_func(self, *args, **kw):
        return calling_func(*args, **kw)
    return wrapper_func

如果您记录修饰的函数或方法,请记住 autodoc 通过导入模块并检查__doc__给定函数或方法的属性来检索其文档字符串。

这意味着如果一个装饰器用另一个装饰器替换了被装饰的函数,它必须将原来的函数复制__doc__到新的函数中。From Python 2.5functools.wraps()可用于创建行为良好的装饰功能。

参考:

于 2012-01-13T05:01:19.683 回答
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

这是我使用的简单 ReST 源:

.. automodule:: myfabfile
   :members:

一些评论:

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

无论如何,事实证明,文档字符串会自动为用@task. __init__Fabric的tasks.WrappedCallableTask类的方法中如下:

if hasattr(callable, '__doc__'):
    self.__doc__ = callable.__doc__

所以它已经按原样工作了(.. autofunction::需要一个明确的)。为了确保函数签名也被保留,decorator可以如上所示使用该模块。


更新

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

.. automodule:: myfabfile2
   :members: 

   .. autofunction:: setup_development(remote='origin', branch='development')

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

于 2012-02-19T12:33:01.130 回答