Registry / serialization / pydantic-argparse

pydantic-argparse

JSON →
library0.10.0pypypi✓ verified 89d ago

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-argparse
INSTALL
IMPORT
SIG · PYDANTIC-ARGPARSE
P
pydantic-argparse
serializationpythonv0.10.0
Install
3.3s avg
Import
491ms
Disk
26MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v0.10.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.10–3.920 runs
installs and imports cleanly · install 0.0s · import 0.504s · 28.1MB
glibc
py 3.10–3.920 runs
installs and imports cleanly · install 3.3s · import 0.478s · 28MB
26MB installed
● package 26MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

ArgumentParser
✓ from pydantic_argparse import ArgumentParser
BaseModel
✓ from pydantic import BaseModel
✗ from pydantic.v1 import BaseModel
While pydantic-argparse added initial Pydantic v2 compatibility in v0.9.0, its official quickstart examples still explicitly import `pydantic.v1` for model definition. This suggests that using Pydantic v1 might be more stable or intended with current examples, or that full v2 migration requires careful adaptation of Pydantic models.

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.

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()
Debug
Known issues
breakingPydantic 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.
fix
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.
affects: >=0.9.0
breakingChanges 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__`.
fix
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'.
affects: <0.6.0
gotchaNo 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.
fix
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.
affects: All versions
gotchaEnvironment 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.
fix
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.
affects: >=0.8.0
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'pydantic_argparse'
The `pydantic-argparse` library has not been installed, or the Python environment where it's installed is not the one being used to run the code.
fix
Ensure the library is installed using pip: `pip install pydantic-argparse`.
error: the following arguments are required: ARG_NAME
A required command-line argument, as defined in the Pydantic model used by `pydantic-argparse`, was not provided when the script was executed.
fix
Supply the missing argument on the command line. For example, if 'name' is required, run `python your_script.py --name 'value'`.
TypeError: Field 'field_name' has a non-default argument following a default argument
This Pydantic-related error occurs when defining a Pydantic `BaseModel` (used by `pydantic-argparse`) where a field with a default value is declared before a field that has no default value (i.e., a required field).
fix
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).
pydantic_core._pydantic_core.ValidationError: 1 validation error for Arguments field_name Input should be a valid integer [type=int_parsing, ...]
The value provided for a command-line argument could not be coerced into the expected Pydantic type (e.g., a string 'abc' was provided for an `int` field), failing Pydantic's validation.
fix
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.
Upgrade
Version history
0.10.0latest on PyPI · released Feb 9, 2025
Audit
Dependencies
pydanticrequiredCore dependency for defining argument models and validation.
Agent activity
5 hits · last 30 days
node
4
Resources