Path: blob/main/singlestoredb/docstring/parser.py
469 views
"""The main parsing routine."""1import inspect2import typing as T34from . import epydoc5from . import google6from . import numpydoc7from . import rest8from .attrdoc import add_attribute_docstrings9from .common import Docstring10from .common import DocstringStyle11from .common import ParseError12from .common import RenderingStyle1314_STYLE_MAP = {15DocstringStyle.REST: rest,16DocstringStyle.GOOGLE: google,17DocstringStyle.NUMPYDOC: numpydoc,18DocstringStyle.EPYDOC: epydoc,19}202122def parse(23text: T.Optional[str], style: DocstringStyle = DocstringStyle.AUTO,24) -> Docstring:25"""Parse the docstring into its components.2627:param text: docstring text to parse28:param style: docstring style29:returns: parsed docstring representation30"""31if style != DocstringStyle.AUTO:32return _STYLE_MAP[style].parse(text)3334exc: T.Optional[Exception] = None35rets = []36for module in _STYLE_MAP.values():37try:38ret = module.parse(text)39except ParseError as ex:40exc = ex41else:42rets.append(ret)4344if not rets and exc is not None:45raise exc4647return sorted(rets, key=lambda d: len(d.meta), reverse=True)[0]484950def parse_from_object(51obj: T.Any,52style: DocstringStyle = DocstringStyle.AUTO,53) -> Docstring:54"""Parse the object's docstring(s) into its components.5556The object can be anything that has a ``__doc__`` attribute. In contrast to57the ``parse`` function, ``parse_from_object`` is able to parse attribute58docstrings which are defined in the source code instead of ``__doc__``.5960Currently only attribute docstrings defined at class and module levels are61supported. Attribute docstrings defined in ``__init__`` methods are not62supported.6364When given a class, only the attribute docstrings of that class are parsed,65not its inherited classes. This is a design decision. Separate calls to66this function should be performed to get attribute docstrings of parent67classes.6869:param obj: object from which to parse the docstring(s)70:param style: docstring style71:returns: parsed docstring representation72"""73docstring = parse(obj.__doc__, style=style)7475if inspect.isclass(obj) or inspect.ismodule(obj):76add_attribute_docstrings(obj, docstring)7778return docstring798081def compose(82docstring: Docstring,83style: DocstringStyle = DocstringStyle.AUTO,84rendering_style: RenderingStyle = RenderingStyle.COMPACT,85indent: str = ' ',86) -> str:87"""Render a parsed docstring into docstring text.8889:param docstring: parsed docstring representation90:param style: docstring style to render91:param indent: the characters used as indentation in the docstring string92:returns: docstring text93"""94st = docstring.style if style == DocstringStyle.AUTO else style95if st is None:96raise ValueError('Docstring style must be specified')97return _STYLE_MAP[st].compose(98docstring, rendering_style=rendering_style, indent=indent,99)100101102