Dumping Comments¶
Writing YAML models with comments has been a hotly-requested feature, as comments are one of the (many) features why YAML is nicer than JSON for human-facing configuration.
Adding Descriptions¶
The preferred way is to use typing.Annotated
and pydantic.Field
for fields, and just docstrings for models:
1 2 3 4 5 6 7 8 |
|
or via configuring the model_config
to use docstrings as descriptions:
1 2 3 4 5 6 7 |
|
Both of these options will work to create:
1 2 3 4 |
|
with output:
1 2 |
|
See the Pydantic docs for more options how to add descriptions in Pydantic v2 and in Pydantic v1.
More Options¶
Note that you can also export just the headers:
1 |
|
1 2 |
|
or just the fields:
1 |
|
1 |
|
Dumping Example Classes¶
If you just want to create example YAML files, you have several main options:
- Create a fully-fledged example showing options. This might be time-consuming, but is probably best for your users.
- "Construct" the example models using
model_construct()
for v2 (justconstruct()
for v1) and useNone
for fields that are not optional but still need to be added. - Your docstrings and descriptions will still be used, so might be a bit confusing to users. Consider
add_comments="fields-only"
. - Create a parallel 'documentation model' where you instruct users in your docstrings/descriptions (rather than document code) and have some examples (or None) as default values.
- This is the most time-consuming, but gives you the most control.
Example of option 2:
1 2 |
|
gives
1 |
|