[英]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.