pydantic-argparse is a Python package that provides declarative typed argument parsing by leveraging Pydantic models. It builds on the standard `argparse` module, offering a simple, opinionated, and type-hinted API for command-line interfaces. The library supports nesting Pydantic models for sub-command functionality and utilizes Pydantic's robust validation system. The current version is 0.10.0, released in February 2025, indicating an active development and release cadence.
pip install pydantic-argparseVerified import paths — ran on the pinned version, not inferred.
Define your command-line arguments using a Pydantic `BaseModel`. Then, create an instance of `pydantic_argparse.ArgumentParser` with your model and call `parse_typed_args()` to get a validated Pydantic model instance. This example uses `pydantic.v1` as shown in the official documentation.
For new projects, decide whether to explicitly use `pydantic.v1` for full compatibility with existing `pydantic-argparse` examples, or to adapt your Pydantic models to v2 and test thoroughly. If using Pydantic v2, consult the Pydantic migration guide for changes to `BaseModel` configuration and validators. The library's main `ArgumentParser` import remains consistent.
Update code that inspects `model.__fields_set__` or uses `model.json(exclude_unset=True)` to account for the new behavior where only explicitly provided arguments are marked as 'set'.
Always define arguments using `pydantic.Field` with implicit or explicit aliases (flags) for all command-line inputs. Do not attempt to define positional arguments through the Pydantic model.
Consult Pydantic's `BaseSettings` documentation for environment variable loading order and precedence when designing your CLI with environment variable support. Clearly document the expected behavior for your users.
Ensure the library is installed using pip: `pip install pydantic-argparse`.
Supply the missing argument on the command line. For example, if 'name' is required, run `python your_script.py --name 'value'`.
Reorder the fields in your Pydantic model so that all fields without default values (required arguments) are declared before any fields with default values (optional arguments).
Provide input values that match the expected type hint for each field in your Pydantic model. For example, for an `int` field, provide a numeric string like '123' instead of non-numeric text.