我正在使用Sphinx的自动摘要为我的模块的每个成员自动生成单独的rst文件。文档是按预期创建的,只是生成的rst文件缺少除__init__以外的所有dunder方法。
在我的conf.py中,我有以下几行:
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
]
autosummary_generate = True
autosummary_imported_members = True考虑下面的虚拟类,它既包含and方法,也包含常规公共方法:
class MyClassA:
def __init__(self):
r'__init__ docstring'
pass
def __call__(self):
r'__call__ docstring'
pass
def __len__(self):
r'__len__ docstring'
pass
def public_method_1(self):
r'public_method_1 docstring'
pass
def public_method_2(self):
r'public_method_2 docstring'
pass在我的主rst文件中,我设置了如下自动摘要:
.. autosummary::
:toctree: my_module_members
my_module.MyClassA
my_module.MyClassB正如预期的那样,自动摘要为模块的每个成员创建了一个名为/my_module_members的子目录,其中包含单独的rst文件。但是这些自动生成的rst文件的方法部分中只列出了__init__。例如:
my_module.MyClassA
==================
.. currentmodule:: my_module
.. autoclass:: MyClassA
.. rubric:: Methods
.. autosummary::
~MyClassA.__init__
~MyClassA.public_method_1
~MyClassA.public_method_2因此,在生成的html文档中,方法表中只列出了这三个方法,而__call__和__len__不存在:

那么,我的问题是,在以这种方式使用自动摘要时,如何包含所有特殊的方法?
发布于 2020-06-02 21:15:26
问题在于自动摘要为类使用的默认模板。这是文档中的相关页面,但是直接查看默认模板会更有帮助:
# In the sphinx v3.0.4 source code:
# sphinx/ext/autosummary/templates/autosummary/class.rst
{{ fullname | escape | underline}}
.. currentmodule:: {{ module }}
.. autoclass:: {{ objname }}
{% block methods %}
.. automethod:: __init__
{% if methods %}
.. rubric:: Methods
.. autosummary::
{% for item in methods %}
~{{ name }}.{{ item }}
{%- endfor %}
{% endif %}
{% endblock %}
{% block attributes %}
{% if attributes %}
.. rubric:: Attributes
.. autosummary::
{% for item in attributes %}
~{{ name }}.{{ item }}
{%- endfor %}
{% endif %}
{% endblock %}您可以看到这个模板如何与为您的项目生成的存根文件相对应(虽然我不知道为什么您的模板缺少.. automethod:: __init__行;也许我们有不同版本的sphinx)。重要的部分是{% for item in methods %}循环。上面链接的文档简要地提到,methods只包含"public“方法,这意味着不以下划线开头的方法。__init__()也被认为是公共的,如sphinx/ext/autosummary/generate.py的第242行所示,尽管这似乎没有任何文档记录。所以希望这能解释你所看到的行为。
考虑到这一点,我可以想到在文档中包含所有特殊方法的三种方法:
members而不是methods的自定义模板。这应该记录所有的东西,但是会消除方法、属性、继承的成员、内部类等之间的区别。methods替换all_methods,将所有方法都包含在自动摘要中(请再次参阅第242行)。不过,公共方法和私有方法之间不会有任何区别。发布于 2020-07-25 18:02:30
最后,我使用了一个自定义类模板来解决这个问题,该模板查找all_methods,然后过滤掉所有私有类,以及要包含的dunder方法列表中的而不是。
{{ fullname | escape | underline}}
.. currentmodule:: {{ module }}
.. autoclass:: {{ objname }}
{% block methods %}
{% if methods %}
.. rubric:: {{ ('Methods') }}
.. autosummary::
{% for item in all_methods %}
{%- if not item.startswith('_') or item in ['__init__',
'__repr__',
'__len__',
'__call__',
'__next__',
'__iter__',
'__getitem__',
'__setitem__',
'__delitem__',
] %}
~{{ name }}.{{ item }}
{%- endif -%}
{%- endfor %}
{% endif %}
{% endblock %}
{% block attributes %}
{% if attributes %}
.. rubric:: {{ ('Attributes') }}
.. autosummary::
{% for item in attributes %}
~{{ name }}.{{ item }}
{%- endfor %}
{% endif %}
{% endblock %}https://stackoverflow.com/questions/62142793
复制相似问题