[英]Using sphinx autodoc for a fabfile
是否可以使用 Sphinx autodoc 从函数文档字符串为我的 fabfile 生成文档?
例如,对于包含我尝试过的setup_development
任务的setup_development
:
.. 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>
这是因为您在函数setup_development
上应用了装饰器
您需要使用functools.wraps
更新您的task
功能,如下所示,
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__
复制到新的函数中。 从Python 2.5
, functools.wraps()
可用于创建行为良好的装饰函数。
参考:
通过使用decorator_apply
decorator
模块文档中的decorator_apply
配方,我能够生成带有保留函数签名的完整文档。
""" 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
修饰的函数保留。 以下是在 Fabric 的tasks.WrappedCallableTask
类的__init__
方法中:
if hasattr(callable, '__doc__'):
self.__doc__ = callable.__doc__
所以这已经可以正常工作了(需要一个显式的.. autofunction::
)。 为了确保函数签名也被保留,可以使用decorator
模块,如上所示。
更新
decorator
模块的使用破坏了 Fabric 的工作(见评论)。 所以这毕竟可能不可行。 作为替代方案,我建议使用以下修改后的 reST 标记:
.. automodule:: myfabfile2
:members:
.. autofunction:: setup_development(remote='origin', branch='development')
也就是说,您必须包含完整的函数签名。 这也是 Sphinx 文档中建议的内容(请参阅 “如果装饰器隐藏了方法的签名,这将很有用。”) 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.