За последние годы я написал несколько вариантов обратных вызовов autodoc-skip-member
для различных несвязанных проектов Python, потому что я хотел, чтобы такие методы, как __init__()
, __enter__()
и __exit__()
, отображались в моей документации API (в конце концов, эти «специальные методы» являются частью API, и что может быть лучше для их документирования, чем внутри строки документации специального метода).
Недавно я взял лучшую реализацию и сделал ее частью одного из моих проектов на Python ( вот документация ). Реализация в основном сводится к следующему:
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 ) который я считаю шумом и совсем не полезен. Подход обратного вызова избегает этого (потому что он работает только на функции / методы и игнорирует другие атрибуты).