【问题标题】:Getting Sphinx autodoc to include 'hidden' classes让 Sphinx autodoc 包含“隐藏”类
【发布时间】:2015-04-07 17:46:07
【问题描述】:

我们有一个模块,其中每个类文件都在一个以下划线开头的文件中。在 init.py 中,我们导入这些文件,并为每个类公开构造函数(这是必要的,因为每个类构造函数都需要一些我们不希望模块用户需要的额外状态打扰)。

例如我们可能有 _foo.py:

class Foo(object):
  def __init(context, params):
    ...

init.py 中我们有:

from ._foo import Foo as _Foo

def foo(params):
  return _Foo(_getContext(), params)

我正在尝试为此使用 Sphinx autodoc 生成文档。我显然希望为 Foo 及其方法(尽管最好不是它的构造函数)以及 foo() 构造函数包装器生成文档。

我可以让 Sphinx 为 foo() 生成文档,但似乎无法让它为 Foo 生成任何内容。我试过了:

.. automodule:: foo_module
    :members:

还有:

.. autoclass:: foo_module.Foo
    :members:

但无济于事。前者只包括 foo();后者给了我一个错误:

index.rst:17: WARNING: autodoc: failed to import class u'Foo' from module u'foo_module'; the following exception was raised:
Traceback (most recent call last):
  File "/python2.7/site-packages/sphinx/ext/autodoc.py", line 342, in import_object
    obj = self.get_attr(obj, part)
  File "/python2.7/site-packages/sphinx/ext/autodoc.py", line 241, in get_attr
    return safe_getattr(obj, name, *defargs)
  File "/python2.7/site-packages/sphinx/util/inspect.py", line 114, in safe_getattr
    raise AttributeError(name)
AttributeError: Foo

有没有办法解决这个问题?

【问题讨论】:

  • 尝试定义__all__以包含_Foo
  • 这行得通,但这意味着我们确实公开了 Foo 构造函数。我想没有办法解决这个问题,因为“Foo.__init__”没有记录为一种方法,而是作为一个类头文件“class Foo(context, params)”。尽管实际上它不适用于 _Foo;我必须将 init 更改为使用“from ._foo import Foo”并在它起作用之前删除下划线。
  • 不要把__init__方法直接放在类上;而是将其命名为_init(假设您没有记录“私人”成员)并在类中包含__init__ = _init。 :-)

标签: python python-sphinx autodoc


【解决方案1】:

很久以前,但是...

也只需使用指令选项:private-members:

来自https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2012-02-09
    • 2012-05-09
    • 2015-02-04
    相关资源
    最近更新 更多