Skip to content

Feature request: Attribute docstring parsing for dataclasses #28

@phil65

Description

@phil65

Hey!
Really a fan of this library (and many other of your libraries too), so thank you for the work you put in first of all.

I wonder if it would be possible to support attribute docstrings for dataclasses for the description?
I think it needs parsing the AST, but I think it shouldnt be too complicated. Some code to show a POC:

def get_field_docs(cls: type) -> dict[str, Any]:
    source = dedent(inspect.getsource(cls))
    docstrings = {}
    for node in ast.walk(ast.parse(source)):
        if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): 
            if (docstring_node := node.value) and isinstance(
                docstring_node, ast.Constant
            ):
                docstrings[node.target.id] = docstring_node.value
    return docstrings

Not sure how robust this approach is, perhaps its worth it to check how pydantic for example does it (when use_attribute_docstrings is set to True),
but for me, this would be a very helpful addition.
Cheers and thank you!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions