Подтвердить что ты не робот

Извлечь reStructuredText из sphinx autodoc?

CPython не использует autodoc для своей документации - мы используем рукописную прозу.

Для PEP 3144 (модуль ipaddress) я хотел бы использовать sphinx-apidoc для создания исходной справочной документации. Это означает, что я хочу выполнить двухпроходную операцию:

  • Используйте sphinx-apidoc для извлечения проекта Sphinx для модуля, который зависит от autodoc

  • Запустите создатель sphinx, который создает новые исходные файлы reStructuredText, при этом все директивы autodoc заменяются встроенным контентом reStructuredText и разметкой, которая производит тот же вывод

Первый шаг прост, но я понятия не имею, как сделать второй шаг и даже не думаю о хороших способах поиска любых существующих проектов в этих строках.

4b9b3361

Ответ 2

Не полный ответ, более или менее отправная точка:

autodoc переводит автоматические директивы в директивы python. Таким образом, можно использовать события autodoc для получения переведенных директив python.

Например, если у вас есть следующий mymodule.py:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
This is my module.
"""

def my_test_func(a, b=1):
    """This is my test function"""
    return a + b 

class MyClass(object):
    """This is my class"""

    def __init__(x, y='test'):
        """The init of my class"""
        self.x = float(x)
        self.y = y 

    def my_method(self, z): 
        """This is my method.

        :param z: a number
        :type z: float, int
        :returns: the sum of self.x and z
        :rtype: float
        """
        return self.x + z 

sphinx-apidoc создаст

mymodule Module
===============

.. automodule:: mymodule
    :members:
    :undoc-members:
    :show-inheritance:

Следующее расширение (или дополнение к conf.py):

NAMES = []
DIRECTIVES = {}

def get_rst(app, what, name, obj, options, signature,
            return_annotation):
    doc_indent = '    '
    directive_indent = ''
    if what in ['method', 'attribute']:
        doc_indent += '    '
        directive_indent += '    '
    directive = '%s.. py:%s:: %s' % (directive_indent, what, name)
    if signature:  # modules, attributes, ... don't have a signature
        directive += signature
    NAMES.append(name)
    rst = directive + '\n\n' + doc_indent + obj.__doc__ + '\n'
    DIRECTIVES[name] = rst 

def write_new_docs(app, exception):
    txt = ['My module documentation']
    txt.append('-----------------------\n')
    for name in NAMES:
        txt.append(DIRECTIVES[name])
    print '\n'.join(txt)
    with open('../doc_new/generated.rst', 'w') as outfile:
        outfile.write('\n'.join(txt))

def setup(app):
    app.connect('autodoc-process-signature', get_rst)
    app.connect('build-finished', write_new_docs)

предоставит вам:

My module documentation
-----------------------

.. py:module:: mymodule


This is my module.


.. py:class:: mymodule.MyClass(x, y='test')

    This is my class

    .. py:method:: mymodule.MyClass.my_method(z)

        This is my method.

        :param z: a number
        :type z: float, int
        :returns: the sum of self.x and z
        :rtype: float


.. py:function:: mymodule.my_test_func(a, b=1)

    This is my test function

Однако, поскольку autodoc не выдает никакого события, когда перевод завершен, дальнейшая обработка, выполняемая autodoc, должна быть адаптирована к docstrings здесь.