### Command-Line Invocation Examples Source: https://manderscience.com/typer-config/latest/examples/schema These examples demonstrate how to invoke the Python Typer application using the `--config` option to load the YAML configuration file. They show different ways to override or provide arguments and options. ```bash $ python simple_app.py --config config.yml ``` ```bash $ python simple_app.py --config config.yml others ``` ```bash $ python simple_app.py --config config.yml --opt1 people ``` -------------------------------- ### Install Typer Config Source: https://manderscience.com/typer-config/latest/install Installs the base Typer Config library. This is the minimal installation required to use the library. ```bash pip install typer-config ``` -------------------------------- ### Terminal Invocation Examples Source: https://manderscience.com/typer-config/latest/examples/default_config These terminal commands illustrate how to invoke the Typer application with different configurations. They show the default behavior, overriding arguments, and specifying an alternative configuration file. ```bash $ python simple_app.py things nothing stuff $ python simple_app.py others things nothing others $ python simple_app.py --opt1 people people nothing stuff $ python simple_app.py --config other.yml foo bar baz ``` -------------------------------- ### Install Optional Dependencies for File Formats Source: https://manderscience.com/typer-config/latest/install Installs optional dependency sets for Typer Config to support additional file formats. Each command installs support for a specific format (YAML, TOML, python-dotenv) or all formats. ```bash pip install typer-config[yaml] # includes pyyaml ``` ```bash pip install typer-config[toml] # includes toml ``` ```bash pip install typer-config[python-dotenv] # includes python-dotenv ``` ```bash pip install typer-config[all] # includes all optional dependencies ``` -------------------------------- ### Invoking Typer App with YAML Config (Terminal) Source: https://manderscience.com/typer-config/latest/examples/simple_yaml Examples demonstrating how to run the Typer application from the terminal using the `--config` option to specify a YAML configuration file. Shows how command-line arguments and options can override or supplement the configuration file. ```bash $ python simple_app.py --config config.yml things nothing stuff $ python simple_app.py --config config.yml others things nothing others $ python simple_app.py --config config.yml --opt1 people people nothing stuff ``` -------------------------------- ### YAML: Example Configuration for List Arguments Source: https://manderscience.com/typer-config/latest/known_issues This YAML file provides an example configuration for the Python script that handles list arguments. It shows how to specify values for string, option, and list arguments directly within the config file, which can then be loaded by typer-config. ```yaml # config.yml opt1: "apple" opt2: "pear" arg1: "lemon" arg2: ["oak", "aspen", "maple"] ``` -------------------------------- ### Quickstart: Add YAML Config to Typer App Source: https://manderscience.com/typer-config/latest/index Demonstrates how to use the `use_yaml_config` decorator to automatically add a `--config` option to a Typer application. This decorator must be placed after the `@app.command()` decorator. It enables loading parameters from a YAML configuration file. ```python import typer from typer_config import use_yaml_config # other formats available app = typer.Typer() @app.command() @use_yaml_config() # MUST BE AFTER @app.command() def main(foo: FooType): ... if __name__ == "__main__": app() ``` -------------------------------- ### YAML Configuration File Example Source: https://manderscience.com/typer-config/latest/examples/pydantic An example YAML file defining configuration parameters for the Typer application. This file is used to provide values for 'arg1', 'opt1', and 'opt2', which are then validated by the Pydantic model in the Python script. The structure of this file must match the fields defined in the 'AppConfig' Pydantic model. ```yaml arg1: stuff opt1: things opt2: nothing ``` -------------------------------- ### Command-Line Invocation Examples Source: https://manderscience.com/typer-config/latest/examples/explicit_config These terminal commands demonstrate how to invoke the Typer application with an explicit YAML configuration file. They show how the configuration is applied and how command-line arguments can override or supplement the config file settings. ```bash $ python simple_app.py --config config.yml # Expected output: things nothing stuff $ python simple_app.py --config config.yml others # Expected output: things nothing others $ python simple_app.py --config config.yml --opt1 people # Expected output: people nothing stuff ``` -------------------------------- ### Load YAML Configuration File Source: https://manderscience.com/typer-config/latest/api Loads configuration from a YAML file into a ConfigDict. Requires the 'pyyaml' library to be installed. Takes a file path as input and returns a dictionary representing the configuration. ```python from typing import Dict, Any from pathlib import Path from .__optional_imports import try_import TyperParameterName = str TyperParameterValue = Any ConfigDict = Dict[TyperParameterName, Any] FilePath = Union[Path, str] def yaml_loader(param_value: TyperParameterValue) -> ConfigDict: """YAML file loader. Args: param_value (TyperParameterValue): path of YAML file Raises: ModuleNotFoundError: pyyaml library is not installed Returns: ConfigDict: dictionary loaded from file """ yaml = try_import("yaml") if yaml is None: # pragma: no cover message = "Please install the pyyaml library." raise ModuleNotFoundError(message) with open(param_value, "r", encoding="utf-8") as _file: conf: ConfigDict = yaml.safe_load(_file) return conf ``` -------------------------------- ### Example Pyproject TOML Configuration Source: https://manderscience.com/typer-config/latest/examples/pyproject This TOML snippet shows the structure of the `pyproject.toml` file, specifically the `[tool.my_tool.parameters]` section, which contains the configuration values that the custom Typer CLI loader will read. ```toml [tool.my_tool.parameters] arg1 = "stuff" opt1 = "things" opt2 = "nothing" ``` -------------------------------- ### Typer App with YAML Config Source: https://manderscience.com/typer-config/latest/examples/default_config This Python script defines a Typer application that automatically loads configuration from a 'config.yml' file by default. It uses the `use_yaml_config` decorator from `typer_config.decorators`. The application accepts arguments and options, which can be overridden by command-line inputs. ```python from typing_extensions import Annotated import typer from typer_config.decorators import use_yaml_config # other formats available app = typer.Typer() @app.command() @use_yaml_config(default_value="config.yml") def main( arg1: str, opt1: Annotated[str, typer.Option()], opt2: Annotated[str, typer.Option()] = "hello", ): typer.echo(f"{opt1} {opt2} {arg1}") if __name__ == "__main__": app() ``` -------------------------------- ### TOML File Loader Source: https://manderscience.com/typer-config/latest/api Loads configuration data from a TOML file. It attempts to use the `tomllib` library first and falls back to the `toml` library if `tomllib` is not available. Requires the 'toml' library to be installed if `tomllib` is not found. ```APIDOC ## toml_loader ### Description TOML file loader. Attempts to use `tomllib` and falls back to `toml`. Requires the `toml` library if `tomllib` is unavailable. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # try: # config = toml_loader("path/to/your/config.toml") # except ModuleNotFoundError as e: # print(e) # 'Please install the toml library.' ``` ### Response #### Success Response (200) - **ConfigDict** (`ConfigDict`) - dictionary loaded from file #### Response Example ```json { "title": "TOML Example", "owner": { "name": "Tom", "dob": "1979-05-27T07:32:00-08:00" } } ``` ### Error Handling - **ModuleNotFoundError**: Raised if the `toml` library is not installed and `tomllib` is not available. ``` -------------------------------- ### YAML Loader Source: https://manderscience.com/typer-config/latest/api Loads configuration from a YAML file. This function requires the 'pyyaml' library to be installed. ```APIDOC ## yaml_loader ### Description YAML file loader. ### Method Not applicable (this is a function) ### Endpoint Not applicable (this is a function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **param_value** (TyperParameterValue) - Required - Path to the YAML file. ### Request Example ```python # Example usage within a Typer application # Assume 'config_loader' is a function that calls yaml_loader # config_loader("path/to/your/config.yaml") ``` ### Response #### Success Response (200) - **ConfigDict** (ConfigDict) - A dictionary representing the loaded configuration. #### Response Example ```json { "key1": "value1", "nested": { "subkey": "subvalue" } } ``` ### Errors - **ModuleNotFoundError**: Raised if the `pyyaml` library is not installed. ``` -------------------------------- ### Dump Configuration to TOML File with Python Source: https://manderscience.com/typer-config/latest/api The `toml_dumper` function serializes a `ConfigDict` object to a specified file location in TOML format. It requires the 'toml' library to be installed, and raises a `ModuleNotFoundError` if it is not available. The function takes the configuration dictionary and the file path as arguments. ```python def toml_dumper(config: ConfigDict, location: FilePath) -> None: """Dump config to TOML file. Args: config (ConfigDict): configuration location (FilePath): file to write Raises: ModuleNotFoundError: toml library is required for writing files """ toml = try_import("toml") if toml is None: # pragma: no cover message = "Please install the toml library to write TOML files." raise ModuleNotFoundError(message) with open(location, "w", encoding="utf-8") as _file: toml.dump(config, _file) # type: ignore ``` -------------------------------- ### Load Configuration from Dotenv Files in Python Source: https://manderscience.com/typer-config/latest/api The `dotenv_loader` function loads configuration settings from a specified .env file. It requires the `python-dotenv` library to be installed. If the library is not found, it raises a `ModuleNotFoundError`. The function returns a dictionary representing the loaded configuration. ```python from typing import Dict from dotenv import dotenv_values from typer_config.config import ConfigDict, TyperParameterValue def dotenv_loader(param_value: TyperParameterValue) -> ConfigDict: """Dotenv file loader. Args: param_value (TyperParameterValue): path of Dotenv file Raises: ModuleNotFoundError: python-dotenv library is not installed Returns: ConfigDict: dictionary loaded from file """ dotenv = try_import("dotenv") if dotenv is None: # pragma: no cover message = "Please install the python-dotenv library." raise ModuleNotFoundError(message) with open(param_value, "r", encoding="utf-8") as _file: # NOTE: I'm using a stream here so that the loader # will raise an exception when the file doesn't exist. conf: ConfigDict = dotenv.dotenv_values(stream=_file) return conf ``` -------------------------------- ### Load TOML Configuration File Source: https://manderscience.com/typer-config/latest/api Loads configuration from a TOML file into a ConfigDict. This loader attempts to use the `tomllib` module first (available in Python 3.11+) and falls back to the `toml` library if `tomllib` is not found. It requires either `tomllib` or the `toml` package to be installed. The function takes the path to the TOML file and returns its parsed content. ```python def toml_loader(param_value: TyperParameterValue) -> ConfigDict: """TOML file loader. Args: param_value (TyperParameterValue): path of TOML file Raises: ModuleNotFoundError: toml library is not installed Returns: ConfigDict: dictionary loaded from file """ # try `tomllib` first tomllib = try_import("tomllib") if tomllib is not None: with open(param_value, "rb") as _file: return tomllib.load(_file) # couldn't find `tommllib`, so try `toml` toml = try_import("toml") if toml is None: # pragma: no cover message = "Please install the toml library." raise ModuleNotFoundError(message) with open(param_value, "r", encoding="utf-8") as _file: return toml.load(_file) ``` -------------------------------- ### YAML Dumper for Configuration Source: https://manderscience.com/typer-config/latest/api The `yaml_dumper` function writes a configuration dictionary to a YAML file. It requires the `pyyaml` library. If `pyyaml` is not installed, it raises a `ModuleNotFoundError`. The function takes the configuration and the output file path, opening the file in write mode with UTF-8 encoding. ```python def yaml_dumper(config: ConfigDict, location: FilePath) -> None: """Dump config to YAML file. Args: config (ConfigDict): configuration location (FilePath): file to write Raises: ModuleNotFoundError: pyyaml is required """ yaml = try_import("yaml") if yaml is None: # pragma: no cover message = "Please install the pyyaml library." raise ModuleNotFoundError(message) with open(location, "w", encoding="utf-8") as _file: yaml.dump(config, _file) ``` -------------------------------- ### Typer App with YAML Config (Python) Source: https://manderscience.com/typer-config/latest/examples/simple_yaml A simple Typer application that utilizes the `use_yaml_config` decorator to load configuration options from a YAML file. It defines command-line arguments and options that can be overridden by the configuration file. ```python from typing_extensions import Annotated import typer from typer_config.decorators import use_yaml_config # other formats available app = typer.Typer() @app.command() @use_yaml_config() def main( arg1: str, opt1: Annotated[str, typer.Option()], opt2: Annotated[str, typer.Option()] = "hello", ): typer.echo(f"{opt1} {opt2} {arg1}") if __name__ == "__main__": app() ``` -------------------------------- ### Load Dotenv Configuration with dotenv_loader Source: https://manderscience.com/typer-config/latest/api The dotenv_loader function parses a Dotenv file (.env) into a ConfigDict. It depends on the 'python-dotenv' library. If this library is not installed, a ModuleNotFoundError is raised. ```python def dotenv_loader(param_value: TyperParameterValue) -> ConfigDict: """Dotenv file loader. Args: param_value (TyperParameterValue): path of Dotenv file Raises: ModuleNotFoundError: python-dotenv library is not installed Returns: ConfigDict: dictionary loaded from file """ dotenv = try_import("dotenv") if dotenv is None: # pragma: no cover message = "Please install the python-dotenv library." raise ModuleNotFoundError(message) with open(param_value, "r", encoding="utf-8") as _file: # NOTE: I'm using a stream here so that the loader # will raise an exception when the file doesn't exist. conf: ConfigDict = dotenv.dotenv_values(stream=_file) return conf ``` -------------------------------- ### Get Dictionary Section Utility Source: https://manderscience.com/typer-config/latest/api Retrieves a nested section from a dictionary based on a list of keys. If any key is not found, it defaults to an empty dictionary, preventing errors. ```python from typing import Dict, Any, Optional, List def get_dict_section( _dict: Dict[Any, Any], keys: Optional[List[Any]] = None ) -> Dict[Any, Any]: """Get section of a dictionary. Args: _dict (Dict[str, Any]): dictionary to access keys (List[str]): list of keys to successively access in the dictionary Returns: Dict[str, Any]: section of dictionary requested """ if keys is not None: for key in keys: _dict = _dict.get(key, {}) return _dict ``` -------------------------------- ### Load YAML Configuration with yaml_loader Source: https://manderscience.com/typer-config/latest/api The yaml_loader function reads a YAML file and parses its content into a ConfigDict. It requires the 'pyyaml' library to be installed. If the library is not found, it raises a ModuleNotFoundError. ```python def yaml_loader(param_value: TyperParameterValue) -> ConfigDict: """YAML file loader. Args: param_value (TyperParameterValue): path of YAML file Raises: ModuleNotFoundError: pyyaml library is not installed Returns: ConfigDict: dictionary loaded from file """ yaml = try_import("yaml") if yaml is None: # pragma: no cover message = "Please install the pyyaml library." raise ModuleNotFoundError(message) with open(param_value, "r", encoding="utf-8") as _file: conf: ConfigDict = yaml.safe_load(_file) return conf ``` -------------------------------- ### Using `is_eager=True` for Config Parameters in Typer Source: https://manderscience.com/typer-config/latest/how Demonstrates how to define a configuration parameter with `is_eager=True` to ensure it is processed first. This is crucial when directly using the `config` parameter in your Typer application to avoid unpredictable parameter values. ```python config: str = typer.Option("", is_eager=True, callback=...) ``` -------------------------------- ### use_config Decorator Source: https://manderscience.com/typer-config/latest/api The `use_config` decorator allows you to easily integrate configuration loading into your Typer commands. It accepts a callback function to handle the configuration loading process and allows customization of the parameter name and help text. ```APIDOC ## use_config Decorator ### Description Decorator for using configuration on a typer command. ### Method DECORATOR ### Endpoint N/A (Decorator) ### Parameters #### Arguments - **callback** (ConfigParameterCallback) - Required - config parameter callback to load - **param_name** (TyperParameterName) - Optional - name of config parameter. Defaults to "config". - **param_help** (str) - Optional - config parameter help string. Defaults to "Configuration file.". ### Request Example ```python import typer from typer_config.decorators import use_config from typer_config import yaml_conf_callback app = typer.Typer() @app.command() @use_config(yaml_conf_callback) def main(...): pass ``` ### Response #### Success Response - **TyperCommandDecorator** (TyperCommandDecorator) - decorator to apply to command ``` -------------------------------- ### JSON File Loader Source: https://manderscience.com/typer-config/latest/api Loads configuration data from a JSON file. This function parses the JSON content into a dictionary. ```APIDOC ## json_loader ### Description JSON file loader. Parses the JSON content of a file into a configuration dictionary. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # config = json_loader("path/to/your/config.json") ``` ### Response #### Success Response (200) - **ConfigDict** (`ConfigDict`) - dictionary loaded from file #### Response Example ```json { "key1": "value1", "key2": { "nested_key": "nested_value" } } ``` ``` -------------------------------- ### File Existence Check and Warning Source: https://manderscience.com/typer-config/latest/api Checks if a file exists at the given path. If the file does not exist, it issues a warning using a simple format. Returns a boolean indicating the file's existence. ```python from pathlib import Path from typing import Union from warnings import showwarning # Assuming SimpleWarningFormat and ORIGINAL_WARNING_FORMATTER are defined elsewhere # For this standalone snippet, we'll include them: ORIGINAL_WARNING_FORMATTER = warnings.formatwarning class SimpleWarningFormat: """Simple Warning Formatter.""" def __enter__(self) -> None: warnings.formatwarning = lambda msg, category, *args, **kwargs: f"{category.__name__}: {msg}\n" def __exit__(self, exc_type, exc_value, exc_tb) -> None: warnings.formatwarning = ORIGINAL_WARNING_FORMATTER def file_exists_and_warn(file_path: Union[Path, str]) -> bool: """Check if file exists and warn if it doesn't exist. Args: file_path (Union[Path, str]): file path to check Returns: bool: whether file exists """ file_path_exists = Path(file_path).is_file() if not file_path_exists: msg = f"No such file: '{file_path}'" with SimpleWarningFormat(): showwarning(msg, UserWarning, "", 0) return file_path_exists ``` -------------------------------- ### Load JSON Configuration File Source: https://manderscience.com/typer-config/latest/api Loads configuration from a JSON file into a ConfigDict. This function takes the path to the JSON file as input. It directly parses the JSON content and returns it as a dictionary. No external libraries beyond standard Python are required for this loader. ```python def json_loader(param_value: TyperParameterValue) -> ConfigDict: """JSON file loader. Args: param_value (TyperParameterValue): path of JSON file Returns: ConfigDict: dictionary loaded from file """ with open(param_value, "r", encoding="utf-8") as _file: conf: ConfigDict = json.load(_file) return conf ``` -------------------------------- ### file_exists_and_warn Source: https://manderscience.com/typer-config/latest/api Checks if a given file path exists. If the file does not exist, it issues a warning to the user. ```APIDOC ## file_exists_and_warn ### Description Check if file exists and warn if it doesn't exist. ### Method *Not applicable (function signature provided)* ### Endpoint *Not applicable (function signature provided)* ### Parameters #### Path Parameters *None* #### Query Parameters *None* #### Request Body *None* ### Request Example *Not applicable (function signature provided)* ### Response #### Success Response (200) *Not applicable (function signature provided)* #### Response Example *Not applicable (function signature provided)* **Function Signature:** ```python file_exists_and_warn(file_path: Union[Path, str]) -> bool ``` **Parameters:** - `file_path` (Union[Path, str]) - Required - file path to check **Returns:** - `bool` (bool) - whether file exists ``` -------------------------------- ### JSON Dumper for Configuration Source: https://manderscience.com/typer-config/latest/api The `json_dumper` function is responsible for writing a configuration dictionary to a JSON file. It takes the configuration as a `ConfigDict` and the output file path as arguments. It opens the file in write mode with UTF-8 encoding. ```python def json_dumper(config: ConfigDict, location: FilePath) -> None: """Dump config to JSON file. Args: config (ConfigDict): configuration location (FilePath): file to write """ with open(location, "w", encoding="utf-8") as _file: json.dump(config, _file) ``` -------------------------------- ### Dump YAML Config Decorator for Typer Commands Source: https://manderscience.com/typer-config/latest/api The `dump_yaml_config` decorator is used with Typer commands to automatically save invocation parameters to a YAML file. It requires the `pyyaml` library to be installed. The decorator takes the file path as an argument and must be placed after the `@app.command()` decorator. ```python def dump_yaml_config(location: FilePath) -> TyperCommandDecorator: """Decorator for dumping a YAML file with parameters from an invocation of a typer command. Usage: ```py import typer from typer.decorators import dump_yaml_config app = typer.Typer() @app.command() # NOTE: @dump_yaml_config MUST BE AFTER @app.command() @dump_yaml_config("config_dump_dir/params.yml") def cmd(...): ... ``` Args: location (FilePath): config file to write Returns: TyperCommandDecorator: command decorator """ return dump_config(dumper=yaml_dumper, location=location) ``` -------------------------------- ### Python Typer App with YAML Schema Validation Source: https://manderscience.com/typer-config/latest/examples/schema This Python script defines a Typer application that accepts a configuration file. It uses a schema to validate the contents of the YAML configuration file loaded via `yaml_loader` and `conf_callback_factory`. The `use_config` decorator applies the custom configuration callback. ```python from typing import Any, Dict from typing_extensions import Annotated from schema import Schema import typer from typer_config import yaml_loader, conf_callback_factory, use_config schema = Schema({"arg1": str, "opt1": str, "opt2": str}) def validator_loader(param_value: str) -> Dict[str, Any]: conf = yaml_loader(param_value) conf = schema.validate(conf) # raises an exception if not valid return conf validator_callback = conf_callback_factory(validator_loader) app = typer.Typer() @app.command() @use_config(validator_callback) def main( arg1: str, opt1: Annotated[str, typer.Option()], opt2: Annotated[str, typer.Option()] = "hello", ): typer.echo(f"{opt1} {opt2} {arg1}") if __name__ == "__main__": app() ``` -------------------------------- ### use_dotenv_config Decorator Source: https://manderscience.com/typer-config/latest/api This decorator allows you to easily load configuration from a .env file for your Typer commands. It handles parameter creation, loading, and transformation of the configuration data. ```APIDOC ## use_dotenv_config Decorator ### Description Decorator for using dotenv configuration on a typer command. It simplifies the process of loading configuration from `.env` files into your Typer application. ### Method Decorator ### Endpoint N/A (Decorator) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import typer from typer_config.decorators import use_dotenv_config app = typer.Typer() @app.command() @use_dotenv_config(section=['database'], param_name='db_config') def main(db_config: dict = typer.Option(...)): print(f"Database config: {db_config}") if __name__ == '__main__': app() ``` ### Response #### Success Response (200) N/A (Decorator) #### Response Example N/A (Decorator) ``` -------------------------------- ### Python Pydantic and Typer App with YAML Config Validation Source: https://manderscience.com/typer-config/latest/examples/pydantic A Python script using Typer and Pydantic to load and validate application configuration from a YAML file. It defines a Pydantic BaseModel for configuration structure and uses a custom callback factory to perform validation before the application logic executes. Dependencies include 'typer', 'pydantic', and 'typer-config'. ```python from typing import Any, Dict from typing_extensions import Annotated from pydantic import BaseModel import typer from typer_config.loaders import yaml_loader from typer_config.callbacks import conf_callback_factory from typer_config.decorators import use_config class AppConfig(BaseModel): arg1: str opt1: str opt2: str def validator_loader(param_value: str) -> Dict[str, Any]: conf = yaml_loader(param_value) AppConfig.validate(conf) # raises an exception if not valid return conf validator_callback = conf_callback_factory(validator_loader) app = typer.Typer() @app.command() @use_config(validator_callback) def main( arg1: str, opt1: Annotated[str, typer.Option()], opt2: Annotated[str, typer.Option()] = "hello", ): typer.echo(f"{opt1} {opt2} {arg1}") if __name__ == "__main__": app() ``` -------------------------------- ### Simple Warning Formatter Context Manager Source: https://manderscience.com/typer-config/latest/api A context manager that temporarily overrides the default warning formatter to provide a simpler format. It restores the original formatter upon exiting the context. ```python import warnings from typing import Any ORIGINAL_WARNING_FORMATTER = warnings.formatwarning class SimpleWarningFormat: """Simple Warning Formatter.""" def __enter__(self: SimpleWarningFormat) -> None: # noqa: D105 warnings.formatwarning = ( lambda msg, category, *args, **kwargs: f"{category.__name__}: {msg}\n" # noqa: ARG005 ) def __exit__( self: SimpleWarningFormat, exc_type: Any, # noqa: ANN401 exc_value: Any, # noqa: ANN401 exc_tb: Any, # noqa: ANN401 ) -> None: warnings.formatwarning = ORIGINAL_WARNING_FORMATTER ``` -------------------------------- ### Dotenv Configuration Callback Source: https://manderscience.com/typer-config/latest/api Provides a callback function for Typer to load configuration from .env files. It uses a factory to create a callback that transforms loaded environment variables. ```APIDOC ## dotenv_conf_callback ### Description Dotenv typer config parameter callback. ### Method N/A (This is a callback function definition) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # This is a callback, not directly invoked with a request body. # Example usage within a Typer app would involve defining a parameter # that uses this callback. ``` ### Response #### Success Response (N/A) N/A #### Response Example ```json { "message": "Configuration loaded from .env file" } ``` ### Raises - **BadParameter**: bad parameter value ``` -------------------------------- ### JSON Configuration Callback Source: https://manderscience.com/typer-config/latest/api Offers a callback function for Typer to load configuration from JSON files. It wraps a JSON loader with transformation capabilities. ```APIDOC ## json_conf_callback ### Description JSON typer config parameter callback. ### Method N/A (This is a callback function definition) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # This is a callback, not directly invoked with a request body. # Example usage within a Typer app would involve defining a parameter # that uses this callback. ``` ### Response #### Success Response (N/A) N/A #### Response Example ```json { "message": "Configuration loaded from JSON file" } ``` ### Raises - **BadParameter**: bad parameter value ``` -------------------------------- ### TOML Configuration Callback Source: https://manderscience.com/typer-config/latest/api Provides a callback function for Typer to load configuration from TOML files. It utilizes a factory and loader transformer for TOML data. ```APIDOC ## toml_conf_callback ### Description TOML typer config parameter callback. ### Method N/A (This is a callback function definition) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # This is a callback, not directly invoked with a request body. # Example usage within a Typer app would involve defining a parameter # that uses this callback. ``` ### Response #### Success Response (N/A) N/A #### Response Example ```json { "message": "Configuration loaded from TOML file" } ``` ### Raises - **BadParameter**: bad parameter value ``` -------------------------------- ### Use Configuration Decorator for Typer Commands (Python) Source: https://manderscience.com/typer-config/latest/api The `use_config` decorator is applied to Typer commands to automatically load configuration from a file. It requires a callback function to process the configuration and can be customized with parameter name and help text. This decorator modifies the command's signature to include the configuration parameter. ```python from typing import Callable, Any from inspect import signature, Parameter from functools import wraps from typer import TyperCommand, Option # Assuming these types are defined elsewhere in the library TyperParameterName = str ConfigParameterCallback = Callable[[str], Any] TyperCommandDecorator = Callable[[TyperCommand], TyperCommand] def use_config( callback: ConfigParameterCallback, param_name: TyperParameterName = "config", param_help: str = "Configuration file.", ) -> TyperCommandDecorator: """Decorator for using configuration on a typer command. Usage: ```py import typer from typer_config.decorators import use_config from typer_config import yaml_conf_callback # whichever callback to use app = typer.Typer() @app.command() @use_config(yaml_conf_callback) def main(...): pass # ... command logic ``` Args: callback (ConfigParameterCallback): config parameter callback to load param_name (TyperParameterName, optional): name of config parameter. Defaults to "config". param_help (str, optional): config parameter help string. Defaults to "Configuration file.". Returns: TyperCommandDecorator: decorator to apply to command """ def decorator(cmd: TyperCommand) -> TyperCommand: # NOTE: modifying a function's __signature__ is dangerous # in the sense that it only affects inspect.signature(). # It does not affect the actual function implementation. # So, a caller can be confused how to pass parameters to # the function with modified signature. sig = signature(cmd, eval_str=True) config_param = Parameter( param_name, kind=Parameter.KEYWORD_ONLY, annotation=str, default=Option("", callback=callback, is_eager=True, help=param_help), ) new_sig = sig.replace(parameters=[*sig.parameters.values(), config_param]) @wraps(cmd) def wrapped(*args, **kwargs): # noqa: ANN20,ANN002,ANN003 # NOTE: need to delete the config parameter # to match the wrapped command's signature. kwargs.pop(param_name, None) return cmd(*args, **kwargs) wrapped.__signature__ = new_sig # type: ignore return wrapped return decorator ``` -------------------------------- ### Load INI Configuration File Source: https://manderscience.com/typer-config/latest/api Loads configuration from an INI file into a ConfigDict. INI files require top-level sections. This loader is often combined with `loader_transformer` to extract specific sections from the loaded configuration. It takes the path to the INI file as input and returns a dictionary representing the file's content. ```python def ini_loader(param_value: TyperParameterValue) -> ConfigDict: """INI file loader. Note: INI files must have sections at the top level. You probably want to combine this with `loader_transformer` to extract the correct section. For example: ```py ini_section_loader = loader_transformer( ini_loader, config_transformer=lambda config: config["section"], ) ``` Args: param_value (TyperParameterValue): path of INI file Returns: ConfigDict: dictionary loaded from file """ ini_parser = ConfigParser() with open(param_value, "r", encoding="utf-8") as _file: ini_parser.read_file(_file) conf: ConfigDict = { sect: dict(ini_parser.items(sect)) for sect in ini_parser.sections() } return conf ``` -------------------------------- ### SimpleWarningFormat Source: https://manderscience.com/typer-config/latest/api A context manager that temporarily changes the global warning format to a simpler one, useful for custom warning messages. ```APIDOC ## SimpleWarningFormat ### Description Simple Warning Formatter. ### Method *Not applicable (class definition provided)* ### Endpoint *Not applicable (class definition provided)* ### Parameters *None* ### Request Example *None* ### Response *None* **Class Definition:** ```python class SimpleWarningFormat: """Simple Warning Formatter.""" def __enter__(self: SimpleWarningFormat) -> None: warnings.formatwarning = ( lambda msg, category, *args, **kwargs: f"{category.__name__}: {msg}\n" ) def __exit__( self: SimpleWarningFormat, exc_type: Any, exc_value: Any, exc_tb: Any, ) -> None: warnings.formatwarning = ORIGINAL_WARNING_FORMATTER ``` ``` -------------------------------- ### conf_callback_factory Source: https://manderscience.com/typer-config/latest/api Creates a Typer configuration callback function. This factory allows you to define how configuration files are loaded and merged into the Typer CLI's default context. ```APIDOC ## conf_callback_factory ### Description Typer configuration callback factory. This function creates a callback that loads configuration from a specified loader and updates the Click context's default map. ### Method Factory Function ### Endpoint N/A (This is a Python function, not an HTTP endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (This is a Python function signature) ### Request Example ```python from typer_config import conf_callback_factory, ConfigLoader from typer import Typer, Context, CallbackParam def my_config_loader(value: str) -> dict: # Implement your config loading logic here # For example, load from a file based on the value if value == "prod": return {"database_url": "postgres://prod_user@host/prod_db"} return {"database_url": "postgres://dev_user@host/dev_db"} callback = conf_callback_factory(loader=my_config_loader) # Example usage within a Typer app (simplified) def main(config_env: str = typer.Option(..., callback=callback)): print(f"Config environment: {config_env}") if __name__ == "__main__": from typer import Typer app = Typer() app.command()(main) app([]) # Example call, in real use it would be `app(['--config-env', 'prod'])` ``` ### Response #### Success Response (200) Returns a `ConfigParameterCallback` function. #### Response Example ```python # The returned value is a callable function, not a direct JSON response. def config_parameter_callback(ctx: Context, param: CallbackParam, param_value: str): # ... internal logic ... return param_value ``` ``` -------------------------------- ### YAML Configuration Callback Source: https://manderscience.com/typer-config/latest/api Offers a callback function for Typer to load configuration from YAML files. It integrates a YAML loader with conditional logic. ```APIDOC ## yaml_conf_callback ### Description YAML typer config parameter callback. ### Method N/A (This is a callback function definition) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # This is a callback, not directly invoked with a request body. # Example usage within a Typer app would involve defining a parameter # that uses this callback. ``` ### Response #### Success Response (N/A) N/A #### Response Example ```json { "message": "Configuration loaded from YAML file" } ``` ### Raises - **BadParameter**: bad parameter value ``` -------------------------------- ### Create Typer Config Callback Factory (Python) Source: https://manderscience.com/typer-config/latest/api The conf_callback_factory is a Python function that generates a configuration parameter callback for Typer applications. It takes a ConfigLoader, which processes CLI arguments into a dictionary, and merges this dictionary into the Click context's default map. This function is crucial for enabling configuration loading from external sources into Typer applications. ```python from typing import Dict, Any from typer.models import CallbackParam from click import Context from typer.main import TyperParameterValue from typer.exceptions import BadParameter ConfigLoader = lambda param_value: Dict[str, Any] ConfigParameterCallback = Any def conf_callback_factory(loader: ConfigLoader) -> ConfigParameterCallback: """Typer configuration callback factory. Args: loader (ConfigLoader): Config loader function that takes the value passed to the typer CLI and returns a dictionary that is applied to the click context's default map. Returns: ConfigParameterCallback: Configuration parameter callback function. """ def _callback( ctx: Context, param: CallbackParam, param_value: TyperParameterValue ) -> TyperParameterValue: """Generated typer config parameter callback. Args: ctx (typer.Context): typer context (automatically passed) param (typer.CallbackParam): typer callback parameter (automatically passed) param_value (TyperParameterValue): parameter value passed to typer (automatically passed) Raises: BadParameter: bad parameter value Returns: TyperParameterValue: must return back the given parameter """ try: conf = loader(param_value) # Load config file ctx.default_map = ctx.default_map or {} # Initialize the default map ctx.default_map.update(conf) # Merge the config Dict into default_map except Exception as ex: raise BadParameter(str(ex), ctx=ctx, param=param) from ex return param_value return _callback ``` -------------------------------- ### Dump Configuration to JSON using Typer Decorator Source: https://manderscience.com/typer-config/latest/api The `dump_json_config` decorator simplifies the process of saving Typer command arguments to a JSON file. It leverages the `dump_config` function internally, using a predefined `json_dumper`. Similar to `dump_config`, this decorator must be placed after `@app.command()` and requires the file path for the output JSON. ```python def dump_json_config(location: FilePath) -> TyperCommandDecorator: """Decorator for dumping a JSON file with parameters from an invocation of a typer command. Usage: ```py import typer from typer.decorators import dump_json_config app = typer.Typer() @app.command() # NOTE: @dump_json_config MUST BE AFTER @app.command() @dump_json_config("config_dump_dir/params.json") def cmd(...): ... ``` Args: location (FilePath): config file to write Returns: TyperCommandDecorator: command decorator """ return dump_config(dumper=json_dumper, location=location) ``` -------------------------------- ### conf_callback_factory Source: https://manderscience.com/typer-config/latest/api Creates a configuration callback function for Typer CLI applications. This callback loads configuration values using a provided loader and updates the Click context's default map. ```APIDOC ## conf_callback_factory ### Description Creates a configuration callback function for Typer CLI applications. This callback loads configuration values using a provided loader and updates the Click context's default map. ### Method Factory Function ### Endpoint N/A (This is a Python function, not a REST endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from typer import Typer, Context, CallbackParam from typer.models import TyperParameterValue from typing import Dict, Any # Assume ConfigLoader and ConfigParameterCallback are defined elsewhere ConfigLoader = Any ConfigParameterCallback = Any def conf_callback_factory(loader: ConfigLoader) -> ConfigParameterCallback: """Typer configuration callback factory.""" def _callback( ctx: Context, param: CallbackParam, param_value: TyperParameterValue ) -> TyperParameterValue: try: conf = loader(param_value) ctx.default_map = ctx.default_map or {} ctx.default_map.update(conf) except Exception as ex: raise Exception(str(ex)) from ex # Simplified exception for example return param_value return _callback # Example Usage: def my_config_loader(value: str) -> Dict[str, Any]: # In a real scenario, this would load from a file based on 'value' if value == "dev": return {"database_url": "sqlite:///dev.db", "debug": True} return {} # Default empty config config_callback = conf_callback_factory(my_config_loader) # This 'config_callback' would then be used in a Typer application # Example: app.add_option('--config', callback=config_callback) ``` ### Response #### Success Response (200) N/A (This is a Python function, not a REST endpoint) #### Response Example N/A ``` -------------------------------- ### Python Decorator for Typer Configuration Loading Source: https://manderscience.com/typer-config/latest/api The `use_config` decorator in `typer-config` is used to add configuration loading capabilities to Typer commands. It takes a callback function to handle configuration loading and optionally allows customization of the parameter name and help string. This decorator modifies the command's signature to include the configuration parameter. ```python from inspect import Parameter, signature from functools import wraps from typer import Option from typer.models import TyperCommand # Assuming these types are defined elsewhere in the library # from .callback import ConfigParameterCallback # from .typing import TyperParameterName # from .decorators import TyperCommandDecorator # Placeholder types for demonstration purposes class ConfigParameterCallback: pass class TyperParameterName(str): pass class TyperCommandDecorator(object): pass def use_config( callback: ConfigParameterCallback, param_name: TyperParameterName = "config", param_help: str = "Configuration file.", ) -> TyperCommandDecorator: """Decorator for using configuration on a typer command. Usage: ```py import typer from typer_config.decorators import use_config from typer_config import yaml_conf_callback # whichever callback to use app = typer.Typer() @app.command() @use_config(yaml_conf_callback) def main(...): ... ``` Args: callback (ConfigParameterCallback): config parameter callback to load param_name (TyperParameterName, optional): name of config parameter. Defaults to "config". param_help (str, optional): config parameter help string. Defaults to "Configuration file.". Returns: TyperCommandDecorator: decorator to apply to command """ def decorator(cmd: TyperCommand) -> TyperCommand: # NOTE: modifying a function's __signature__ is dangerous # in the sense that it only affects inspect.signature(). # It does not affect the actual function implementation. # So, a caller can be confused how to pass parameters to # the function with modified signature. sig = signature(cmd, eval_str=True) config_param = Parameter( param_name, kind=Parameter.KEYWORD_ONLY, annotation=str, default=Option("", callback=callback, is_eager=True, help=param_help), ) new_sig = sig.replace(parameters=[*sig.parameters.values(), config_param]) @wraps(cmd) def wrapped(*args, **kwargs): # noqa: ANN20,ANN002,ANN003 # NOTE: need to delete the config parameter # to match the wrapped command's signature. kwargs.pop(param_name, None) return cmd(*args, **kwargs) wrapped.__signature__ = new_sig # type: ignore return wrapped return decorator ```