pypae / pydantic-typer

Typer extension to enable pydantic support
MIT License
3 stars 0 forks source link

Options help from description. #2

Closed pablospe closed 2 months ago

pablospe commented 2 months ago

How to see the help description when doing --help?

import pydantic_typer
from pydantic import BaseModel, Field

class User(BaseModel):
    id: int = Field(..., description="The unique identifier for the user")
    name: str = Field("John Doe", description="The name of the user")

def main(user: User):
    print(user, type(user))

if __name__ == "__main__":
    pydantic_typer.run(main)

./test_cli.py --help

╭─ Options ───────────────────────────────────────────────────────────────╮
│ *  --user.id          INTEGER  [default: None] [required]               │
│    --user.name        TEXT     [default: John Doe]                      │
│    --help                      Show this message and exit.              │
╰─────────────────────────────────────────────────────────────────────────╯
pypae commented 2 months ago

Currently, you have to annotate the fields with typer.Option in addition to pydantic.Field to add a custom cli help text like so:

from typing import Annotated

import pydantic_typer
from pydantic import BaseModel, Field
from typer import Option

class User(BaseModel):
    id: Annotated[int, Option(help="The unique identifier for the user")] = Field(
        ..., description="The unique identifier for the user"
    )
    name: Annotated[str, Option(help="The name of the user")] = Field(
        "John Doe", description="The name of the user"
    )

def main(user: User):
    print(user, type(user))

if __name__ == "__main__":
    pydantic_typer.run(main)

It would probably make sense to copy all metadata of the Field into the typer.Option automatically. I started working on this in a PR.

pablospe commented 2 months ago

Thanks a lot for the answer! As I see in your PR, using Field with Annotated would work for me (more info about Field with Annotated here).