![](/img/trans.png)
[英]How can I provide Sphinx documentation for a namedtuple (with autodoc)?
[英]Python: Sphinx namedtuple documentation
我正在嘗試記錄命名元組。 當我構建文檔時,我收到警告WARNING: duplicate object description
和記錄后的相同空函數。 例如:
如何刪除這些別名? 我已經嘗試過這個解決方案,在conf.py
中編寫了幾個函數來創建空屬性。
另外,我認為值得一提的是,在構建后我得到了一個使用說明:noindex:
但我不明白我應該在哪里使用它? 在我的文檔字符串、rst 文件或其他地方?
代碼示例:
File = namedtuple("File", ["path", "size", "extension",
"adate", "mdate", "links",
"user_owner", "group_owner",
"inode", "device", "permissions",
"depth"])
"""File attributes.
.. py:attribute:: path
**-** path to the found file
.. note::
depending on command-line arguments can be absolute or relative
...
我在記錄命名元組時遇到了同樣的問題。 這是我的解決方案。
不要在您的 autodoc 指令中使用:members:
選項。
Example.rst 文件:
.. documentation for module with namedtuple
Module with namedtuple
======================
.. automodule:: packagename.modulename
.. autoclass:: packagename.modulename.namedtuplename
此外,為了讓 Sphinx 獲取我的 namedtuple 文檔字符串,我必須使用它的__doc__
屬性。 所以使用你的例子:
File = namedtuple("File", ["path", ..., "depth"])
File.__doc__ = """File attributes.
.. :attribute:: path
...
"""
automodule::
指令獲取模塊的文檔字符串autoclass::
指令獲取 namedtuple 的文檔字符串。 使用 autodoc 的首選(也是通常)方法是使用:members:
選項並遞歸地記錄模塊中的所有內容。 但是當模塊包含一個命名元組時,使用:members:
選項(帶有任一指令)會在文檔中生成別名。
使用automodule::
, :members:
選項使 Sphinx 遞歸記錄成員:首先是模塊的成員(namedtuple 的類),然后是成員的成員(該類的屬性)。 這會拾取由 namedtuple 創建的 class 的重復屬性,從而導致別名問題。
使用autoclass:
, :members:
選項再次選擇重復的 class 屬性,從而導致別名問題。
_fields
重復項的基本機制是文檔字符串中記錄的 class 屬性已記錄為 namedtuple 的字段名稱( 請參閱文檔)。 此行為內置於命名元組中; 我不確定如何覆蓋它。
要查看這個底層機制,請打開一個 REPL 並列出您的_fields
的 _fields:
>>> File._fields
要查看重復文檔問題導致別名消息的位置,請獲取有關 namedtuple 的幫助:
>>> help(File)
如果您繼續滾動瀏覽文檔,您最終應該會看到如下內容:
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| adate
| Alias for field number 3
|
| depth
| Alias for field number 11
同樣重要的是,namedtuple 使用與其類型相同的名稱,就像您所做的那樣:
File = namedtuple("File", ["path", ..., "depth"])
無論如何這是約定,但由於它不是必需的,因此值得注意的是,使用不同的名稱將導致class而不是 class 屬性的別名問題。
sphinx-toolbox
對此提供了解決方案,有關更多信息,請參見此處。
要使用它,您需要為pip
用戶安裝sphinx-toolbox
:
pip install sphinx-toolbox
然后將擴展名插入conf.py
。
extensions = [
...
'sphinx_toolbox.more_autodoc.autonamedtuple',
]
沒有更多的配置:)
我遇到了一個比接受的答案更好的解決方案,我只是想分享它:
只需在你的 conf.py 中寫下:
# -- Post process ------------------------------------------------------------
import collections
def remove_namedtuple_attrib_docstring(app, what, name, obj, skip, options):
if type(obj) is collections._tuplegetter:
return True
return skip
def setup(app):
app.connect('autodoc-skip-member', remove_namedtuple_attrib_docstring)
這會從所有 NamedTuple 類中刪除使用此“字段別名..”自動記錄的所有參數。
這使用 autodoc 事件autodoc-skip-member
每次遇到任何類型的成員時都會觸發處理程序
app.connect('autodoc-skip-member', remove_namedtuple_attrib_docstring)
將處理程序remove_namedtuple_attrib_docstring
到事件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.