9

我想解析一个 numpydoc 文档字符串并以编程方式访问每个组件。

例如:

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之类的东西,但我没有找到任何关于如何在我自己的程序中使用它们的好的线索。我会很感激任何帮助。

4

1 回答 1

14

您可以使用 NumpyDocString fromnumpydoc将文档字符串解析为 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"])

通过查看他们源代码中的这个测试,我发现了这一切。因此,这并没有真正记录在案,但希望足以让您开始。

于 2016-12-11T07:33:35.733 回答