File: parse-docstrings.md

package info (click to toggle)
python-griffe 1.15.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,292 kB
  • sloc: python: 17,202; makefile: 47; sh: 24; javascript: 13
file content (36 lines) | stat: -rw-r--r-- 1,308 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# Using Griffe as a docstring-parsing library

You can use Griffe to parse arbitrary docstrings. You don't have to load anything through the Griffe loader. You just need to import the [`Docstring`][griffe.Docstring] class. Then you can build a `Docstring` instance and call its `parse` method, choosing the parsing-style to use:

```python
from griffe import Docstring

text = "Hello I'm a docstring!"
docstring = Docstring(text, lineno=1)
parsed = docstring.parse("google")
```

If you want to take advantage of the parsers ability to fetch annotations from the object from which the docstring originates, you can manually create the parent objects and link them to the docstring:

```python
from griffe import Docstring, Function, Parameters, Parameter, ParameterKind

function = Function(
    "func",
    parameters=Parameters(
        Parameter("param1", annotation="str", kind=ParameterKind.positional_or_keyword),
        Parameter("param2", annotation="int", kind=ParameterKind.keyword_only),
    ),
)
text = """
Hello I'm a docstring!

Parameters:
    param1: Description.
    param2: Description.
"""
docstring = Docstring(text, lineno=1, parent=function)
parsed = docstring.parse("google")
```

With this the parser will fetch the `str` and `int` annotations from the parent function's parameters.