<p>在过去的几年中,我为各种不相关的Python项目编写了<code>autodoc-skip-member</code>回调的几个变体,因为我希望像<code>__init__()</code>、<code>__enter__()</code>和<code>__exit__()</code>这样的方法出现在我的API文档中(毕竟,这些“特殊方法”是API的一部分,有什么地方比在特殊方法的docstring中更好地记录它们)。</p>
<p>最近,我把最好的实现作为我的一个Python项目(<a href="https://humanfriendly.readthedocs.io/en/latest/api.html#humanfriendly.sphinx.enable_special_methods" rel="nofollow noreferrer">here's the documentation</a>)的一部分。<a href="https://github.com/xolox/python-humanfriendly/blob/master/humanfriendly/sphinx.py" rel="nofollow noreferrer">The implementation</a>基本上可以归结为:</p>
<pre><code>def setup(app):
"""Enable Sphinx customizations."""
enable_special_methods(app)
def enable_special_methods(app):
"""
Enable documenting "special methods" using the autodoc_ extension.
:param app: The Sphinx application object.
This function connects the :func:`special_methods_callback()` function to
``autodoc-skip-member`` events.
.. _autodoc: http://www.sphinx-doc.org/en/stable/ext/autodoc.html
"""
app.connect('autodoc-skip-member', special_methods_callback)
def special_methods_callback(app, what, name, obj, skip, options):
"""
Enable documenting "special methods" using the autodoc_ extension.
Refer to :func:`enable_special_methods()` to enable the use of this
function (you probably don't want to call
:func:`special_methods_callback()` directly).
This function implements a callback for ``autodoc-skip-member`` events to
include documented "special methods" (method names with two leading and two
trailing underscores) in your documentation. The result is similar to the
use of the ``special-members`` flag with one big difference: Special
methods are included but other types of members are ignored. This means
that attributes like ``__weakref__`` will always be ignored (this was my
main annoyance with the ``special-members`` flag).
The parameters expected by this function are those defined for Sphinx event
callback functions (i.e. I'm not going to document them here :-).
"""
if getattr(obj, '__doc__', None) and isinstance(obj, (types.FunctionType, types.MethodType)):
return False
else:
return skip
</code></pre>
<p>是的,有比逻辑更多的文档:-)。与使用<code>special-members</code>选项(对我来说)相比,定义这样的<code>autodoc-skip-member</code>回调的好处是<code>special-members</code>选项还支持<code>__weakref__</code>(可用于所有新样式类,AFAIK)等属性的文档,我认为这些属性是噪音,根本没有用处。回调方法避免了这一点(因为它只对函数/方法起作用,而忽略其他属性)。</p>