Skip to content

numpy

This module defines functions and classes to parse docstrings into structured data.

RE_DOCTEST_BLANKLINE = re.compile('^\\s*<BLANKLINE>\\s*$') module-attribute ¤

Regular expression to match lines of the form <BLANKLINE>.

RE_DOCTEST_FLAGS = re.compile('(\\s*#\\s*doctest:.+)$') module-attribute ¤

Regular expression to match lines containing doctest flags of the form # doctest: +FLAG.

Numpy ¤

Bases: Parser

A Numpy-style docstrings parser.

Source code in src/pytkdocs/parsers/docstrings/numpy.py
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
class Numpy(Parser):
    """A Numpy-style docstrings parser."""

    def __init__(self, trim_doctest_flags: bool = True, **kwargs: Any) -> None:  # noqa: FBT001, FBT002, ARG002
        """Initialize the objects.

        Arguments:
            trim_doctest_flags: Whether to remove doctest flags.
        """
        super().__init__()
        self.trim_doctest_flags = trim_doctest_flags
        self.section_reader = {
            Section.Type.PARAMETERS: self.read_parameters_section,
            Section.Type.EXCEPTIONS: self.read_exceptions_section,
            Section.Type.EXAMPLES: self.read_examples_section,
            Section.Type.ATTRIBUTES: self.read_attributes_section,
            Section.Type.RETURN: self.read_return_section,
        }

    def parse_sections(self, docstring: str) -> list[Section]:  # noqa: D102
        if "signature" not in self.context:
            self.context["signature"] = getattr(self.context["obj"], "signature", None)
        if "annotation" not in self.context:
            self.context["annotation"] = getattr(self.context["obj"], "type", empty)
        if "attributes" not in self.context:
            self.context["attributes"] = {}

        docstring_obj = parse(docstring)
        description_all = (
            none_str_cast(docstring_obj.short_description) + "\n\n" + none_str_cast(docstring_obj.long_description)
        ).strip()
        sections = [Section(Section.Type.MARKDOWN, description_all)] if description_all else []
        sections_other = [
            reader(docstring_obj) if sec == Section.Type.RETURN else reader(docstring, docstring_obj)  # type: ignore[operator]
            for (sec, reader) in self.section_reader.items()
        ]
        sections.extend([sec for sec in sections_other if sec])
        return sections

    def read_parameters_section(
        self,
        docstring: str,
        docstring_obj: Docstring,
    ) -> Optional[Section]:
        """Parse a "parameters" section.

        Arguments:
            docstring: The raw docstring.
            docstring_obj: Docstring object parsed by docstring_parser.

        Returns:
            A `Section` object (or `None` if section is empty).
        """
        parameters = []

        docstring_params = [p for p in docstring_obj.params if p.args[0] == "param"]

        for param in docstring_params:
            name = param.arg_name
            kind = None
            type_name = param.type_name
            default = param.default or empty
            try:
                signature_param = self.context["signature"].parameters[name.lstrip("*")]
            except (AttributeError, KeyError):
                self.error(f"No type annotation for parameter '{name}'")
            else:
                if signature_param.annotation is not empty:
                    type_name = signature_param.annotation
                if signature_param.default is not empty:
                    default = signature_param.default
                kind = signature_param.kind

            description = param.description or ""
            if not description:
                self.error(f"No description for parameter '{name}'")

            parameters.append(
                Parameter(
                    name=param.arg_name,
                    annotation=type_name,
                    description=description,
                    default=default,
                    kind=kind,
                ),
            )

        if parameters:
            return Section(Section.Type.PARAMETERS, parameters)
        if re.search("Parameters\n", docstring):
            self.error("Empty parameter section")
        return None

    def read_attributes_section(
        self,
        docstring: str,
        docstring_obj: Docstring,
    ) -> Optional[Section]:
        """Parse an "attributes" section.

        Arguments:
            docstring: The raw docstring.
            docstring_obj: Docstring object parsed by docstring_parser.

        Returns:
            A `Section` object (or `None` if section is empty).
        """
        attributes = []
        docstring_attributes = [p for p in docstring_obj.params if p.args[0] == "attribute"]

        for attr in docstring_attributes:
            description = attr.description or ""
            if not description:
                self.error(f"No description for attribute '{attr.arg_name}'")
            attributes.append(
                Attribute(
                    name=attr.arg_name,
                    annotation=attr.type_name,
                    description=description,
                ),
            )

        if attributes:
            return Section(Section.Type.ATTRIBUTES, attributes)
        if re.search("Attributes\n", docstring):
            self.error("Empty attributes section")
        return None

    def read_exceptions_section(
        self,
        docstring: str,
        docstring_obj: Docstring,
    ) -> Optional[Section]:
        """Parse an "exceptions" section.

        Arguments:
            docstring: The raw docstring.
            docstring_obj: Docstring object parsed by docstring_parser.

        Returns:
            A `Section` object (or `None` if section is empty).
        """
        exceptions = []
        except_obj = docstring_obj.raises

        for exception in except_obj:
            description = exception.description or ""
            if not description:
                self.error(f"No description for exception '{exception.type_name}'")
            exceptions.append(AnnotatedObject(exception.type_name, description))

        if exceptions:
            return Section(Section.Type.EXCEPTIONS, exceptions)
        if re.search("Raises\n", docstring):
            self.error("Empty exceptions section")
        return None

    def read_return_section(
        self,
        docstring_obj: Docstring,
    ) -> Optional[Section]:
        """Parse a "returns" section.

        Arguments:
            docstring_obj: Docstring object parsed by docstring_parser.

        Returns:
            A `Section` object (or `None` if section is empty).
        """
        if docstring_obj.returns:
            return_obj = docstring_obj.returns

            if return_obj.description:
                description = return_obj.description
            else:
                self.error("Empty return description")
                description = ""

            if self.context["signature"]:
                annotation = self.context["signature"].return_annotation
            else:
                annotation = self.context["annotation"]

            if annotation is empty and return_obj.type_name:
                annotation = return_obj.type_name

            if not annotation:
                self.error("No return type annotation")
                annotation = ""

            if annotation or description:
                return Section(Section.Type.RETURN, AnnotatedObject(annotation, description))

        return None

    def read_examples_section(
        self,
        docstring: str,
        docstring_obj: Docstring,
    ) -> Optional[Section]:
        """Parse an "examples" section.

        Arguments:
            docstring: The raw docstring.
            docstring_obj: Docstring object parsed by docstring_parser.

        Returns:
            A `Section` object (or `None` if section is empty).
        """
        text = next(
            (
                meta.description
                for meta in docstring_obj.meta
                if isinstance(meta, DocstringMeta) and meta.args[0] == "examples"
            ),
            "",
        )

        sub_sections = []
        in_code_example = False
        in_code_block = False
        current_text: list[str] = []
        current_example: list[str] = []

        if text:
            for line in text.split("\n"):
                if is_empty_line(line):
                    if in_code_example:
                        if current_example:
                            sub_sections.append((Section.Type.EXAMPLES, "\n".join(current_example)))
                            current_example = []
                        in_code_example = False
                    else:
                        current_text.append(line)

                elif in_code_example:
                    if self.trim_doctest_flags:
                        line = RE_DOCTEST_FLAGS.sub("", line)  # noqa: PLW2901
                        line = RE_DOCTEST_BLANKLINE.sub("", line)  # noqa: PLW2901
                    current_example.append(line)

                elif line.startswith("```"):
                    in_code_block = not in_code_block
                    current_text.append(line)

                elif in_code_block:
                    current_text.append(line)

                elif line.startswith(">>>"):
                    if current_text:
                        sub_sections.append((Section.Type.MARKDOWN, "\n".join(current_text)))
                        current_text = []
                    in_code_example = True

                    if self.trim_doctest_flags:
                        line = RE_DOCTEST_FLAGS.sub("", line)  # noqa: PLW2901
                    current_example.append(line)
                else:
                    current_text.append(line)

        if current_text:
            sub_sections.append((Section.Type.MARKDOWN, "\n".join(current_text)))
        elif current_example:
            sub_sections.append((Section.Type.EXAMPLES, "\n".join(current_example)))

        if sub_sections:
            return Section(Section.Type.EXAMPLES, sub_sections)

        if re.search("Examples\n", docstring):
            self.error("Empty examples section")
        return None

