stubpy.docstring¶
stubpy.docstring¶
Docstring type inference — parse parameter and return types from structured docstrings when no explicit annotation is present.
Three docstring conventions are supported:
NumPy style:
Parameters
----------
x : int
Description of x.
items : list[str], optional
Description of items.
Returns
-------
float
Description of the return value.
Google style:
Args:
x (int): Description of x.
items (list[str], optional): Description of items.
Returns:
float: Description of the return value.
Sphinx / reST style:
:param int x: Description of x.
:type items: list[str]
:returns: Description.
:rtype: float
The public API is a single function: parse_docstring_types().
Usage in stub generation¶
When infer_types_from_docstrings is
True and a parameter has no annotation, parse_docstring_types()
is called and any inferred type is emitted as an inline comment:
def foo(
x, # type: int -- inferred from docstring
y: str,
) -> None: ...
The # type: comment style keeps inferred types visually distinct from
developer-supplied annotations so the origin is always clear.
Multiple docstring formats in the same docstring are supported: all
parsers run and their results are merged, so a developer who uses
NumPy-style params but an :rtype: Sphinx return tag will get full
coverage.
- class DocstringTypes(params: dict[str, str]=<factory>, returns: str | None = None)[source]¶
Bases:
objectResult of parsing one docstring for type information.
Examples
>>> dt = DocstringTypes(params={"x": "int", "y": "str"}, returns="float") >>> dt.params["x"] 'int' >>> dt.returns 'float'
- is_empty() bool[source]¶
Return
Truewhen no type information was extracted.Examples
>>> DocstringTypes().is_empty() True >>> DocstringTypes(params={"x": "int"}).is_empty() False
- merge(other: DocstringTypes) DocstringTypes[source]¶
Return a new
DocstringTypesmerging self with other.self’s values take precedence; other fills gaps.
- Parameters:
other (DocstringTypes) – The secondary result to fill in missing entries from.
- Returns:
DocstringTypes – A merged result.
Examples
>>> a = DocstringTypes(params={"x": "int"}, returns=None) >>> b = DocstringTypes(params={"y": "str"}, returns="float") >>> m = a.merge(b) >>> sorted(m.params.items()) [('x', 'int'), ('y', 'str')] >>> m.returns 'float'
- parse_docstring_types(docstring: str | None) DocstringTypes[source]¶
Parse type information from a structured docstring.
Runs NumPy, Google, and Sphinx/reST parsers and merges all results so mixed-style docstrings receive full coverage.
- Parameters:
docstring (str or None) – Raw docstring text.
Noneor empty strings return an emptyDocstringTypes.- Returns:
DocstringTypes – Merged type information from all parsers. May be empty if no types were found.
Examples
>>> parse_docstring_types(None).is_empty() True >>> result = parse_docstring_types( ... "Args:\n x (int): desc\n y (str): desc\nReturns:\n float: value" ... ) >>> result.params {'x': 'int', 'y': 'str'} >>> result.returns 'float'