在过去的几年中,我为几个不相关的 Python 项目编写了几个
autodoc-skip-member
回调函数的变体,因为我希望像
__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__
之类的属性的文档(在所有新式类上都可用,据我所知),而我认为这是噪音,没有任何用处。回调方法避免了这种情况(因为它仅适用于函数/方法并忽略其他属性)。
"both" Both the class’ and the __init__ method’s docstring are concatenated and inserted.
-> 因此,如果你有类的docstring,它不应该只是__init__(self)
,而且还应该包括类的docstring。你能提供一个测试用例吗?因为如果是这样,感觉像是一个bug,对吧? - László Papp