【问题标题】:How do I get sphinx to recognize decorated python functions如何让 sphinx 识别装饰的 python 函数
【发布时间】:2017-08-03 10:16:16
【问题描述】:

Sphinx 不记录用装饰器包装的函数。我曾尝试使用类风格装饰器和函数风格装饰器,但无济于事。这些函数没有出现在我生成的 html 中,而同一模块中的其他函数确实出现了

唯一成功的方法是用装饰器装饰器包装我的类装饰器,但这不会在类中使用__call__ 函数,我需要从装饰器返回一个值

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

然后我有一个运行的批处理文件

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

这会生成一个名为 testfunctions.rst 的文件,其中包含 testfunctions 文件夹中每个模块的部分

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

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

【问题讨论】:

  • 使用minimal reproducible example,可能会更容易提供帮助。
  • 所有功能都记录在案
  • 只是示例代码
  • 您提到了一个带有__call__ 方法的类。它不在您的示例代码中。
  • 我尝试将装饰器实现为一个类,看看是否有帮助,但没有。你有什么建议吗?

标签: python python-sphinx python-decorators


【解决方案1】:

这是documented in sphinx manual

注意

如果您记录修饰的函数或方法,请记住 autodoc 通过导入模块并检查给定函数或方法的 doc 属性来检索其文档字符串。这意味着如果一个装饰器用另一个装饰器替换了被装饰的函数,它必须将原来的 doc 复制到新的函数中。 从 Python 2.5 开始,functools.wraps() 可用于创建行为良好的装饰函数。

【讨论】:

  • 我已经尝试过了,问题是函数的签名发生了变化,参数列表隐藏在 *args 和 **kwargs 后面,我看不到函数中定义的参数
  • 至少你的装饰函数确实出现了,是吗?-)
  • 不,他们没有出现
猜你喜欢
  • 2021-05-17
  • 2014-09-25
  • 2013-01-20
  • 2022-07-04
  • 1970-01-01
  • 2019-03-20
  • 2018-01-19
  • 1970-01-01
  • 2011-04-10
相关资源
最近更新 更多