如何在Sphinx中的方法内自动修改函数

时间:2012-08-20 14:32:36

标签: python documentation python-sphinx restructuredtext

代码示例:

class A(object):
    def do_something(self):
        """ doc_a """
        def inside_function():
            """ doc_b """
            pass
        pass

我试过了:

.. autoclass:: A
    .. autofunction:: A.do_something.inside_function

但它不起作用。

有没有办法为我生成doc_b

1 个答案:

答案 0 :(得分:0)

函数内的函数位于局部变量范围内。函数的局部变量不能从函数外部访问:

>>> def x():
...    def y():
...       pass
... 
>>> x
<function x at 0x7f68560295f0>
>>> x.y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute 'y'

如果Sphinx无法获取对该函数的引用,则无法对其进行记录。

可能有效的解决方法是将函数分配给函数的变量,如下所示:

>>> def x():
...    def _y():
...       pass
...    x.y = _y
... 

起初无法访问:

>>> x.y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute 'y'

但是在第一次调用函数之后,它将是:

>>> x()
>>> x.y
<function _y at 0x1a720c8>

如果在Sphinx导入模块时执行该函数,这可能会有效。