Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: Attribute docstring parsing for dataclasses #28

Open
phil65 opened this issue Feb 11, 2025 · 4 comments
Open

Feature request: Attribute docstring parsing for dataclasses #28

phil65 opened this issue Feb 11, 2025 · 4 comments

Comments

@phil65
Copy link

phil65 commented Feb 11, 2025

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!

@tlambert03
Copy link
Member

hey @phil65, thanks for your note

Yeah, attribute docstrings has been coming up recently at griffe-fieldz as well: pyapp-kit/griffe-fieldz#17

is your use case outside of generating documentation? I'd kind of like to avoid AST parsing if we can avoid it, but i agree it shouldn't be terribly hard (and I can look at how pydantic does it)

@phil65
Copy link
Author

phil65 commented Feb 11, 2025

Yes, I also have use cases outside of documentation. Would be cool if it could get added, but otherwise it´s not a big deal if you follow a no-AST policy here, I would just wrap your library then and special-case dataclasses.

@tlambert03
Copy link
Member

no policy :) i'm open to it. let's have a look 👍

@phil65
Copy link
Author

phil65 commented Feb 11, 2025

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants