How can I parse the numpydoc docstring and access the components?

I would like to parse the numpydoc docstring and access each component programmatically.

For instance:

def foobar(a, b):
   '''Something something

   Parameters
   ----------
   a : int, default: 5
        Does something cool
   b : str
        Wow
'''

I would like:

parsed = magic_parser(foobar)
parsed.text  # Something something
parsed.a.text  # Does something cool
parsed.a.type  # int
parsed.a.default  # 5

I searched and found things like numpydoc and napoleon , but I did not find any good examples of how to use them in my own program. I would appreciate any help.

+4
source share
1 answer

You can use NumpyDocString from numpydocto parse docstrings in a Python friendly structure.

This is an example of how to use it:

from numpydoc.docscrape import NumpyDocString


class Photo():
    """
    Array with associated photographic information.


    Parameters
    ----------
    x : type
        Description of parameter `x`.
    y
        Description of parameter `y` (with type not specified)

    Attributes
    ----------
    exposure : float
        Exposure in seconds.

    Methods
    -------
    colorspace(c='rgb')
        Represent the photo in the given colorspace.
    gamma(n=1.0)
        Change the photo gamma exposure.

    """

    def __init__(x, y):
        print("Snap!")

doc = NumpyDocString(Photo.__doc__)
print(doc["Summary"])
print(doc["Parameters"])
print(doc["Attributes"])
print(doc["Methods"])

( , ) , . FunctionDoc ClassDoc, .

from numpydoc.docscrape import FunctionDoc

def foobar(a, b):
   '''Something something

   Parameters
   ----------
   a : int, default: 5
        Does something cool
   b : str
        Wow
'''

doc = FunctionDoc(foobar)
print(doc["Parameters"])

, , , , , , .

+3

All Articles