__init__(trim_doctest_flags=True, **kwargs) ¤

Initialize the objects.

Parameters:

Name Type Description Default
trim_doctest_flags bool

Whether to remove doctest flags.

True
Source code in src/pytkdocs/parsers/docstrings/numpy.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def __init__(self, trim_doctest_flags: bool = True, **kwargs: Any) -> None:  # noqa: FBT001, FBT002, ARG002
    """Initialize the objects.

    Arguments:
        trim_doctest_flags: Whether to remove doctest flags.
    """
    super().__init__()
    self.trim_doctest_flags = trim_doctest_flags
    self.section_reader = {
        Section.Type.PARAMETERS: self.read_parameters_section,
        Section.Type.EXCEPTIONS: self.read_exceptions_section,
        Section.Type.EXAMPLES: self.read_examples_section,
        Section.Type.ATTRIBUTES: self.read_attributes_section,
        Section.Type.RETURN: self.read_return_section,
    }

read_attributes_section(docstring, docstring_obj) ¤

Parse an "attributes" section.

Parameters:

Name Type Description Default
docstring str

The raw docstring.

required
docstring_obj Docstring

Docstring object parsed by docstring_parser.

required

Returns:

Type Description
Optional[Section]

A Section object (or None if section is empty).

Source code in src/pytkdocs/parsers/docstrings/numpy.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def read_attributes_section(
    self,
    docstring: str,
    docstring_obj: Docstring,
) -> Optional[Section]:
    """Parse an "attributes" section.

    Arguments:
        docstring: The raw docstring.
        docstring_obj: Docstring object parsed by docstring_parser.

    Returns:
        A `Section` object (or `None` if section is empty).
    """
    attributes = []
    docstring_attributes = [p for p in docstring_obj.params if p.args[0] == "attribute"]

    for attr in docstring_attributes:
        description = attr.description or ""
        if not description:
            self.error(f"No description for attribute '{attr.arg_name}'")
        attributes.append(
            Attribute(
                name=attr.arg_name,
                annotation=attr.type_name,
                description=description,
            ),
        )

    if attributes:
        return Section(Section.Type.ATTRIBUTES, attributes)
    if re.search("Attributes\n", docstring):
        self.error("Empty attributes section")
    return None

