[英]How can I parse a numpydoc docstring and access components?
I'd like to parse a numpydoc docstring and access each component programatically.我想解析一个 numpydoc 文档字符串并以编程方式访问每个组件。
For example:例如:
def foobar(a, b):
'''Something something
Parameters
----------
a : int, default: 5
Does something cool
b : str
Wow
'''
What I'd like to do is:我想做的是:
parsed = magic_parser(foobar)
parsed.text # Something something
parsed.a.text # Does something cool
parsed.a.type # int
parsed.a.default # 5
I've been searching around and found things like numpydoc and napoleon but I haven't found any good leads for how to use them in my own program.我一直在四处寻找,找到了numpydoc和napoleon 之类的东西,但我还没有找到任何关于如何在我自己的程序中使用它们的好线索。 I'd appreciate any help.我很感激任何帮助。
You can use NumpyDocString from numpydoc
to parse docstrings into a Python-friendly structure.您可以使用 numpydoc 中的numpydoc
将文档字符串解析为 Python 友好的结构。
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'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"])
However, this won't work with the example you gave (nor a lot of the code I want to run this on) for reasons I don't understand.但是,由于我不明白的原因,这不适用于您提供的示例(也不是我想在其上运行的很多代码)。 Instead, you need to use the specific FunctionDoc
or ClassDoc
class, depending on your use-case.相反,您需要使用特定的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"])
I figured this all out by looking at this test in their source code .我通过在他们的源代码中查看这个测试来弄清楚这一切。 So, this isn't really documented, but hopefully is enough for you to get started.所以,这并没有真正记录在案,但希望足以让您开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.