pydantic-settings
pydantic-settings copied to clipboard
Request for "with_attr_docs" feature
As mentioned in https://github.com/pydantic/pydantic/pull/4492, I have been using https://github.com/danields761/pydantic-settings/ mostly for its with_attrs_docs
decorator. (That being said, I wanted to link to its documentation here, but cannot find it…)
It greatly reduces the visual noise / clutter when documenting fields that otherwise do not even need a Field()
.
Hence, I would love to see this be supported in this new project as well (not caring so much about the actual syntax / import, in case the name should change).
Well this is embarrassing, after looking into with_attrs_docs
it seems like it would actually make more sense to implement this in pydantic itself or in a separate library (if it requires multiple extra dependencies), sorry for pointing you here :facepalm:.
Still, I'll leave the issue here for now and we can think more about the idea and how to implement it when we're nearer to V2 release.
More information on what this does, from here:
Extracts fields documentation
Allows to extract Sphinx style attributes documentation by processing AST tree of class definition
from pydantic import BaseModel
from pydantic_settings import with_attrs_docs
@with_attrs_docs
class Foo(BaseModel):
bar: str
"""here is docs"""
#: docs for baz
baz: int
#: yes
#: of course
is_there_multiline: bool = True
assert Foo.__fields__['bar'].field_info.description == 'here is docs'
assert Foo.__fields__['baz'].field_info.description == 'docs for baz'
assert Foo.__fields__['is_there_multiline'].field_info.description == (
'yes\nof course'
)
Would you accept a PR that adds a more limited form of this functionality? From looking into pydantic_settings (and the related class_doc) most of the code has to do with parsing comments. If you only support docstrings it's under 100 lines of code.
Yes I think so, would love to review a PR.
So you mean only the bar
format in the example above would be supported? I must say that I would have to get used to that format (which seems to be a strange de-facto standard in the ecosystem, but not officially supported by python itself), but I would still be happy to have that feature!
This has now been implemented in https://github.com/pydantic/pydantic/pull/6563. When it's released (not in 2.6.0, unfortunately) use_attribute_docstrings
in the model config will activate the feature.
Released in v2.7!
It would be great if the documentation had an annotation that this feature is only available with 2.7 or later—since ConfigDict doesn't reject unknown kwargs, it took me 10 minutes of playing around to discover that the reason it wasn't working was that my version (2.5) didn't support it.
I've added a docs update to resolve this issue. Thanks folks!