read_examples_section(docstring, docstring_obj) ¤

Parse an "examples" section.

Parameters:

Name Type Description Default
docstring str

The raw docstring.

required
docstring_obj Docstring

Docstring object parsed by docstring_parser.

required

Returns:

Type Description
Optional[Section]

A Section object (or None if section is empty).

Source code in src/pytkdocs/parsers/docstrings/numpy.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
def read_examples_section(
    self,
    docstring: str,
    docstring_obj: Docstring,
) -> Optional[Section]:
    """Parse an "examples" section.

    Arguments:
        docstring: The raw docstring.
        docstring_obj: Docstring object parsed by docstring_parser.

    Returns:
        A `Section` object (or `None` if section is empty).
    """
    text = next(
        (
            meta.description
            for meta in docstring_obj.meta
            if isinstance(meta, DocstringMeta) and meta.args[0] == "examples"
        ),
        "",
    )

    sub_sections = []
    in_code_example = False
    in_code_block = False
    current_text: list[str] = []
    current_example: list[str] = []

    if text:
        for line in text.split("\n"):
            if is_empty_line(line):
                if in_code_example:
                    if current_example:
                        sub_sections.append((Section.Type.EXAMPLES, "\n".join(current_example)))
                        current_example = []
                    in_code_example = False
                else:
                    current_text.append(line)

            elif in_code_example:
                if self.trim_doctest_flags:
                    line = RE_DOCTEST_FLAGS.sub("", line)  # noqa: PLW2901
                    line = RE_DOCTEST_BLANKLINE.sub("", line)  # noqa: PLW2901
                current_example.append(line)

            elif line.startswith("```"):
                in_code_block = not in_code_block
                current_text.append(line)

            elif in_code_block:
                current_text.append(line)

            elif line.startswith(">>>"):
                if current_text:
                    sub_sections.append((Section.Type.MARKDOWN, "\n".join(current_text)))
                    current_text = []
                in_code_example = True

                if self.trim_doctest_flags:
                    line = RE_DOCTEST_FLAGS.sub("", line)  # noqa: PLW2901
                current_example.append(line)
            else:
                current_text.append(line)

    if current_text:
        sub_sections.append((Section.Type.MARKDOWN, "\n".join(current_text)))
    elif current_example:
        sub_sections.append((Section.Type.EXAMPLES, "\n".join(current_example)))

    if sub_sections:
        return Section(Section.Type.EXAMPLES, sub_sections)

    if re.search("Examples\n", docstring):
        self.error("Empty examples section")
    return None

read_exceptions_section(docstring, docstring_obj) ¤

Parse an "exceptions" section.

Parameters:

Name Type Description Default
docstring str

The raw docstring.

required
docstring_obj Docstring

