### Basic ArgField with Description Source: https://github.com/edornd/argdantic/blob/main/_autodocs/configuration.md Example of defining configuration fields with descriptions for command-line help. ```python from argdantic import ArgField from pydantic import BaseModel class Config(BaseModel): name: str = ArgField(description="Application name") version: str = ArgField( default="1.0.0", description="Version number" ) ``` -------------------------------- ### Example Usage of TomlSettingsStore Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/settings-stores.md Demonstrates how to use TomlSettingsStore with Pydantic models and ArgParser to save configuration to a TOML file. The example excludes default values from being saved. ```python from pydantic import BaseModel from argdantic import ArgParser from argdantic.stores import TomlSettingsStore class AppConfig(BaseModel): name: str version: str port: int = 8080 parser = ArgParser() @parser.command( stores=[ TomlSettingsStore( path="app_config.toml", exclude_defaults=True # Don't save port (has default) ) ] ) def create(config: AppConfig): print(f"App {config.name} v{config.version} configured") if __name__ == "__main__": parser() ``` -------------------------------- ### Usage Example for Dynamic File Source Source: https://github.com/edornd/argdantic/blob/main/_autodocs/common-patterns.md Shows how to specify a configuration file path on the command line to dynamically load settings. ```bash python cli.py --settings.config-file config.json ``` -------------------------------- ### Example config.json for JsonSettingsSource Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/settings-sources.md This JSON file provides configuration values for the 'init' command when using JsonSettingsSource. ```json { "name": "MyApp", "debug": true } ``` -------------------------------- ### Multiple Commands Example Source: https://github.com/edornd/argdantic/blob/main/_autodocs/INDEX.md Shows how to define and use multiple distinct commands within a single Argdantic application. ```python from argdantic import Argdantic app = Argdantic() @app.command() def greet(name: str): print(f'Hello {name}') @app.command() def farewell(name: str): print(f'Goodbye {name}') ``` -------------------------------- ### Example pyproject.toml for TomlSettingsSource Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/settings-sources.md This TOML file provides configuration values for the 'config' command when using TomlSettingsSource. ```toml [project] version = "0.1.0" author = "John Doe" ``` -------------------------------- ### Example: Testing a Simple Command Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/testing.md Demonstrates how to use CLIRunner to test a simple command-line interface. ```APIDOC ## Example: Testing a Simple Command ### Description This example shows how to test a basic command-line function using `CLIRunner`. ### Code ```python from argdantic import ArgParser from argdantic.testing import CLIRunner parser = ArgParser() @parser.command() def add(a: int, b: int): return a + b def test_add(): runner = CLIRunner() result = runner.invoke(parser, ["--a", "10", "--b", "20"]) assert result.exception is None assert result.return_value == 30 if __name__ == "__main__": test_add() print("Test passed!") ``` ``` -------------------------------- ### Install Argdantic with Pip Source: https://github.com/edornd/argdantic/blob/main/README.md Install argdantic using pip. The recommended choice installs all optional dependencies. Alternatively, install with specific dependencies or only the minimum requirement. ```console user@pc:~$ pip install argdantic[all] user@pc:~$ pip install argdantic[env|json|toml|yaml] user@pc:~$ pip install argdantic ``` -------------------------------- ### TomlSettingsStore Example Usage Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/settings-stores.md Demonstrates how to use TomlSettingsStore with Pydantic models and ArgParser to load and save application configurations. ```APIDOC ## TomlSettingsStore Example Usage ### Description Demonstrates how to use TomlSettingsStore with Pydantic models and ArgParser to load and save application configurations. ### Code Example ```python from pydantic import BaseModel from argdantic import ArgParser from argdantic.stores import TomlSettingsStore class AppConfig(BaseModel): name: str version: str port: int = 8080 parser = ArgParser() @parser.command( stores=[ TomlSettingsStore( path="app_config.toml", exclude_defaults=True # Don't save port (has default) ) ] ) def create(config: AppConfig): print(f"App {config.name} v{config.version} configured") if __name__ == "__main__": parser() ``` ### Generated TOML File Example ```toml name = "MyApp" version = "1.0.0" ``` ``` -------------------------------- ### Install Argdantic with all dependencies Source: https://github.com/edornd/argdantic/blob/main/docs/index.md Install Argdantic with recommended dependencies including orjson, pyyaml, tomli, and python-dotenv. ```console pip install argdantic[all] ``` -------------------------------- ### Singleton Mode Example Source: https://github.com/edornd/argdantic/blob/main/_autodocs/INDEX.md Illustrates how to configure Argdantic to run a single command, useful for simple scripts. ```python from argdantic import Argdantic app = Argdantic(singleton=True) @app.command() def main(message: str): print(message) ``` -------------------------------- ### Install minimum Argdantic Source: https://github.com/edornd/argdantic/blob/main/docs/index.md Install Argdantic with only the pydantic dependency. ```console pip install argdantic ``` -------------------------------- ### Optional Fields Example Source: https://github.com/edornd/argdantic/blob/main/_autodocs/INDEX.md Shows how to define arguments that are not required. ```python from argdantic import Argdantic app = Argdantic() @app.command() def main(name: str, greeting: str | None = None): if greeting: print(f'{greeting}, {name}!') else: print(f'Hello, {name}!') ``` -------------------------------- ### Example JSON Configuration File Source: https://github.com/edornd/argdantic/blob/main/_autodocs/common-patterns.md A sample JSON file used for loading application configuration. This file provides base settings that can be overridden by environment variables. ```json { "app_name": "MyApp", "debug": false, "log_level": "info" } ``` -------------------------------- ### Nested Command Hierarchy Example Source: https://github.com/edornd/argdantic/blob/main/_autodocs/INDEX.md Demonstrates creating a hierarchical command structure, similar to git subcommands. ```python from argdantic import Argdantic app = Argdantic() @app.group() def config(): "Manage configuration" @config.command() def set(key: str, value: str): print(f'Setting {key} to {value}') @config.group() def get(): "Get configuration values" @get.command() def user(): print('Getting user config') ``` -------------------------------- ### Install Argdantic with specific dependencies Source: https://github.com/edornd/argdantic/blob/main/docs/index.md Install Argdantic with specific dependencies for environment variables, JSON, TOML, or YAML. ```console pip install argdantic[env|json|toml|yaml] ``` -------------------------------- ### Boolean Flags Example Source: https://github.com/edornd/argdantic/blob/main/_autodocs/INDEX.md Demonstrates the use of boolean flags for simple on/off options. ```python from argdantic import Argdantic app = Argdantic() @app.command() def main(verbose: bool = False): if verbose: print('Verbose mode enabled') else: print('Verbose mode disabled') ``` -------------------------------- ### Optimizer Configuration YAML Source: https://github.com/edornd/argdantic/blob/main/docs/guide/sources.md Example YAML file defining the configuration for the `Optim` model. ```yaml name: adam learning_rate: 0.001 ``` -------------------------------- ### Install Argdantic with Pip Source: https://github.com/edornd/argdantic/blob/main/_autodocs/README.md Install argdantic using pip. Choose the minimal install or include optional dependencies for extended functionality like JSON, YAML, TOML, or .env file support. ```bash # Minimal install (only pydantic required) pip install argdantic ``` ```bash # With all optional dependencies pip install argdantic[all] ``` ```bash # Specific extras pip install argdantic[json] # JSON support (orjson) pip install argdantic[yaml] # YAML support (pyyaml) pip install argdantic[toml] # TOML support (tomli/toml) pip install argdantic[env] # .env file support (python-dotenv) ``` -------------------------------- ### Basic Field with Description Example Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/ArgField.md An example demonstrating how to use ArgField to define fields with descriptions and default values for a Pydantic model. ```APIDOC ## Example: Basic Field with Description ```python from pydantic import BaseModel from argdantic import ArgField, ArgParser class Config(BaseModel): name: str = ArgField( description="Name of the application" ) version: str = ArgField( default="1.0.0", description="Application version" ) parser = ArgParser() @parser.command() def init(config: Config): print(f"{config.name} v{config.version}") if __name__ == "__main__": parser() ``` ``` -------------------------------- ### Dataset Configuration YAML Source: https://github.com/edornd/argdantic/blob/main/docs/guide/sources.md Example YAML file defining the configuration for the `Dataset` model. ```yaml name: coco tile_size: 512 ``` -------------------------------- ### Example: Testing Command with Model Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/testing.md Illustrates testing a command that accepts a Pydantic model as an argument. ```APIDOC ## Example: Testing Command with Model ### Description This example demonstrates testing a command that takes a Pydantic model as input, using `CLIRunner`. ### Code ```python from pydantic import BaseModel from argdantic import ArgParser from argdantic.testing import CLIRunner class User(BaseModel): name: str email: str parser = ArgParser() @parser.command() def create_user(user: User): return f"Created user: {user.name} ({user.email})" def test_create_user(): runner = CLIRunner() result = runner.invoke( parser, ["--user.name", "Alice", "--user.email", "alice@example.com"] ) assert result.exception is None assert "Alice" in result.return_value if __name__ == "__main__": test_create_user() print("Test passed!") ``` ``` -------------------------------- ### Example Environment Variables File Source: https://github.com/edornd/argdantic/blob/main/_autodocs/common-patterns.md A sample .env file used for overriding application configuration settings. Values in this file take precedence over those in the JSON configuration. ```env DEBUG=true LOG_LEVEL=debug ``` -------------------------------- ### Usage Examples for Custom Argument Names Source: https://github.com/edornd/argdantic/blob/main/_autodocs/common-patterns.md Demonstrates various ways to invoke the CLI with custom argument names defined via ArgField. ```bash python cli.py -f data.txt -o results/ python cli.py --file data.txt --output-dir results/ python cli.py --input data.txt --output-dir results/ ``` -------------------------------- ### Field with Alternative Names Example Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/ArgField.md This example shows how to define a field with multiple alternative CLI argument names using ArgField. ```APIDOC ## Example: Field with Alternative Names ```python from pydantic import BaseModel from argdantic import ArgField, ArgParser class Input(BaseModel): file_path: str = ArgField( "-f", "--file", "--input", description="Path to input file" ) verbose: bool = ArgField( "-v", "--verbose", default=False, description="Enable verbose output" ) parser = ArgParser() @parser.command() def process(input_: Input): mode = "verbose" if input_.verbose else "quiet" print(f"Processing {input_.file_path} ({mode})") if __name__ == "__main__": parser() ``` Usage examples: - `python cli.py --file mydata.txt` - `python cli.py -f mydata.txt` - `python cli.py --input mydata.txt` ``` -------------------------------- ### Example of Nested Parser Configuration Source: https://github.com/edornd/argdantic/blob/main/_autodocs/configuration.md Demonstrates setting up a root parser with a nested subparser for database commands. This structure organizes related functionalities under a common prefix. ```python root = ArgParser(name="app") db = ArgParser(name="db", description="Database commands") @db.command() def migrate(): print("Running migrations") root.add_parser(db) # Usage: python cli.py db migrate ``` -------------------------------- ### Argdantic Container Type Examples Source: https://github.com/edornd/argdantic/blob/main/docs/guide/types.md This script demonstrates the usage of various container types supported by Argdantic for command-line argument parsing. It includes examples for lists, tuples, dictionaries, sets, deques, and optional types. ```python from typing import Deque, FrozenSet, List, Set, Tuple, Dict, Optional, Sequence from argdantic import Argdantic class Containers(Argdantic): simple_list: List[str] list_of_ints: List[int] simple_tuple: Tuple[str, ...] multi_typed_tuple: Tuple[int, float, str, bool] simple_dict: Dict[str, str] dict_str_float: Dict[str, float] simple_set: Set[str] set_bytes: Set[bytes] frozen_set: FrozenSet[int] none_or_str: Optional[str] sequence_of_ints: Sequence[int] compound: Dict[str, Dict[str, int]] deque: Deque[int] if __name__ == "__main__": containers = Containers() print(containers.dict()) ``` -------------------------------- ### Basic Argdantic CLI Example Source: https://github.com/edornd/argdantic/blob/main/README.md Create a simple CLI application using ArgParser and a decorated function. The CLI can be invoked from the command line with arguments. ```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() ``` -------------------------------- ### Multiple Values (Lists) Example Source: https://github.com/edornd/argdantic/blob/main/_autodocs/INDEX.md Demonstrates accepting multiple values for an argument, collected into a list. ```python from argdantic import Argdantic app = Argdantic() @app.command() def process_items(items: list[str]): print('Processing items:') for item in items: print(f'- {item}') ``` -------------------------------- ### Nested Models Example Source: https://github.com/edornd/argdantic/blob/main/_autodocs/INDEX.md Illustrates how to use nested Pydantic models for complex command structures. ```python from argdantic import Argdantic from pydantic import BaseModel class User(BaseModel): name: str age: int class Settings(BaseModel): user: User app = Argdantic() @app.command() def main(settings: Settings): print(f'User: {settings.user.name}, Age: {settings.user.age}') ``` -------------------------------- ### Boolean Flags Usage Examples Source: https://github.com/edornd/argdantic/blob/main/_autodocs/common-patterns.md Illustrates how to use the defined boolean flags from the command line, showing default behavior and explicit setting of flags. ```bash python cli.py # defaults python cli.py --opts.verbose # verbose=True python cli.py --opts.no-verbose # verbose=False (explicit) python cli.py --opts.verbose --opts.debug # both True python cli.py --opts.verbose --opts.no-debug # verbose=True, debug=False ``` -------------------------------- ### Example Usage of YamlSettingsStore Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/settings-stores.md Demonstrates how to use YamlSettingsStore with a Pydantic model and ArgParser. Settings are saved to 'db_config.yaml', excluding fields with None values. ```python from pydantic import BaseModel from argdantic import ArgParser from argdantic.stores import YamlSettingsStore class Database(BaseModel): host: str port: int username: str password: str = None parser = ArgParser() @parser.command( stores=[ YamlSettingsStore( path="db_config.yaml", exclude_none=True # Don't save password if None ) ] ) def setup_db(db: Database): print(f"Database configured at {db.host}:{db.port}") if __name__ == "__main__": parser() ``` -------------------------------- ### Use `from_file` Annotation for Dynamic Sources Source: https://github.com/edornd/argdantic/blob/main/docs/guide/sources.md Use the `from_file` annotation to automatically add command-line arguments for reading configuration from files. This example demonstrates setting up `--dataset` and `--optim` arguments that load configurations from specified files. ```python from argdantic import Argdantic, from_file from pydantic import BaseModel class Dataset(BaseModel): name: str = "CIFAR10" batch_size: int = 32 tile_size: int = 256 shuffle: bool = True class Optim(BaseModel): name: str = "SGD" learning_rate: float = 0.01 momentum: float = 0.9 @Argdantic() def main( dataset: Dataset = from_file("dataset", default=None), optim: Optim = from_file("optim", default=None), ): print(dataset) print(optim) if __name__ == "__main__": main() ``` -------------------------------- ### Define Single Command with Multiple Sources Source: https://github.com/edornd/argdantic/blob/main/docs/guide/sources.md This example demonstrates defining a single command with multiple input sources: environment variables, JSON, YAML, and TOML files. Command line arguments have the highest priority. ```python from argdantic import Argdantic from pathlib import Path class Example(Argdantic): name: str description: str price: float tags: set[str] image: dict cmd = Example( sources=[ "./sources.env", "./sources.json", "./sources.yaml", "./sources.toml", ], name="example", description="Example item", price=2.3, tags={"example", "item", "tag"}, image={"url": "https://example.com/image.jpg", "name": "example.jpg"}, ) if __name__ == "__main__": print(cmd) ``` -------------------------------- ### Multiple Commands with Argdantic Source: https://github.com/edornd/argdantic/blob/main/docs/guide/customization.md When multiple commands are registered, their names are required for execution. This example demonstrates registering 'hi' and 'bye' commands. ```python from argdantic import Argdantic parser = Argdantic() @parser.command() def hi(name: str): print(f"Hello, {name}!") @parser.command() def bye(name: str): print(f"Goodbye, {name}!") ``` -------------------------------- ### Generated JSON Settings File Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/settings-stores.md Example of the JSON file generated by JsonSettingsStore, showing only the fields that were not excluded. ```json { "name": "Alice", "theme": "dark" } ``` -------------------------------- ### Configure Application with JsonSettingsStore Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/settings-stores.md Use JsonSettingsStore within an ArgParser command to automatically save configuration to a JSON file. This example excludes the 'email' field from being saved. ```python from pydantic import BaseModel from argdantic import ArgParser from argdantic.stores import JsonSettingsStore class UserConfig(BaseModel): name: str email: str theme: str = "dark" parser = ArgParser() @parser.command( stores=[ JsonSettingsStore( path="user_config.json", exclude={"email"} # Don't save email ) ] ) def configure(config: UserConfig): print(f"Configuration saved for {config.name}") if __name__ == "__main__": parser() ``` -------------------------------- ### Load Settings from YAML File Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/settings-sources.md Use `YamlSettingsSource` to load configuration from a YAML file. Ensure the `pyyaml` library is installed. The `path` parameter specifies the location of the YAML file. ```python from argdantic import ArgParser from argdantic.sources import YamlSettingsSource parser = ArgParser() @parser.command( sources=[YamlSettingsSource(path="settings.yaml")] ) def deploy(environment: str, replicas: int): print(f"Deploying to {environment} with {replicas} replicas") if __name__ == "__main__": parser() ``` ```yaml environment: production replicas: 3 ``` -------------------------------- ### Configuration from Files Source: https://github.com/edornd/argdantic/blob/main/_autodocs/INDEX.md Shows how to load configuration settings from external files (e.g., YAML, JSON). ```python from argdantic import Argdantic from pydantic import BaseModel class Settings(BaseModel): api_key: str app = Argdantic(config_files=['config.yaml']) @app.command() def main(settings: Settings): print(f'API Key: {settings.api_key}') ``` -------------------------------- ### Saving Configuration to Files Source: https://github.com/edornd/argdantic/blob/main/_autodocs/INDEX.md Demonstrates how to save the current configuration to a file. ```python from argdantic import Argdantic from pydantic import BaseModel class Settings(BaseModel): api_key: str app = Argdantic() @app.command() def save_config(settings: Settings, output_file: str = 'config.yaml'): settings.save(output_file) print(f'Configuration saved to {output_file}') ``` -------------------------------- ### Initialize EnvSettingsSource Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/settings-sources.md Demonstrates how to initialize EnvSettingsSource to read from environment variables and .env files. Specify options like env_file, env_prefix, and env_nested_delimiter for custom behavior. ```python from argdantic import ArgParser from argdantic.sources import EnvSettingsSource parser = ArgParser() @parser.command( sources=[ EnvSettingsSource(env_file=".env", env_prefix="APP_") ] ) def start(host: str, port: int): print(f"Server on {host}:{port}") if __name__ == "__main__": parser() ``` -------------------------------- ### PrimitiveArgument Example with Pydantic Model Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/argument-types.md Demonstrates how PrimitiveArgument is automatically used for scalar types like str, int, and float when defined in a Pydantic BaseModel. This example shows registering a command that accepts a Pydantic model with primitive fields. ```python from pydantic import BaseModel from argdantic import ArgParser class Person(BaseModel): name: str # PrimitiveArgument(str) age: int # PrimitiveArgument(int) height: float # PrimitiveArgument(float) parser = ArgParser() @parser.command() def register(person: Person): print(f"{person.name}: {person.age} years old, {person.height}m tall") if __name__ == "__main__": parser() ``` -------------------------------- ### Primitive Field Types Example Source: https://github.com/edornd/argdantic/blob/main/docs/guide/types.md This example demonstrates the usage of various primitive field types supported by Argdantic, including string, integer, float, bytes, and boolean flags. Boolean fields automatically generate --field and --no-field flags. ```python from argdantic import ArgumentParser parser = ArgumentParser() parser.add_argument("--name", type=str) parser.add_argument("--age", type=int) parser.add_argument("--weight", type=float) parser.add_argument("--data", type=bytes) parser.add_argument("--flag", type=bool, default=False) args = parser.parse_args() print(f"Name: {args.name}") print(f"Age: {args.age}") print(f"Weight: {args.weight}") print(f"Data: {args.data}") print(f"Flag: {args.flag}") ``` -------------------------------- ### Initialize ArgParser with JsonSettingsSource Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/settings-sources.md Demonstrates how to use JsonSettingsSource to load settings from a JSON file. Ensure the 'config.json' file exists with the expected structure. ```python from argdantic import ArgParser from argdantic.sources import JsonSettingsSource parser = ArgParser() @parser.command( sources=[JsonSettingsSource(path="config.json")] ) def init(name: str, debug: bool): print(f"Initialized {name} (debug={debug})") if __name__ == "__main__": parser() ``` -------------------------------- ### BaseSettingsStore Constructor Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/settings-stores.md Initializes a settings store. Specify the path for storing settings and optionally configure the output mode, encoding, and filtering options for fields. ```python def __init__( self, path: Union[str, Path], *, mode: Literal["python", "json"] = "python", 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 ``` -------------------------------- ### Configuring Settings Sources and Stores Source: https://github.com/edornd/argdantic/blob/main/_autodocs/configuration.md Illustrates how to configure custom settings sources (e.g., JSON files) and stores (e.g., for saving output) for a command using the 'sources' and 'stores' parameters of the @parser.command decorator. ```python from argdantic.sources import JsonSettingsSource from argdantic.stores import JsonSettingsStore @parser.command( sources=[JsonSettingsSource("config.json")], stores=[JsonSettingsStore("output.json")] ) def process(input_file: str): print(f"Processing {input_file}") ``` -------------------------------- ### Multiple Output Formats for Configuration Source: https://github.com/edornd/argdantic/blob/main/_autodocs/configuration.md Shows how to configure multiple settings stores to save configuration in different formats simultaneously. This allows for flexibility in how configuration data is managed and accessed across various tools or environments. ```python from argdantic.stores import ( JsonSettingsStore, YamlSettingsStore, TomlSettingsStore ) @parser.command( stores=[ JsonSettingsStore(path="config.json"), YamlSettingsStore(path="config.yaml"), TomlSettingsStore(path="config.toml"), ] ) def generate(name: str, version: str): print("Config generated in all formats") ``` -------------------------------- ### Enum Choices Example Source: https://github.com/edornd/argdantic/blob/main/_autodocs/INDEX.md Uses Python Enums to provide a restricted set of choices for an argument. ```python from argdantic import Argdantic from enum import Enum class Color(str, Enum): RED = 'red' GREEN = 'green' BLUE = 'blue' app = Argdantic() @app.command() def main(color: Color): print(f'Selected color: {color.value}') ``` -------------------------------- ### Load Configuration from JSON and Environment Files Source: https://github.com/edornd/argdantic/blob/main/_autodocs/common-patterns.md Configure your application by loading settings from multiple sources, including JSON files and environment variables. This pattern allows for flexible configuration management, with environment variables overriding JSON settings. ```python from pydantic import BaseModel from argdantic import ArgParser from argdantic.sources import ( JsonSettingsSource, EnvSettingsSource, ) class AppConfig(BaseModel): app_name: str = "MyApp" debug: bool = False log_level: str = "info" parser = ArgParser() @parser.command( sources=[ JsonSettingsSource("config.json"), # Base config EnvSettingsSource(env_file=".env"), # Override with env ] ) def run(config: AppConfig): print(f"Running {config.app_name}") print(f"Debug: {config.debug}") print(f"Log level: {config.log_level}") if __name__ == "__main__": parser() ``` -------------------------------- ### Initialize JsonSettingsStore Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/settings-stores.md Instantiate JsonSettingsStore to save settings to a JSON file. Specify the file path and optional parameters like encoding, field inclusion/exclusion, and serialization options. ```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 ``` -------------------------------- ### Field with Validation Example Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/ArgField.md Demonstrates using ArgField with pydantic validators and constraints for field validation. ```APIDOC ## Example: Field with Validation ```python from pydantic import BaseModel, field_validator from argdantic import ArgField, ArgParser class Config(BaseModel): port: int = ArgField( default=8080, description="Server port number", ge=1, le=65535 ) @field_validator('port') @classmethod def validate_port(cls, v): if v < 1024: raise ValueError('Port must be >= 1024 for unprivileged users') return v parser = ArgParser() @parser.command() def start(config: Config): print(f"Starting server on port {config.port}") if __name__ == "__main__": parser() ``` ``` -------------------------------- ### Cascading Configuration Sources Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/settings-sources.md Demonstrates how to define multiple configuration sources for a command, including JSON files and environment variables. Later sources override earlier ones, establishing a clear priority order. ```python from argdantic import ArgParser from argdantic.sources import EnvSettingsSource, JsonSettingsSource parser = ArgParser() @parser.command( sources=[ JsonSettingsSource(path="defaults.json"), # Base configuration JsonSettingsSource(path="config.json"), # Override with environment-specific EnvSettingsSource(env_file=".env"), # Override with environment variables ] ) def init(db_url: str, debug: bool, log_level: str): print(f"DB: {db_url}, Debug: {debug}, Level: {log_level}") if __name__ == "__main__": parser() ``` -------------------------------- ### Initialize ArgParser with TomlSettingsSource Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/settings-sources.md Shows how to use TomlSettingsSource to load settings from a TOML file, such as 'pyproject.toml'. The 'tomli' library is required. ```python from argdantic import ArgParser from argdantic.sources import TomlSettingsSource parser = ArgParser() @parser.command( sources=[TomlSettingsSource(path="pyproject.toml")] ) def config(version: str, author: str): print(f"{author}'s {version}") if __name__ == "__main__": parser() ``` -------------------------------- ### Example: Testing Validation Errors Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/testing.md Shows how to test for validation errors when invoking a command with invalid input. ```APIDOC ## Example: Testing Validation Errors ### Description This example demonstrates how to use `CLIRunner` to test for and assert validation errors in command-line arguments. ### Code ```python from pydantic import BaseModel, field_validator from argdantic import ArgParser from argdantic.testing import CLIRunner class Config(BaseModel): port: int @field_validator('port') @classmethod def port_in_range(cls, v): if not (1 <= v <= 65535): raise ValueError("Port must be between 1 and 65535") return v parser = ArgParser() @parser.command() def server(config: Config): print(f"Server on port {config.port}") def test_invalid_port(): runner = CLIRunner(catch_exceptions=True) result = runner.invoke(parser, ["--config.port", "99999"]) # Validation error should be caught assert result.exception is not None assert "Port must be between" in str(result.exception) if __name__ == "__main__": test_invalid_port() print("Validation test passed!") ``` ``` -------------------------------- ### Simple Command with Primitives Source: https://github.com/edornd/argdantic/blob/main/_autodocs/INDEX.md Demonstrates a basic command-line interface using primitive data types. ```python from argdantic import Argdantic app = Argdantic() @app.command() def main(name: str, age: int): print(f'Hello {name}, you are {age} years old.') ``` -------------------------------- ### Save Configuration to JSON Source: https://github.com/edornd/argdantic/blob/main/_autodocs/configuration.md Demonstrates how to save configuration to a JSON file using JsonSettingsStore. This is useful for applications that require configuration to be stored in a human-readable and widely compatible format. ```python from argdantic.stores import JsonSettingsStore @parser.command( stores=[ JsonSettingsStore(path="output.json") ] ) def save(name: str, value: int): print(f"Saved {name}={value}") ``` -------------------------------- ### Cascading Configuration Sources with Argdantic Source: https://github.com/edornd/argdantic/blob/main/_autodocs/common-patterns.md Load configuration from multiple sources like JSON files and environment variables, with a clear priority order. Ensure configuration files exist for the specified sources. ```python from pydantic import BaseModel from argdantic import ArgParser from argdantic.sources import ( JsonSettingsSource, EnvSettingsSource, ) class Config(BaseModel): database_url: str = "sqlite:///db.sqlite" api_port: int = 8000 log_level: str = "info" parser = ArgParser() @parser.command( sources=[ JsonSettingsSource("defaults.json"), # 1. Load defaults JsonSettingsSource("config.json"), # 2. Override with environment-specific EnvSettingsSource(env_file=".env"), # 3. Override with .env ] ) def start(config: Config): print(f"Database: {config.database_url}") print(f"API Port: {config.api_port}") print(f"Log Level: {config.log_level}") if __name__ == "__main__": parser() ``` -------------------------------- ### Load Configuration from Files Source: https://github.com/edornd/argdantic/blob/main/_autodocs/README.md Configure commands to load settings from external files like JSON and environment files by specifying `JsonSettingsSource` and `EnvSettingsSource` in the `sources` list. ```python from argdantic.sources import JsonSettingsSource, EnvSettingsSource @parser.command( sources=[ JsonSettingsSource("config.json"), EnvSettingsSource(env_file=".env"), ] ) def start(config: Config): pass ``` -------------------------------- ### Nested Dictionary Reconstruction Example Source: https://github.com/edornd/argdantic/blob/main/_autodocs/conversion-and-validation.md Demonstrates the conversion of a flat argparse Namespace into a nested dictionary structure, suitable for pydantic models. ```python # Raw argparse Namespace (flat): Namespace( person__name="Alice", person__address__street="123 Main", person__address__city="New York" ) # Converted to nested dict: { "person": { "name": "Alice", "address": { "street": "123 Main", "city": "New York" } } } # Validated against pydantic model: person = Person( name="Alice", address=Address( street="123 Main", city="New York" ) ) ``` -------------------------------- ### Basic ArgParser Initialization Source: https://github.com/edornd/argdantic/blob/main/_autodocs/configuration.md Initialize ArgParser with a program name and description for help messages. ```python from argdantic import ArgParser parser = ArgParser( name="myapp", description="A simple application" ) ``` -------------------------------- ### Add a Command to an ArgParser Source: https://github.com/edornd/argdantic/blob/main/docs/guide/intro.md This example demonstrates how to add a command to a parser using the `@parser.command()` decorator. The command function will be executed when the script is run. ```python from argdantic import ArgParser parser = ArgParser() @parser.command() def main(): print("Hello World!") if __name__ == "__main__": parser() ``` -------------------------------- ### ArgParser Command Decorator Example Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/Command.md Demonstrates creating a Command indirectly using the @parser.command() decorator. This is the typical way to define commands in Argdantic. ```python from argdantic import ArgParser from pydantic import BaseModel class Item(BaseModel): name: str quantity: int parser = ArgParser(name="shop") # The @parser.command() decorator creates a Command internally @parser.command( name="buy", help="Purchase items" ) def purchase_item(item: Item): print(f"Purchased {item.quantity} x {item.name}") # When invoked, the Command's __call__ handles argument validation and execution if __name__ == "__main__": parser() ``` -------------------------------- ### JSON Parsing Errors for Dictionary Input Source: https://github.com/edornd/argdantic/blob/main/_autodocs/conversion-and-validation.md Providing invalid JSON for a dictionary field will result in a `json.JSONDecodeError`. For example, `--config.data '{invalid json}'`. ```python from typing import Dict class Config(BaseModel): data: Dict[str, str] # CLI: --config.data '{invalid json}' # Error: json.JSONDecodeError ``` -------------------------------- ### BaseSettingsStore Constructor Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/settings-stores.md Initializes a BaseSettingsStore. This is an abstract base class for all settings stores, providing the fundamental interface for persisting validated arguments. ```APIDOC ## BaseSettingsStore Constructor ### Description Initializes a BaseSettingsStore. This is an abstract base class for all settings stores, providing the fundamental interface for persisting validated arguments. ### Method __init__ ### Parameters #### Path Parameters - **path** (Union[str, Path]) - Required - Path where the settings will be stored. #### Query Parameters - **mode** (Literal["python", "json"]) - Optional - Default: "python" - Output format mode (implementation-specific). - **encoding** (str) - Optional - Default: "utf-8" - Text encoding for file output. - **include** (Optional[Set[str]]) - Optional - Default: None - Set of field names to include in output (others excluded). - **exclude** (Optional[Set[str]]) - Optional - Default: None - Set of field names to exclude from output. - **by_alias** (bool) - Optional - Default: False - Use field aliases instead of field names in output. - **exclude_unset** (bool) - Optional - Default: False - Exclude fields that were not explicitly set. - **exclude_defaults** (bool) - Optional - Default: False - Exclude fields that have their default values. - **exclude_none** (bool) - Optional - Default: False - Exclude fields with None values. ``` -------------------------------- ### Unsupported Union Type Example Source: https://github.com/edornd/argdantic/blob/main/_autodocs/types.md General Union types with multiple non-None alternatives are not supported by Argdantic. Use Literal for multiple choices instead. ```python # Not supported status: Union[int, str] # Error: Union types not supported # Use Literal instead status: Literal["pending", "completed", "failed"] ``` -------------------------------- ### Command with Custom Sources and Stores Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/ArgParser.md Configure commands to load settings from custom sources like environment variables or JSON files, and to save parsed arguments to stores like JSON files. ```python from argdantic import ArgParser from argdantic.sources import EnvSettingsSource, JsonSettingsSource from argdantic.stores import JsonSettingsStore parser = ArgParser() @parser.command( sources=[ EnvSettingsSource(env_file=".env"), JsonSettingsSource(path="config.json"), ], stores=[ JsonSettingsStore(path="output.json"), ] ) def process(input_file: str, output_dir: str): print(f"Processing {input_file} to {output_dir}") if __name__ == "__main__": parser() ``` -------------------------------- ### Load .env File with EnvSettingsSource Source: https://github.com/edornd/argdantic/blob/main/_autodocs/configuration.md Configures Argdantic to load settings from a specified .env file. ```python from argdantic.sources import EnvSettingsSource @parser.command( sources=[ EnvSettingsSource(env_file=".env") ] ) def start(host: str, port: int): print(f"Starting on {host}:{port}") ``` -------------------------------- ### TomlSettingsStore Constructor Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/settings-stores.md Initializes a TomlSettingsStore to manage settings in a TOML file. It accepts various parameters to control serialization, encoding, and field inclusion/exclusion. ```APIDOC ## TomlSettingsStore Constructor ### Description Initializes a TomlSettingsStore to manage settings in a TOML file. It accepts various parameters to control serialization, encoding, and field inclusion/exclusion. ### Signature ```python def __init__( self, path: Union[str, Path], *, mode: Literal["python", "json"] = "python", 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 Parameters - **path** (Union[str, Path]) - Required - Path to the TOML file to write. #### Other Parameters - **mode** (Literal["python", "json"]) - Optional - Default: `"python"` - Serialization mode for complex types. - **encoding** (str) - Optional - Default: `"utf-8"` - Text encoding for the file. - **include** (Optional[Set[str]]) - Optional - Default: `None` - Fields to include. - **exclude** (Optional[Set[str]]) - Optional - Default: `None` - Fields to exclude. - **by_alias** (bool) - Optional - Default: `False` - Use field aliases. - **exclude_unset** (bool) - Optional - Default: `False` - Exclude unset fields. - **exclude_defaults** (bool) - Optional - Default: `False` - Exclude default values. - **exclude_none** (bool) - Optional - Default: `False` - Exclude None values. ### Notes Requires the `toml` library (included in `argdantic[toml]` extra). ``` -------------------------------- ### Field Validation with Constraints Source: https://github.com/edornd/argdantic/blob/main/_autodocs/common-patterns.md Enforce constraints on CLI arguments using Pydantic's field validators and ArgField. This example validates server host, port, and worker counts. ```python from pydantic import BaseModel, field_validator from argdantic import ArgField, ArgParser class ServerConfig(BaseModel): host: str = ArgField(description="Server hostname") port: int = ArgField( default=8080, description="Server port", ge=1, le=65535 ) workers: int = ArgField( default=4, description="Worker threads", ge=1 ) @field_validator('host') @classmethod def validate_host(cls, v): if not v or v.strip() == "": raise ValueError("Host cannot be empty") return v parser = ArgParser() @parser.command() def start(config: ServerConfig): print(f"Starting on {config.host}:{config.port} ({config.workers} workers)") if __name__ == "__main__": parser() ``` -------------------------------- ### Basic ArgParser Invocation Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/ArgParser.md Demonstrates how to create an ArgParser, define a command, and invoke the parser with default arguments (sys.argv). ```python from argdantic import ArgParser parser = ArgParser() @parser.command() def hello(name: str): return f"Hello, {name}!" if __name__ == "__main__": result = parser() ``` -------------------------------- ### ArgParser Constructor Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/ArgParser.md Illustrates the initialization of an ArgParser instance with custom name, description, and delimiter settings. This is useful for setting up the main parser for your CLI application. ```python from argdantic import ArgParser parser = ArgParser( name="myapp", description="My application", delimiter="." ) @parser.command() def greet(name: str): print(f"Hello, {name}!") if __name__ == "__main__": parser() ``` -------------------------------- ### Adding Descriptions to Fields with ArgField Source: https://github.com/edornd/argdantic/blob/main/docs/guide/customization.md Include a description for a CLI argument using the `description` keyword argument in `ArgField`. This description will appear in the `--help` output, guiding the user. ```python from argdantic import ArgField def main( name: str = ArgField(default="John", names=("name", "n"), description="your name"), age: int = ArgField(default=30, names=("age", "a"), description="your age"), ): print(f"Hello, {name}!") print(f"You are {age} years old.") if __name__ == "__main__": main() ``` -------------------------------- ### Instantiate and Call an ArgParser Source: https://github.com/edornd/argdantic/blob/main/docs/guide/intro.md This snippet shows the basic structure for importing, instantiating, and calling an ArgParser. A parser must have at least one command or group of commands to function correctly. ```python from argdantic import ArgParser parser = ArgParser() if __name__ == "__main__": parser() ``` -------------------------------- ### Type Mismatch Errors for List of Integers Source: https://github.com/edornd/argdantic/blob/main/_autodocs/conversion-and-validation.md Providing non-integer values within a list intended for integers will raise a validation error. Example: `--config.items 1 2 abc`. ```python from typing import List class Config(BaseModel): items: List[int] # CLI: --config.items 1 2 abc # Error: value is not a valid integer ``` -------------------------------- ### Create a Simple CLI Application Source: https://github.com/edornd/argdantic/blob/main/_autodocs/README.md Initialize an ArgParser and define a simple command with a single argument. The CLI can be executed when the script is run directly. ```python from argdantic import ArgParser parser = ArgParser() @parser.command() def hello(name: str): print(f"Hello, {name}!") if __name__ == "__main__": parser() ``` -------------------------------- ### Forced Command Grouping with Argdantic Source: https://github.com/edornd/argdantic/blob/main/docs/guide/customization.md Use 'force_group=True' to enforce command grouping, requiring users to specify the command name even with a single command. This example forces the 'greetings' command to be grouped. ```python from argdantic import Argdantic parser = Argdantic(force_group=True) @parser.command() def greetings(name: str): print(f"Hello, {name}!") ``` -------------------------------- ### EnvSettingsSource Parameters Source: https://github.com/edornd/argdantic/blob/main/_autodocs/configuration.md Details the parameters for EnvSettingsSource, used to load configuration from environment variables. ```python EnvSettingsSource( env_file: Optional[DotenvType], env_file_encoding: Optional[str] = "utf-8", env_nested_delimiter: Optional[str] = "__", env_prefix: str = "", env_case_sensitive: bool = False, ) ``` -------------------------------- ### Type Mismatch Errors for Integer Fields Source: https://github.com/edornd/argdantic/blob/main/_autodocs/conversion-and-validation.md Providing non-integer input for an integer field will raise a validation error indicating the value is not a valid integer. Example: `--config.count "not-a-number"`. ```python class Config(BaseModel): count: int # CLI: --config.count "not-a-number" # Error: value is not a valid integer ``` -------------------------------- ### Custom Settings Store for CSV Source: https://github.com/edornd/argdantic/blob/main/_autodocs/api-reference/settings-stores.md Implement a custom settings store to persist data in a CSV format. This example demonstrates how to define a callable that accepts a Pydantic model and writes its data to a CSV file. ```python from pydantic import BaseModel from argdantic import ArgParser def csv_store(settings: BaseModel) -> None: """Custom store that writes to CSV.""" import csv with open("config.csv", "w") as f: writer = csv.DictWriter(f, fieldnames=settings.model_fields.keys()) writer.writeheader() writer.writerow(settings.model_dump()) class UserSettings(BaseModel): name: str email: str age: int parser = ArgParser() @parser.command(stores=[csv_store]) def register(user: UserSettings): print(f"User {user.name} registered and saved") if __name__ == "__main__": parser() ``` -------------------------------- ### Customize `from_file` Behavior with `required` and `use_field` Source: https://github.com/edornd/argdantic/blob/main/docs/guide/sources.md Customize the `from_file` behavior by setting `required=False` and using `use_field` to specify a model field for the file path. This example shows how to load an optimizer configuration from a file specified by the `path` field. ```python from pathlib import Path from argdantic import Argdantic, from_file, YamlFileLoader from pydantic import BaseModel class Optim(BaseModel): path: Path name: str = "SGD" learning_rate: float = 0.01 momentum: float = 0.9 @Argdantic() def main( optim: Optim = from_file( "optim", loader=YamlFileLoader, use_field="path", required=False, ) ): print(optim) if __name__ == "__main__": main() ```