【问题标题】:autosummary with toctree also lists imported members带有 toctree 的自动摘要还列出了导入的成员
【发布时间】:2014-08-20 12:46:06
【问题描述】:

我使用 Sphinx 和 autosummary 来生成 Python 软件的文档。它运行良好,但生成的 .rst 文件还列出了导入的函数和类,这不是我想要的行为。

例如带有文档字符串的包“packageex”:

"""
Package Example (:mod:`packageex`)
==================================

.. currentmodule:: packageex
.. autosummary::
   :toctree:

   module0
   module1
"""

会产生一个文件 packageex.module0.rst 与

Module0 (:mod:`packageex.module0`)
=================================

.. currentmodule:: packageex.module0

.. rubric:: Functions

.. autosummary::

   f0
   f1
   f2_imported
   f3_imported

.. rubric:: Classes

.. autosummary::

   Class0
   ClassImported

有没有办法只列出模块中定义的函数和类(而不是那些导入的)?

在 autodoc (http://sphinx-doc.org/latest/ext/autodoc.html) 的文档中,有“在带有 members 选项集的 automodule 指令中,只有 __module__ 属性等于给 automodule 的模块名称的模块成员才会被记录。这是为了防止记录导入的类或函数。如果要防止这种行为并记录所有可用成员,请设置imported-members选项。请注意,导入模块的属性将不会被记录,因为属性文档是通过解析源文件发现的当前模块的。”是否可以使用自动摘要获得相同的行为?

【问题讨论】:

标签: python python-sphinx toctree


【解决方案1】:

正如 mzjn 所提到的,这似乎是扩展自动摘要的已知奇怪行为。为了获得想要的行为(即防止列出导入的对象),我刚刚修改了函数get_members(sphinx.ext.autosummary.generate 的 l.166),如下所示:

def get_members(obj, typ, include_public=[], imported=False):
    items = []
    for name in dir(obj):
        try:
            obj_name = safe_getattr(obj, name)
            documenter = get_documenter(obj_name, obj)
        except AttributeError:
            continue
        if documenter.objtype == typ:
            try:
                cond = (
                    imported or 
                    obj_name.__module__ == obj.__name__
                    )
            except AttributeError:
                cond = True
            if cond:
                items.append(name)
    public = [x for x in items
              if x in include_public or not x.startswith('_')]
    return public, items

【讨论】:

  • 注意到这个问题在最新的 sphinx 中仍然存在。不知道为什么这里的代码没有修复它。非常遗憾。
  • 还有问题吗? github.com/sphinx-doc/sphinx/issues/1061 已关闭。
  • 仅供将来参考:该代码对我不起作用。为记录我的模块而生成的 .rst 文件是空的。小心使用!
猜你喜欢
  • 2016-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
相关资源
最近更新 更多