Typed Argument Parsing with Pydantic
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.
Warnings
- breaking Pydantic v1 vs v2 Compatibility: While pydantic-argparse v0.9.0 introduced initial compatibility with Pydantic v2, the official quickstart examples (even for v0.10.0) continue to explicitly use `import pydantic.v1 as pydantic`. Pydantic v2 includes significant breaking changes to its API (e.g., `Config` class vs `model_config` dict, `@validator` vs `@field_validator`, behavior of `Optional` fields). Users migrating from Pydantic v1 to v2 should carefully review the Pydantic migration guide and adapt their argument models, as direct compatibility with `pydantic-argparse` may require specific Pydantic v1 imports or adjustments.
- breaking Changes to Default Value Handling (v0.6.0): Prior to v0.6.0, `pydantic-argparse` explicitly set default values for arguments not provided by the user via `argparse`. From v0.6.0 onwards, it transitioned to using `argparse.SUPPRESS` and relies on the `pydantic` model's default values for missing arguments. This change impacts how `model.__fields_set__` and `model.json(exclude_unset=True)` behave, as arguments not provided by the user will no longer appear in `__fields_set__`.
- gotcha No Positional Arguments: `pydantic-argparse` has an opinionated design that explicitly does not support positional arguments, only optional and required arguments which are defined with flags. Users accustomed to `argparse`'s positional argument behavior may find this limiting.
- gotcha Environment Variable Precedence: Version 0.8.0 introduced handling for environment variables, leveraging `pydantic.BaseSettings` for configuration. While a powerful feature, users should be aware of the precedence rules if arguments can be supplied via both command-line flags and environment variables, as the order of overriding might not always be intuitive without consulting Pydantic's settings documentation.
Install
-
pip install pydantic-argparse
Imports
- ArgumentParser
from pydantic_argparse import ArgumentParser
- BaseModel
from pydantic.v1 import BaseModel
from pydantic import BaseModel
Quickstart
import pydantic.v1 as pydantic
from pydantic import Field
from pydantic_argparse import ArgumentParser
class Arguments(pydantic.BaseModel):
"""Simple Command-Line Arguments."""
# Required Args
string: str = Field(description="a required string", aliases=["-s"])
integer: int = Field(description="a required integer", aliases=["-i"])
flag: bool = Field(description="a required flag", aliases=["-f"])
# Optional Args
second_flag: bool = Field(False, description="an optional flag")
third_flag: bool = Field(True, description="an optional flag")
def main() -> None:
"""Simple Main Function."""
parser = ArgumentParser(
model=Arguments,
prog="Example Program",
description="Example Description",
version="0.0.1",
epilog="Example Epilog",
)
args = parser.parse_typed_args()
print(args)
if __name__ == "__main__":
main()