简体   繁体   中英

How do I get sphinx to recognize decorated python functions

Sphinx does not document functions wrapped with a decorator. I have tried using class style decorators and function style decorators but to no avail. These functions do not appear in my generated html whereas other functions in the same module do appear

The only hack that has semi-worked is by wrapping my class decorator with the decorator decorator but this then doesn't use the __call__ function in the class and I need to return a value from the decorator

import decorator
import functools

@decorator.decorator
def MyDecoratorA(fn, *args, **kwargs):
    # do things
    return fn(*args, **kwargs)

def MyDecoratorB(fn):

    @functools.wraps(fn)
    def inner(*args, **kwargs):
        # do things
        return fn(*args, **kwargs)
    return inner


@MyDecoratorA
def TestA(a, b=None):
    """This is a doc

    :param a: variable b
    :type a: int
    :param b: variable b
    :type b: list
    :returns: None
    """
    pass

@MyDecoratorB
def TestB(a, b=None):
    """This is a doc

    :param a: variable b
    :type a: int
    :param b: variable b
    :type b: list
    :returns: None
    """
    pass

I then have a batch file that runs

sphinx-apidoc -f -l -M -T -o /tmp/source/testfunctions ${DIR}/modules/testfunctions/ 1>/dev/null
make html

This generates a file called testfunctions.rst with a section for each module within the testfunctions folder

testfunctions.cluster module
----------------------------

.. automodule:: testfunctions.cluster
    :members:
    :undoc-members:
    :show-inheritance:

This is documented in sphinx manual :

Note

If you document decorated functions or methods, keep in mind that autodoc retrieves its docstrings by importing the module and inspecting the doc attribute of the given function or method. That means that if a decorator replaces the decorated function with another, it must copy the original doc to the new function. From Python 2.5, functools.wraps() can be used to create well-behaved decorating functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM