How to autodoc a function inside a method in Sphinx

后端 未结 1 1038
渐次进展
渐次进展 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
    <function x at 0x7f68560295f0>
    >>> x.y
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    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 "<stdin>", line 1, in <module>
    AttributeError: 'function' object has no attribute 'y'
    

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

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

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

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