Skip to content

Support pydantic dataclasses #51

@eric-czech

Description

@eric-czech

I have had no issues using Pydantic dataclasses with draccus so far except that field descriptions are not parsed correctly in CLI help strings, e.g.:

# > cat pydantic_example.py
from pydantic import Field
from pydantic.dataclasses import dataclass
import draccus


@dataclass
class Config:

    batch_size: int = Field(
        default=128, 
        description="Batch size for training"
    )

@draccus.wrap()
def main(cfg: Config):
    """Main function."""
    print(cfg)


if __name__ == "__main__":
    main()

Show CLI help:

python pydantic_example.py --help
...
Config:

  --batch_size int    #  <---- The field description is ignored

Similarly, adding a comment near the field definition is both redundant and demonstrates that default values aren't processed correctly (i.e. the Field wrapper is not unwrapped):

+   # Batch size for training
    batch_size: int = Field(
        default=128, 
        description="Batch size for training"
    )

Show the help again:

python pydantic_example.py --help
...
Config:

  --batch_size int   Batch size for training (default: annotation=NoneType required=False default=128
                     description='Batch size for training')

Now there is a help comment, but not a great one.


I'll also note that It may be possible to support metadata in standard dataclass fields with a similar solution, e.g. from https://docs.pydantic.dev/latest/concepts/dataclasses/:

Image

The dataclasses.field used in this case comes from the Python standard library: https://docs.python.org/3/library/dataclasses.html#dataclasses.field.

Perhaps looking for both title and metadata in either dataclass field metadata or Pydantic Field instances would be a reasonable start.

Another better option IMO would be to provide an API allowing users to determine how necessary field metadata is parsed. It looks like draccus/wrappers/docstring.py#L65 would be where such a thing would need to plug in?

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