How to autodoc a function inside a method in Sphinx

后端 未结 1 1040
渐次进展
渐次进展 2021-01-21 16:58

Code example:

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


        
1条回答
  •  时光取名叫无心
    2021-01-21 17:08

    A function within a function is at the local variable scope. The local variables of a function are not accessible from outside of the function:

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

    If Sphinx can't get a reference to the function, it can't document it.

    A workaround that might work is to assign the function to a variable of the function, like this:

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

    It won't be accessible at first:

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

    But after the first invocation of the function, it will be:

    >>> x()
    >>> x.y
    
    

    This might work if the function gets executed when Sphinx imports the module.

    0 讨论(0)
提交回复
热议问题