Docstring object parsed by docstring_parser.

required

Returns:

Type Description
Optional[Section]

A Section object (or None if section is empty).

Source code in src/pytkdocs/parsers/docstrings/numpy.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
def read_exceptions_section(
    self,
    docstring: str,
    docstring_obj: Docstring,
) -> Optional[Section]:
    """Parse an "exceptions" section.

    Arguments:
        docstring: The raw docstring.
        docstring_obj: Docstring object parsed by docstring_parser.

    Returns:
        A `Section` object (or `None` if section is empty).
    """
    exceptions = []
    except_obj = docstring_obj.raises

    for exception in except_obj:
        description = exception.description or ""
        if not description:
            self.error(f"No description for exception '{exception.type_name}'")
        exceptions.append(AnnotatedObject(exception.type_name, description))

    if exceptions:
        return Section(Section.Type.EXCEPTIONS, exceptions)
    if re.search("Raises\n", docstring):
        self.error("Empty exceptions section")
    return None

read_parameters_section(docstring, docstring_obj) ¤

Parse a "parameters" section.

Parameters:

Name Type Description Default
docstring str

The raw docstring.

required
docstring_obj Docstring

Docstring object parsed by docstring_parser.

required

Returns:

Type Description
Optional[Section]

A Section object (or None if section is empty).

Source code in src/pytkdocs/parsers/docstrings/numpy.py
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def read_parameters_section(
    self,
    docstring: str,
    docstring_obj: Docstring,
) -> Optional[Section]:
    """Parse a "parameters" section.

    Arguments:
        docstring: The raw docstring.
        docstring_obj: Docstring object parsed by docstring_parser.

    Returns:
        A `Section` object (or `None` if section is empty).
    """
    parameters = []

    docstring_params = [p for p in docstring_obj.params if p.args[0] == "param"]

    for param in docstring_params:
        name = param.arg_name
        kind = None
        type_name = param.type_name
        default = param.default or empty
        try:
            signature_param = self.context["signature"].parameters[name.lstrip("*")]
        except (AttributeError, KeyError):
            self.error(f"No type annotation for parameter '{name}'")
        else:
            if signature_param.annotation is not empty:
                type_name = signature_param.annotation
            if signature_param.default is not empty:
                default = signature_param.default
            kind = signature_param.kind

        description = param.description or ""
        if not description:
            self.error(f"No description for parameter '{name}'")

        parameters.append(
            Parameter(
                name=param.arg_name,
                annotation=type_name,
                description=description,
                default=default,
                kind=kind,
            ),
        )

    if parameters:
        return Section(Section.Type.PARAMETERS, parameters)
    if re.search("Parameters\n", docstring):
        self.error("Empty parameter section")
    return None

read_return_section(docstring_obj) ¤

Parse a "returns" section.

Parameters:

Name Type Description Default
docstring_obj Docstring

Docstring object parsed by docstring_parser.

required

Returns:

Type Description
Optional[Section]

A Section object (or None if section is empty).

Source code in src/pytkdocs/parsers/docstrings/numpy.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
def read_return_section(
    self,
    docstring_obj: Docstring,
) -> Optional[Section]:
    """Parse a "returns" section.

    Arguments:
        docstring_obj: Docstring object parsed by docstring_parser.

    Returns:
        A `Section` object (or `None` if section is empty).
    """
    if docstring_obj.returns:
        return_obj = docstring_obj.returns

        if return_obj.description:
            description = return_obj.description
        else:
            self.error("Empty return description")
            description = ""

        if self.context["signature"]:
            annotation = self.context["signature"].return_annotation
        else:
            annotation = self.context["annotation"]

        if annotation is empty and return_obj.type_name:
            annotation = return_obj.type_name

        if not annotation:
            self.error("No return type annotation")
            annotation = ""

        if annotation or description:
            return Section(Section.Type.RETURN, AnnotatedObject(annotation, description))

    return None

is_empty_line(line) ¤

Tell if a line is empty.

Parameters:

Name Type Description Default
line str

The line to check.

required

Returns:

Type Description
bool

True if the line is empty or composed of blanks only, False otherwise.

Source code in src/pytkdocs/parsers/docstrings/numpy.py
291
292
293
294
295
296
297
298
299
300
def is_empty_line(line: str) -> bool:
    """Tell if a line is empty.

    Arguments:
        line: The line to check.

    Returns:
        True if the line is empty or composed of blanks only, False otherwise.
    """
    return not line.strip()