在过去的几年里,我autodoc-skip-member
为各种不相关的 Python 项目编写了几种回调变体,因为我想要像__init__()
,__enter__()
和__exit__()
出现在我的 API 文档中的方法(毕竟,这些“特殊方法”是 API 的一部分,还有什么更好的地方可以记录它们而不是在特殊方法的文档字符串中)。
最近,我采用了最好的实现,并将其作为我的 Python 项目之一(这里是文档)的一部分。实现基本上归结为:
import types
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
是的,有比逻辑更多的文档:-)。autodoc-skip-member
与使用该special-members
选项(对我而言)相比,定义这样的回调的优势在于,该special-members
选项还启用了属性的文档,例如__weakref__
(适用于所有新型类,AFAIK),我认为这些属性是噪音并且根本没有用。回调方法避免了这种情况(因为它只适用于函数/方法并忽略其他属性)。