過去数年間、私はさまざまな無関係な Python プロジェクトのコールバックのいくつかのバリアントを作成してきました。これは、やautodoc-skip-member
のようなメソッドを API ドキュメントに表示したかったからです(結局のところ、これらの「特別なメソッド」は API の一部であり、より適切な場所はありません)。特別なメソッドの docstring 内よりもそれらを文書化します)。__init__()
__enter__()
__exit__()
最近、私は最良の実装を採用し、それを私の Python プロジェクトの 1 つに含めました (ここにドキュメントがあります)。実装は基本的に次のようになります。
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
オプションにより、(すべての新しいスタイルのクラスで利用可能、AFAIK) のようなプロパティのドキュメント化も可能になること__weakref__
です。これはノイズであり、まったく役に立たないと考えています。コールバック アプローチはこれを回避します (関数/メソッドでのみ機能し、他の属性を無視するため)。