argdantic: Typed CLI Interfaces with Pydantic
Argdantic is a Python library that allows you to define command-line interfaces (CLIs) using Pydantic models for argument definition and type validation, combined with `argparse` for parsing. It aims to provide a modern, type-hinted approach to CLI development, leveraging Pydantic's strong data validation and `argparse`'s robust parsing capabilities. The current version is 1.3.3 and it actively maintained.
Common errors
-
TypeError: 'NoneType' object is not callable
cause The `Argdantic` app instance was created, but its `app()` or `app.run()` method was not called to actually parse command-line arguments and execute the command.fixAdd `app()` (or `app.run()`) to the main execution block of your script, typically within `if __name__ == '__main__':`. -
TypeError: missing a required argument: '...' (e.g., 'name')
cause A non-optional argument was defined in a command function (or Pydantic model) but not provided by the user via the command line, and no default value was specified.fixEither provide a default value for the argument in the command definition (e.g., `name: str = 'Default'`) or ensure the user provides the argument via the CLI (e.g., `--name MyName`). -
Error: unrecognized arguments: --some-unknown-flag
cause The user provided a command-line flag or argument that does not correspond to any defined parameter in the command function's signature or Pydantic model.fixCheck the command-line syntax and ensure all provided arguments match the defined parameters. If the argument is intended, add it to the command function's signature with a type hint.
Warnings
- breaking Major API overhaul in version 1.0.0 changed the way commands are defined and executed.
- gotcha Forgetting to call `app()` or `app.run()` at the end of your script will result in the CLI application not parsing arguments or executing commands.
- gotcha Default values for arguments without `Field` metadata will be inferred from the type annotation, but `help` messages and custom descriptions will be missing.
Install
-
pip install argdantic
Imports
- Argdantic
from argdantic.parse import parse
from argdantic import Arqdantic
- Field
from pydantic import Field
Quickstart
from argdantic import Arqdantic
from pydantic import Field
import sys
# Instantiate the Arqdantic application
app = Arqdantic()
# Define a command using a decorator
@app.command()
def greet(
name: str = Field('World', help='The name to greet.'),
count: int = Field(1, help='Number of times to greet.')
):
"""Greets the given name multiple times."""
for _ in range(count):
print(f"Hello, {name}!")
if __name__ == "__main__":
# Example of how to run from the CLI:
# python your_script.py greet --name Alice --count 3
# For testing within the script, you can temporarily modify sys.argv:
# sys.argv = ['your_script.py', 'greet', '--name', 'Alice', '--count', '3']
app() # This parses sys.argv and executes the command