Skip to main content
 首页 » 编程设计

python之如何在 Sphinx 中的方法内自动记录函数

2025年05月04日9mengfanrong

代码示例:

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?

请您参考如下方法:

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

>>> 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 导入模块时执行,这可能会起作用。