Skip to content

[FEATURE] Support Pydantic Models as ParamTypes #111

Description

@sm-hawkfish

Is your feature request related to a problem

I would like to use Pydantic Models as type annotations in my Typer CLI program.

The solution you would like

Typer would call Model.parse_raw on the string that was passed to the CLI

Describe alternatives you've considered

Rather than having Typer be so aware of the Pydantic API, I tried to create a custom click.ParamType that did the parsing, but even that did not work as custom types do not currently seem to be supported in the get_click_type function.

Additional context

Here's a simple example:

#!/usr/bin/env python3
import click
import typer
from pydantic import BaseModel


class User(BaseModel):
    id: int
    name = "Jane Doe"


class UserParamType(click.ParamType):
    def convert(self, value, param, ctx):
        return User.parse_raw(value)


USER = UserParamType()


def main(num: int, user: USER):
    print(num, type(num))
    print(user, type(user))


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

This currently throws:

Traceback (most recent call last):
  File "./typer_exp.py", line 26, in <module>
    typer.run(main)
  File "/usr/local/lib/python3.7/site-packages/typer/main.py", line 848, in run
    app()
  File "/usr/local/lib/python3.7/site-packages/typer/main.py", line 213, in __call__
    return get_command(self)()
  File "/usr/local/lib/python3.7/site-packages/typer/main.py", line 238, in get_command
    click_command = get_command_from_info(typer_instance.registered_commands[0])
  File "/usr/local/lib/python3.7/site-packages/typer/main.py", line 422, in get_command_from_info
    ) = get_params_convertors_ctx_param_name_from_function(command_info.callback)
  File "/usr/local/lib/python3.7/site-packages/typer/main.py", line 403, in get_params_convertors_ctx_param_name_from_function
    click_param, convertor = get_click_param(param)
  File "/usr/local/lib/python3.7/site-packages/typer/main.py", line 656, in get_click_param
    annotation=main_type, parameter_info=parameter_info
  File "/usr/local/lib/python3.7/site-packages/typer/main.py", line 586, in get_click_type
    raise RuntimeError(f"Type not yet supported: {annotation}")  # pragma no cover
RuntimeError: Type not yet supported: <__main__.UserParamType object at 0x7fc346234b10>

A major bonus would be if I could write the user: User type annotation directly, without creating the UserParamType.

Also - just want to say thank you for writing such an awesome python package and keep up the great work! 👏

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions