Search code examples
pythonscopepython-sphinxrestructuredtextautodoc

How to autodoc a function inside a method in Sphinx


Code example:

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

I tried:

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

but it doesn't work.

Is there some way to generate doc_b for me?


Solution

  • 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.