如何解析numpydoc文档字符串和访问组件?

时间:2016-06-20 18:56:52

标签: python parsing python-sphinx docstring

我想解析一个numpydoc docstring并以编程方式访问每个组件。

例如:

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

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

我想做的是:

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

我一直在搜索numpydocnapoleon之类的内容,但我没有找到任何有关如何在我自己的程序中使用它们的良好线索。我很感激任何帮助。

1 个答案:

答案 0 :(得分:7)

您可以使用numpydoc中的NumpyDocString将文档字符串解析为Python友好的结构。

这是如何使用它的一个例子:

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's gamma exposure.

    """

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

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

但是,由于我不理解的原因,这不适用于您提供的示例(我也没有很多代码要运行此代码)。相反,您需要使用特定的FunctionDocClassDoc类,具体取决于您的使用情况。

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"])

我通过查看this test in their source code来解决这个问题。所以,这并没有真正记录在案,但希望你已经足够开始了。

相关问题