gpt4 book ai didi

python - 如何防止 Sphinx 将 "object"列为基类?

转载 作者:太空狗 更新时间:2023-10-30 00:58:58 30 4
gpt4 key购买 nike

我有这门课:

class Class:
pass

sphinx 生成的文档(以防万一,我使用了 autodoc 扩展)如下所示:

class package.Class

     Bases: object

object 的继承对读者来说不是有用的信息,因此我不希望它出现在我的文档中。我想看到的输出是这样的:

class package.Class


有没有办法从基类列表中排除object

最佳答案

这其实深深嵌入the autodoc source code ,无法将其关闭:

bases = [b.__module__ in ('__builtin__', 'builtins') and
u':class:`%s`' % b.__name__ or
u':class:`%s.%s`' % (b.__module__, b.__name__)
for b in self.object.__bases__]
self.add_line(u' ' + _(u'Bases: %s') % ', '.join(bases), sourcename)

object 没有得到任何特殊处理;没有内置方法可以将其从列表中排除。


我能找到的最佳(自动)解决方案是 monkeypatch autodoc。

将此添加到 conf.py 可以实现所需的行为:

# ClassDocumenter.add_directive_header uses ClassDocumenter.add_line to
# write the class documentation.
# We'll monkeypatch the add_line method and intercept lines that begin
# with "Bases:".
# In order to minimize the risk of accidentally intercepting a wrong line,
# we'll apply this patch inside of the add_directive_header method.

from sphinx.ext.autodoc import ClassDocumenter, _

add_line = ClassDocumenter.add_line
line_to_delete = _(u'Bases: %s') % u':class:`object`'

def add_line_no_object_base(self, text, *args, **kwargs):
if text.strip() == line_to_delete:
return

add_line(self, text, *args, **kwargs)

add_directive_header = ClassDocumenter.add_directive_header

def add_directive_header_no_object_base(self, *args, **kwargs):
self.add_line = add_line_no_object_base.__get__(self)

result = add_directive_header(self, *args, **kwargs)

del self.add_line

return result

ClassDocumenter.add_directive_header = add_directive_header_no_object_base

关于python - 如何防止 Sphinx 将 "object"列为基类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46279030/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com