在sphinx中包含特定的特殊方法

mgi*_*son 15 python python-sphinx

我有一堆使用"特殊方法"的类:

class Foo(object):
   "Foo docstring"

   attr1 = "Attribute!" #: first attribute
   attr2 = "Another Attribute!" #: second attribute

   def __init__(self):
       self.x = 12

   def say_hello(self):
       """
       say_hello(self) -> None

       Issue a friendly greeting.
       """
       print "Hello! x is {0}".format(self.x)

   def __contains__(self,other):
       """Implement ``other in self``"""
       return other == self.x
Run Code Online (Sandbox Code Playgroud)

现在我想使用Sphinx和autodoc为此生成html文档.我如何告诉Sphinx记录__contains__?我尝试添加

autodoc_default_flags = ['members', 'undoc-members', 'special-members']
Run Code Online (Sandbox Code Playgroud)

conf.py,但也包括__dict__我绝对不想要的.

目前,该myproject.rst文件的相关部分如下所示:

.. automodule:: myproject.foomodule
    :members:
    :undoc-members:
    :show-inheritance:
Run Code Online (Sandbox Code Playgroud)

编辑添加

.. automodule:: myproject.foomodule
    :members:
    :undoc-members:
    :show-inheritance:

.. automethod:: myproject.foomodule.Foo.__contains__
Run Code Online (Sandbox Code Playgroud)

确实添加了该方法的文档,但是在单独的部分中 - 不作为Foo类文档的一部分.

aru*_*aku 15

你可以加:

:special-members:
:exclude-members: __dict__,__weakref__
Run Code Online (Sandbox Code Playgroud)

.rst文件中以显示特殊成员,除了__dict____weakref__


小智 9

对我有用的是添加".. automethod :: methodName "

类的docstring中的指令,而不是在.rst文件中执行.

所以,你可以改变"Foo docstring"

"""
Foo docstring

.. automethod:: __contains__
"""
Run Code Online (Sandbox Code Playgroud)


mzj*_*zjn 7

现在,特殊成员选项接受参数(这是Sphinx 1.2的新功能)。

所以这应该工作:

.. automodule:: myproject.foomodule
    :members:
    :undoc-members:
    :special-members: __contains__
    :show-inheritance:
Run Code Online (Sandbox Code Playgroud)


Yar*_*nko 5

从 Sphinx 1.8 开始,您可以conf.py. 例子:

autodoc_default_options = {
    'members': 'var1, var2',
    'member-order': 'bysource',
    'special-members': '__init__',
    'undoc-members': True,
    'exclude-members': '__weakref__'
}
Run Code Online (Sandbox Code Playgroud)

将 None 或 True 设置为值相当于仅向指令提供选项名称。

请注意,您可以在一个字符串中给出多个值:“ __init__,__call__”。


mgi*_*son 3

我目前对这个解决方案并不是 100% 兴奋,所以我希望有人可以一起改进它。但是,我解决这个问题的方法是执行以下操作:

.. automodule:: myproject.foomodule
    :members:
    :undoc-members:
    :show-inheritance:

    .. autoclass:: myproject.foomodule.Foo
        :exclude-members: attr1,attr2

        .. autoattribute:: myproject.foomodule.Foo.attr1 

        .. autoattribute:: myproject.foomodule.Foo.attr2 

        .. automethod:: myproject.foomodule.Foo.__contains__
Run Code Online (Sandbox Code Playgroud)

在这里,我实际上需要告诉autodoc避免(自动)记录类属性,然后我需要显式地将它们添加回来。原因是因为显然当您显式嵌套命令时,显式命令会先出现。如果我只明确地说添加__contains__,那么它会显示在我不喜欢的属性之前。