### Example usage with EnvSettingsSource Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/sources.md Shows how to use EnvSettingsSource in an ArgParser command. The example reads from a .env file with the key ITEM__NAME=example to populate the item.name field when not provided on the CLI. ```python from argdantic import ArgParser from argdantic.sources import EnvSettingsSource from pydantic import BaseModel class Item(BaseModel): name: str = "test" price: float = 10.0 parser = ArgParser() @parser.command(sources=[EnvSettingsSource(env_file=".env", env_file_encoding="utf-8")]) def item(item: Item): print(item) ``` -------------------------------- ### Help output for descriptions example Source: https://github.com/edornd/argdantic/blob/main/docs/guide/customization.md Output of running the descriptions script with --help, showing the descriptions. ```console $ python main.py --help > usage: main.py [-h] [--name TEXT] [--age INT] > > optional arguments: > -h, --help show this help message and exit > --name TEXT, -n TEXT your name (default: John) > --age INT, -a INT your age (default: 30) ``` -------------------------------- ### Help output for aliases example Source: https://github.com/edornd/argdantic/blob/main/docs/guide/customization.md Output of running the aliases script with --help, showing the aliases -n and -a. ```console $ python main.py --help > usage: main.py [-h] --name TEXT --age INT > > optional arguments: > -h, --help show this help message and exit > --name TEXT, -n TEXT (required) > --age INT, -a INT (required) ``` -------------------------------- ### Usage example with CLIRunner Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/testing.md Shows how to create an ArgParser with a command, invoke it using CLIRunner, and inspect the Result. ```python from argdantic import ArgParser from argdantic.testing import CLIRunner parser = ArgParser() @parser.command() def add(a: int, b: int) -> int: return a + b runner = CLIRunner() result = runner.invoke(parser, ["--a", "1", "--b", "2"]) print(result.return_value) # 3 print(result.exception) # None ``` -------------------------------- ### Run aliases example with short flags Source: https://github.com/edornd/argdantic/blob/main/docs/guide/customization.md Executing the aliases script with -n and -a flags. ```console $ python main.py -n John -a 42 > Hello, John! > You are 42 years old. ``` -------------------------------- ### TomlSettingsStore class implementation Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/stores.md Defines a settings store that writes settings to a TOML file. Requires the 'toml' package (install via 'pip install argdantic[toml]'); raises ImportError with instructions if missing. Uses model_dump with configurable options and writes UTF-8 encoded text. ```python class TomlSettingsStore(BaseSettingsStore): def __call__(self, settings: BaseSettings) -> None: try: import toml except ImportError: raise ImportError( "You need to install TOML dependencies to use the TOML source. " "You can do so by running `pip install argdantic[toml]`." ) with self.path.open("wb") as f: text = toml.dumps( settings.model_dump( mode=self.mode, include=self.include, exclude=self.exclude, by_alias=self.by_alias, exclude_defaults=self.exclude_defaults, exclude_unset=self.exclude_unset, exclude_none=self.exclude_none, ) ) f.write(text.encode(self.encoding)) def __repr__(self) -> str: return f"" ``` -------------------------------- ### Hello command and renderer pair (using System Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/core.md Two separate code blocks displayed sequentially as a single source. The first configures a be simple greeting and the second calls it. Note that executes in the same example, but the only got a comment. ```python from argdantic import ArgParser parser = ArgParser(name="greet") @parser.command() def hello(name: str): return f"Hello, {name}" if __name__ == "__main__": # raise SystemExit on missing required --name print(parser(["--name", "world"])) # "Hello, world" ``` -------------------------------- ### Run nested_models.py --help to show generated CLI arguments Source: https://github.com/edornd/argdantic/blob/main/docs/guide/composition.md Shows the command-line interface generated by the nested models example, including required fields and their usage. ```console $ python nested_models.py --help > usage: nested_models.py [-h] --item.name TEXT --item.description TEXT --item.price FLOAT --item.tags TEXT [TEXT ...] --item.image.url TEXT --item.image.name TEXT > > optional arguments: > -h, --help show this help message and exit > --item.name TEXT TEXT (required) > --item.description TEXT > --item.price FLOAT (required) > --item.tags [TEXT [TEXT ...]] (default: set()) > --item.image.url TEXT (required) > --item.image.name TEXT (required) ``` -------------------------------- ### TomlSettingsStore.__call__ Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/stores.md Serializes the given settings to TOML format and writes them to the configured file path. Requires the 'toml' package; raises ImportError if not installed. ```APIDOC ## TomlSettingsStore.__call__ ### Description Serializes the given settings to TOML format and writes them to the configured file path. Requires the 'toml' package; raises ImportError if not installed. ### Method __call__ ### Signature ```python def __call__(self, settings: BaseSettings) -> None ``` ### Parameters - **settings** (BaseSettings) - Required - The settings instance to serialize and store. ### Behavior - Opens the file at `self.path` in binary write mode. - Uses `toml.dumps` on the result of `settings.model_dump()` with the store's configuration options. - Writes the encoded TOML string to the file. ### Exceptions - **ImportError** - Raised if the `toml` package is not installed. Message includes installation instructions. ### Example ```python store = TomlSettingsStore(path="settings.toml") store(settings) ``` ``` -------------------------------- ### argazing Example usage of typing containers Source: https://github.com/edornd/argdantic/blob/main/docs/guide/types.md This example of the argyed package of the source types. The script was originally in the examples/typing directory. ```python {!examples/typing/containers.py!} ``` -------------------------------- ### Create a basic parser (main.py) Source: https://github.com/edornd/argdantic/blob/main/docs/guide/intro.md Minimal parser setup that imports ArgParser, instantiates it, and calls it in the main block. Running this without any command raises an AssertionError because a parser must have at least one command or group. ```python {!examples/basic/empty.py!} ``` -------------------------------- ### YAML configuration files for dataset and optim Source: https://github.com/edornd/argdantic/blob/main/docs/guide/sources.md Defines the YAML configuration files for the dataset and optim fields, used by the dynamic.py example. ```yaml {!examples/sources/resources/dataset.yml!} ``` ```yaml {!examples/sources/resources/optim.yml!} ``` -------------------------------- ### SecretsSettingsSource usage example Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/sources.md Shows how to use SecretsSettingsSource with a command. Each file name under ./secrets maps to a model field. ```python from argdantic.sources import SecretsSettingsSource # each file name under ./secrets maps to a model field @parser.command(sources=[SecretsSettingsSource(secrets_dir="./secrets")]) def deploy(api_key: str): ... ``` -------------------------------- ### Using multiple sources for arguments Source: https://github.com/edornd/argdantic/blob/main/README.md Import and add multiple sources to a command using the `sources` parameter. This example uses environment variables and a JSON file as sources for the command arguments. ```python from argdantic import ArgParser from argdantic.sources import EnvSettingsSource, JsonSettingsSource parser = ArgParser() @parser.command( sources=[ EnvSettingsSource(env_file=".env", env_file_encoding="utf-8"), JsonSettingsSource(path="settings.json"), ] ) def sell(item: str, quantity: int, value: float): print(f"Selling: {item} x {quantity}, {value:.2f}$") if __name__ == "__main__": parser() ``` -------------------------------- ### Execute nested_models.py with required arguments to see output Source: https://github.com/edornd/argdantic/blob/main/docs/guide/composition.md Shows the command and its output when all required arguments are provided for the nested models example. ```console $ python nested_models.py --item.name "My Item" \ --item.description "My Item Description" \ --item.price 10.0 \ --item.tags "tag1" "tag2" \ --item.image.url "https://example.com/image.png" \ --item.image.name "My Image" > name='My Item' description='My Item Description' price=10.0 tags={'tag1', 'tag2'} image=Image(url='https://example.com/image.png' name='My Image') ``` -------------------------------- ### Run command with default values (python main.py) Source: https://github.com/edornd/argdantic/blob/main/docs/guide/customization.md Output of the previous default values example when executed with no arguments. It prints `Hello World!` and `You are 42 years old.`. ```console $ python main.py > Hello, World! > You are 42 years old. ``` -------------------------------- ### Help output showing default values (python main.py --help) Source: https://github.com/edornd/argdantic/blob/main/docs/guide/customization.md Console output showing the help message for the default values example. It lists the defaults in parentheses after each option. ```console $ python main.py --help > usage: main.py [-h] [--name TEXT] [--age INT] > > optional arguments: > -h, --help show this help message and exit > --name TEXT (default: World) > --age INT (default: 42) ``` -------------------------------- ### Error handling example with CLIRunner Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/testing.md Demonstrates catching exceptions raised by the command body, including the behavior when catch_exceptions is False. ```python from argdantic import ArgParser from argdantic.testing import CLIRunner parser = ArgParser() @parser.command() def risky(token: str): if not token: raise ValueError("missing token") return f"ok:{token}" runner = CLIRunner() # catch_exceptions=True ok = runner.invoke(parser, ["--token", "abc"]) print(ok.return_value) # "ok:abc" bad = runner.invoke(parser, ["--token", ""]) print(bad.exception) # ValueError("missing token") print(bad.exc_info) # (type, value, traceback) strict = CLIRunner(catch_exceptions=False) # re-raises the ValueError immediately: # strict.invoke(parser, []) ``` -------------------------------- ### Create a simple CLI with ArgParser Source: https://github.com/edornd/argdantic/blob/main/docs/index.md A minimal example of creating a CLI with argdantic. It defines a command 'buy' that takes a name, quantity, and price, and prints a formatted message. The parser is invoked when the script is run directly. ```python from argdantic import ArgParser # 1. create a CLI instance parser = ArgParser() # 2. decorate the function to be called @parser.command() def buy(name: str, quantity: int, price: float): print(f"Bought {quantity} {name} at ${price:.2f}.") # 3. Use your CLI by simply calling it if __name__ == "__main__": parser() ``` -------------------------------- ### Example: using from_file with YamlFileLoader Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/sources.md Shows how to use the from_file decorator with a YAML loader. The CLI command reads the file and overrides learning_rate from the command line. The file keys must match field names. ```python from pydantic import BaseModel from argdantic import ArgParser from argdantic.sources import YamlFileLoader, from_file @from_file(loader=YamlFileLoader) class Optimizer(BaseModel): name: str = "SGD" learning_rate: float = 0.01 momentum: float = 0.9 cli = ArgParser() @cli.command() def create_item(dataset: Dataset, optim: Optimizer): ... ``` -------------------------------- ### Basic command with ArgParser Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/core.md Basic command registration example. The `buy` function takes `name` (required) and `quantity` (default 1); the docstring becomes the help text. Run with `python script.py buy --name apple --quantity 3`. ```python from argdantic import ArgParser parser = ArgParser() @parser.command() def buy(name: str, quantity: int = 1): """Buy an item.""" print(f"Bought {quantity} x {name}") ``` -------------------------------- ### TomlFileLoader and TomlSettingsSource classes Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/sources.md Defines TomlFileLoader, which reads TOML data using tomli, and TomlSettingsSource, which builds the loader. Requires the tomli package (argdantic[toml] extra); raises ImportError with install instructions if missing. ```python class TomlFileLoader(FileBaseSettingsSource): def get_field_value(self, field: FieldInfo, field_name: str) -> Tuple[Any, str, bool]: return None, field_name, False def __call__(self) -> Dict[str, Any]: try: import tomli except ImportError: raise ImportError( "You need to install TOML libraries to use the TOML source. " "You can do so by running `pip install argdantic[toml]`." ) with open(self.path, mode="rb") as f: return tomli.load(f) class TomlSettingsSource(FileSettingsSourceBuilder): def __call__(self, settings: Type[BaseSettings]) -> PydanticBaseSettingsSource: return TomlFileLoader(settings, self.path) def __repr__(self) -> str: return f"" ``` -------------------------------- ### Define command with multiple sources Source: https://github.com/edornd/argdantic/blob/main/docs/guide/sources.md Example from sources.py defining a single command with multiple sources, including file sources. Comment out JSON and TOML sources to run successfully. The YAML file supplies values for the arguments. ```python {!examples/sources/single_cmd.py!} ``` -------------------------------- ### Help output for primitives.py Source: https://github.com/edornd/argdantic/blob/main/docs/guide/types.md Console output showing the generated help message for the primitives.py example. It displays the CLI flags for each primitive type, including the mutually exclusive --flag/--no-flag options for booleans. ```console $ python primitives.py --help > usage: primitives.py [-h] --name TEXT --age INT --weight FLOAT --data BYTES (--flag | --no-flag) > > optional arguments: > -h, --help show this help message and exit > --name TEXT (required) > --age INT (required) > --weight FLOAT (required) > --data BYTES (required) > --flag > --no-flag ``` -------------------------------- ### Usage example with ActionTracker Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/actions.md Shows how to instantiate an action indirectly through ActionTracker and use it with argparse. The comment illustrates that --tag a b --tag c results in namespace.tag == ["a", "b", "c"], and tracker.is_set() returns True once --tag is provided. ```python from argdantic.parsing import ActionTracker from argdantic.parsing.actions import AppendAction tracker = ActionTracker(AppendAction) parser.add_argument("--tag", dest="tag", action=tracker, nargs="*", type=str) # --tag a b --tag c → namespace.tag == ["a", "b", "c"] print(tracker.is_set()) # True once --tag was provided at least once ``` -------------------------------- ### Install argdantic with pip Source: https://github.com/edornd/argdantic/blob/main/docs/index.md Installation commands for argdantic. The recommended choice installs all optional dependencies (orjson, pyyaml, tomli, python-dotenv). Alternatively, install only specific dependencies using the env, json, toml, or yaml extras, or install the minimum requirement with only pydantic. ```console user@pc:~$ pip install argdantic[all] ``` ```console user@pc:~$ pip install argdantic[env|json|toml|yaml] ``` ```console user@pc:~$ pip install argdantic ``` -------------------------------- ### Show help for the buy command Source: https://github.com/edornd/argdantic/blob/main/docs/index.md Running the CLI with the --help flag displays usage information and the required arguments: --name, --quantity, and --price. ```console $ python cli.py --help > usage: buy [-h] --name TEXT --quantity INT --price FLOAT > > optional arguments: > -h, --help show this help message and exit > --name TEXT > --quantity INT > --price FLOAT ``` -------------------------------- ### Primitive types example (primitives.py) Source: https://github.com/edornd/argdantic/blob/main/docs/guide/types.md Example script demonstrating primitive field types in argdantic. The source uses an include marker, so the actual code is not visible on this page. ```python {!examples/typing/primitive.py!} ``` -------------------------------- ### Show CLI help for singleton configuration (python singleton.py --help) Source: https://github.com/edornd/argdantic/blob/main/docs/guide/composition.md Output of running the singleton configuration script with --help, showing that the top-level name is absent from the fields. ```console $ python singleton.py --help > usage: test.py [-h] --name TEXT --description TEXT --image.name TEXT > > optional arguments: > -h, --help show this help message and exit > --name TEXT (required) > --description TEXT (required) > --image.name TEXT (required) ``` -------------------------------- ### Using ArgField in function signature Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/fields.md Example from the customization examples, showing how to use ArgField to define CLI options with aliases and defaults in a command function. This creates options -n and -a with default values. ```python from argdantic import ArgField, ArgParser parser = ArgParser() @parser.command() def hello( name: str = ArgField("-n", default="John", description="your name"), age: int = ArgField("-a", default=30, description="your age"), ): print(f"Hello, {name}! You are {age}.") if __name__ == "__main__": parser() ``` -------------------------------- ### YamlSettingsStore class implementation Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/stores.md Defines a settings store that writes settings to a YAML file. Requires 'pyyaml' (install via 'pip install argdantic[yaml]'); raises ImportError with instructions if missing. Uses yaml.safe_dump with allow_unicode=True and writes with UTF-8 encoding. ```python class YamlSettingsStore(BaseSettingsStore): def __call__(self, settings: BaseSettings) -> None: try: import yaml except ImportError: raise ImportError( "You need to install YAML dependencies to use the YAML store. " "You can do so by running `pip install argdantic[yaml]`." ) with self.path.open("w") as f: data = settings.model_dump( mode=self.mode, include=self.include, exclude=self.exclude, by_alias=self.by_alias, exclude_defaults=self.exclude_defaults, exclude_unset=self.exclude_unset, exclude_none=self.exclude_none, ) yaml.safe_dump(data, f, encoding="utf-8", allow_unicode=True) def __repr__(self) -> str: return f"" ``` -------------------------------- ### Run dynamic.py with configuration files Source: https://github.com/edornd/argdantic/blob/main/docs/guide/sources.md Shows the command to run dynamic.py with the dataset and optim configuration files, and the resulting output. ```console $ python dynamic.py --dataset resources/dataset.yml --optim resources/optim.yml name='coco' batch_size=32 tile_size=512 shuffle=True name='adam' learning_rate=0.001 momentum=0.9 ``` -------------------------------- ### Run the buy command with arguments Source: https://github.com/edornd/argdantic/blob/main/docs/index.md Executing the CLI with the required arguments produces the output 'Bought 10 apples at $3.40.' ```console $ python cli.py --name apples --quantity 10 --price 3.4 > Bought 10 apples at $3.40. ``` -------------------------------- ### JsonSettingsStore.__init__ Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/stores.md Initializes a JsonSettingsStore instance with the given path and serialization options. ```APIDOC ## JsonSettingsStore.__init__ ### Description Initializes a JsonSettingsStore instance with the given path and serialization options. ### Method Constructor ### Signature ```python def __init__( self, path: Union[str, Path], *, encoding: str = "utf-8", include: Optional[Set[str]] = None, exclude: Optional[Set[str]] = None, by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, ) -> None ``` ### Parameters - **path** (Union[str, Path]) - Required - The file path where settings will be written. - **encoding** (str) - Optional - The encoding to use when writing the file. Defaults to "utf-8". - **include** (Optional[Set[str]]) - Optional - Set of field names to include in the serialized output. - **exclude** (Optional[Set[str]]) - Optional - Set of field names to exclude from the serialized output. - **by_alias** (bool) - Optional - Whether to use field aliases in the serialized output. Defaults to False. - **exclude_unset** (bool) - Optional - Whether to exclude fields that were not explicitly set. Defaults to False. - **exclude_defaults** (bool) - Optional - Whether to exclude fields that have default values. Defaults to False. - **exclude_none** (bool) - Optional - Whether to exclude fields that are None. Defaults to False. ### Returns None ``` -------------------------------- ### Command.__init__ Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/core.md Initializes a Command instance with a callback, arguments, model class, name, and optional settings. ```APIDOC ## Command.__init__ ### Description Initializes a Command instance that wraps a callback function, its arguments, and the generated pydantic model. ### Method Constructor ### Parameters - **callback** (Callable) - Required - Function invoked on dispatch; `assert callback is not None`. - **arguments** (Iterable[Argument]) - Required - Arguments registered on the argparse parser. - **model_class** (Type[BaseModel]) - Required - Validation model built from the callback signature. - **name** (str) - Required - Command name used in the group. - **description** (Optional[str]) - Optional - Help text. Default: `None`. - **singleton** (bool) - Optional - Pass model whole vs. destructured to callback. Default: `False`. - **stores** (Optional[List[SettingsStoreCallable]]) - Optional - Post-validation store callables. Default: `None`. - **delimiter** (str) - Optional - The parser's `internal_delimiter`, used to re-nest CLI values. Default: `"__"`. ### Returns None ``` -------------------------------- ### Model-based validation and pydantic with error Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/core.md Another example shows a BaseModel with a pydantic error; the tutorial shows that the CLI delegates. ```python from argdantic import ArgParser from pydantic import BaseModel from argdantic.testing import CLIRunner parser = ArgParser() class Item(BaseModel): price: float = 0.0 @parser.command() def set_price(item: Item): print(item) if __name__ == "__main__": # `--item.price apples` → "1 validation error while parsing arguments ... item -> price: Input should be a valid number" try: parser(["--item.price", "apples"]) except SystemExit: print("exit: 2") ``` -------------------------------- ### CLI help output for dynamic.py Source: https://github.com/edornd/argdantic/blob/main/docs/guide/sources.md Shows the help output for the dynamic.py script, including the automatically added --dataset and --optim arguments. ```diff $ python dynamic.py --help usage: models.py [-h] [--dataset.name TEXT] [--dataset.batch-size INT] [--dataset.tile-size INT] [--dataset.shuffle | --no-dataset.shuffle] --dataset PATH [--optim.name TEXT] [--optim.learning-rate FLOAT] [--optim.momentum FLOAT] --optim PATH options: -h, --help show this help message and exit --dataset.name TEXT (default: CIFAR10) --dataset.batch-size INT (default: 32) --dataset.tile-size INT (default: 256) --dataset.shuffle (default: True) --no-dataset.shuffle + --dataset PATH (required) --optim.name TEXT (default: SGD) --optim.learning-rate FLOAT (default: 0.01) --optim.momentum FLOAT (default: 0.9) + --optim PATH (required) ``` -------------------------------- ### YamlSettingsStore.__call__ Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/stores.md Serializes the given settings to YAML format and writes them to the configured file path. Requires the 'pyyaml' package; raises ImportError if not installed. ```APIDOC ## YamlSettingsStore.__call__ ### Description Serializes the given settings to YAML format and writes them to the configured file path. Requires the 'pyyaml' package; raises ImportError if not installed. ### Method __call__ ### Signature ```python def __call__(self, settings: BaseSettings) -> None ``` ### Parameters - **settings** (BaseSettings) - Required - The settings instance to serialize and store. ### Behavior - Opens the file at `self.path` in text write mode. - Uses `yaml.safe_dump` on the result of `settings.model_dump()` with the store's configuration options. - Writes the YAML output to the file with `allow_unicode=True`. ### Exceptions - **ImportError** - Raised if the `yaml` package is not installed. Message includes installation instructions. ### Example ```python store = YamlSettingsStore(path="settings.yaml") store(settings) ``` ``` -------------------------------- ### Use from_file annotation to load configuration from files Source: https://github.com/edornd/argdantic/blob/main/docs/guide/sources.md Shows how to use the from_file annotation to load configuration for dataset and optim fields from files. The CLI automatically adds --dataset and --optim arguments. ```python {!examples/sources/dynamic.py!} ``` -------------------------------- ### Run sources.py and get YAML-sourced output Source: https://github.com/edornd/argdantic/blob/main/docs/guide/sources.md Command output showing the command running successfully with the file-based source. The arguments are taken from the YAML file. ```bash $ python sources.py > name='example' description='Example item' price=2.3 tags={'example', 'item', 'tag'} image=Image(url='https://example.com/image.jpg', name='example.jpg') ``` -------------------------------- ### Using JsonSettingsStore and YamlSettingsStore with ArgParser Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/stores.md Shows how to attach JsonSettingsStore and YamlSettingsStore to a command so that validated values are written to out.json and out.yaml after parsing. Missing optional dependencies raise ImportError; writes occur after validation regardless of the callback's return value. ```python from argdantic import ArgParser from argdantic.stores import JsonSettingsStore, YamlSettingsStore parser = ArgParser() @parser.command(stores=[JsonSettingsStore("out.json"), YamlSettingsStore("out.yaml")]) def train(epochs: int = 10, lr: float = 0.01): return epochs, lr if __name__ == "__main__": # after validation, out.json/out.yaml are written with the validated values parser(["--epochs", "20"]) ``` -------------------------------- ### Define a Pydantic model for dynamic sources Source: https://github.com/edornd/argdantic/blob/main/docs/guide/sources.md Defines a Fruit model with name, color, and price fields. This model is used as an example for loading configuration from a file. ```python from pydantic import BaseModel class Fruit(BaseModel): name: str color: str price: float ``` -------------------------------- ### Define command with None defaults (default_values_none.py) Source: https://github.com/edornd/argdantic/blob/main/docs/guide/customization.md This example that sets default values to `None` results in a truly optional field with no `required` or `default` flag in the help message. ```python {!examples/customization/default_values_none.py!} ``` -------------------------------- ### Define command with docstring description (main.py) Source: https://github.com/edornd/argdantic/blob/main/docs/guide/customization.md Provides a default command description automatically from the function's docstring. This is the first variant used in the description customization example. ```python {!examples/customization/description.py!} ``` -------------------------------- ### Run dynamic_custom.py with use_field Source: https://github.com/edornd/argdantic/blob/main/docs/guide/sources.md Shows the command to run dynamic_custom.py with the optim path provided via a standard field, and the resulting output. ```diff +$ python dynamic_custom.py --optim.path resources/optim.yml name='CIFAR10' batch_size=32 tile_size=256 shuffle=True path=PosixPath('resources/optim.yml') name='adam' learning_rate=0.001 momentum=0.9 ``` -------------------------------- ### Type aliases for pydantic settings sources and generic ArgParser Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/core.md The type imports and two public type aliases from the start of the module. They come directly from the source; the distinct. ```python # argdantic/core.py:15 SettingSourceCallable = Callable[[Type[BaseSettings]], PydanticBaseSettingsSource] # argdantic/core.py:16 ParserType = TypeVar("ParserType", bound="ArgParser") ``` -------------------------------- ### JsonFileLoader and JsonSettingsSource class definitions Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/sources.md Defines a settings source that reads a JSON file. Uses orjson when installed (the argdantic[json] extra), otherwise the standard library json. ```python class JsonFileLoader(FileBaseSettingsSource): def get_field_value(self, field: FieldInfo, field_name: str) -> Tuple[Any, str, bool]: return None, field_name, False def __call__(self) -> Dict[str, Any]: try: import orjson as json return json.loads(self.path.read_bytes()) except ImportError: import json return json.load(self.path.open()) class JsonSettingsSource(FileSettingsSourceBuilder): def __call__(self, settings: Type[BaseSettings]) -> PydanticBaseSettingsSource: return JsonFileLoader(settings, self.path) def __repr__(self) -> str: return f"" ``` -------------------------------- ### Catch ImportError for missing YAML dependencies Source: https://github.com/edornd/argdantic/blob/main/_autodocs/errors.md Wrap parser invocation in a try/except to catch ImportError when optional YAML dependencies are missing. The exception message contains installation instructions. ```python from argdantic.sources import YamlSettingsSource try: parser.command(sources=[YamlSettingsSource("settings.yaml")])(my_func) parser([...]) except ImportError as e: print(e) # install instructions ``` -------------------------------- ### Nested parsers with add_parser Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/core.md Example from `examples/composition/nested_parsers.py` showing how to compose nested parsers. Two sub-parsers (`users` and `books`) are created and added to a root `cli` parser via `add_parser`. ```python from argdantic import ArgParser users = ArgParser(name="users") books = ArgParser(name="books") @users.command() def add_user(name: str, age: int): print(f"Adding user: {name} ({age})") @books.command() def add_book(name: str, author: str): print(f"Adding book: {name} ({author})") cli = ArgParser() cli.add_parser(users) cli.add_parser(books) ``` -------------------------------- ### Simple CLI with ArgParser Source: https://github.com/edornd/argdantic/blob/main/README.md Create a basic CLI with argdantic by decorating a function with @parser.command(). The function parameters become required command-line arguments. Running the script with --help shows usage information. ```python from argdantic import ArgParser from pydantic import BaseModel parser = ArgParser() @parser.command() def buy(name: str, quantity: int, price: float): print(f"Bought {quantity} {name} at ${price:.2f}.") if __name__ == "__main__": parser() ``` -------------------------------- ### Show help for add-user subcommand Source: https://github.com/edornd/argdantic/blob/main/docs/guide/composition.md Output of running 'python nested_parsers.py users add-user --help'. Shows the required arguments --name and --age for the add-user subcommand. ```console $ python nested_parsers.py users add-user --help > usage: nested_parsers.py users add-user [-h] --name TEXT --age INT > > optional arguments: > -h, --help show this help message and exit > --name TEXT (required) > --age INT (required) ```