### Example YAML configuration file Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/settings_sources.md Sample YAML structure for settings. ```yaml # config.yaml database: host: localhost port: 5432 app: api_key: secret123 ``` -------------------------------- ### Use EnvSettingsSource Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/settings_sources.md Example of loading settings from environment variables. ```python import os from pydantic_settings import BaseSettings, EnvSettingsSource class Settings(BaseSettings): database_url: str debug: bool = False # Load from DATABASE_URL and DEBUG env vars os.environ['DATABASE_URL'] = 'postgresql://...' os.environ['DEBUG'] = 'true' settings = Settings() ``` -------------------------------- ### Example TOML configuration file Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/settings_sources.md Sample TOML structure for settings. ```toml # pyproject.toml [tool.myapp] api_key = "secret123" database_url = "postgresql://..." ``` -------------------------------- ### Example JSON configuration file Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/settings_sources.md Sample JSON structure for settings. ```json { "api_key": "secret123", "database": { "host": "localhost", "port": 5432 } } ``` -------------------------------- ### Use InitSettingsSource Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/settings_sources.md Example of passing settings values directly during initialization. ```python from pydantic_settings import BaseSettings class Settings(BaseSettings): api_key: str debug: bool = False # Values passed to __init__ have highest priority settings = Settings(api_key='secret', debug=True) ``` -------------------------------- ### Install Pydantic Settings Source: https://github.com/pydantic/pydantic-settings/blob/main/docs/index.md Use pip to install the package. ```bash pip install pydantic-settings ``` -------------------------------- ### Use DotEnvSettingsSource Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/settings_sources.md Example of configuring settings to load from a .env file. ```python from pathlib import Path from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict( env_file=Path('.env'), env_file_encoding='utf-8', ) api_key: str database_url: str ``` -------------------------------- ### Configure ConfigFileSourceType in Settings Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/types.md Example of using filesystem and package resource paths for configuration sources. ```python from pathlib import Path from importlib.resources import files from pydantic_settings import BaseSettings, JsonConfigSettingsSource class Settings(BaseSettings): api_key: str @classmethod def settings_customise_sources(cls, ...): # From filesystem fs_source = JsonConfigSettingsSource( cls, json_file='config.json' ) # From package resources pkg_source = JsonConfigSettingsSource( cls, json_file=files('mypackage').joinpath('config.json') ) return (fs_source, pkg_source, ...) ``` -------------------------------- ### Use SecretsSettingsSource Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/settings_sources.md Example of configuring settings to load from a directory of secret files. ```python from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict(secrets_dir='/run/secrets') api_key: str # Loaded from /run/secrets/api_key password: str # Loaded from /run/secrets/password ``` -------------------------------- ### Example Pyproject.toml Structure Source: https://github.com/pydantic/pydantic-settings/blob/main/docs/index.md A sample pyproject.toml file structure compatible with the provided settings classes. ```toml field = "root" [tool.pydantic-settings] field = "default-table" [tool.some-table] field = "some-table" ``` -------------------------------- ### Configure DotenvType in Settings Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/types.md Example of providing a sequence of paths to the env_file configuration. ```python from pathlib import Path from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict( env_file=[Path('.env'), Path('.env.local')] ) ``` -------------------------------- ### Configure Settings with SettingsConfigDict Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/types.md Example of applying SettingsConfigDict to a BaseSettings subclass to define environment variable behavior. ```python from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict( env_prefix='APP_', env_file='.env', case_sensitive=False, env_nested_delimiter='__', ) database_url: str api_key: str ``` -------------------------------- ### Sample TOML files for merging Source: https://github.com/pydantic/pydantic-settings/blob/main/docs/index.md Example files demonstrating shallow merging behavior. ```toml # config.default.toml hello = "World" [nested] foo = 1 bar = 2 ``` ```toml # config.custom.toml [nested] foo = 3 ``` ```toml hello = "world" [nested] foo = 3 ``` -------------------------------- ### Implement AWSSecretsManagerSettingsSource Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/settings_sources.md Example showing how to integrate AWS Secrets Manager into a Pydantic settings class. ```python from pydantic_settings import BaseSettings, AWSSecretsManagerSettingsSource class Settings(BaseSettings): api_key: str @classmethod def settings_customise_sources(cls, ...): return ( AWSSecretsManagerSettingsSource(settings_cls), # ... other sources ) ``` -------------------------------- ### Define Dotenv File Content Source: https://github.com/pydantic/pydantic-settings/blob/main/docs/index.md Example format for a .env file using standard environment variable syntax. ```bash # ignore comment ENVIRONMENT="production" REDIS_ADDRESS=localhost:6379 MEANING_OF_LIFE=42 MY_VAR='Hello world' ``` -------------------------------- ### Configure Settings with EnvPrefixTarget Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/types.md Example usage of env_prefix_target within a BaseSettings model configuration. ```python from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict( env_prefix='APP_', env_prefix_target='all', ) api_key: str = Field(validation_alias='api_token') # Matches: APP_API_KEY, APP_API_TOKEN (both get prefix) ``` -------------------------------- ### Secrets File Structure Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/settings_sources.md Example directory structure for secret files. ```text /etc/secrets/ ├── api_key ├── database_url └── password ``` -------------------------------- ### Usage of CliPositionalArg Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/cli_source.md Example command line usage for positional arguments. ```bash command /path/to/input command /path/to/input --output-file out.txt ``` -------------------------------- ### Customize settings sources with JSON config Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/base_settings.md Example of overriding settings_customise_sources to add a JSON configuration source with the highest priority. ```python from pydantic_settings import BaseSettings, JsonConfigSettingsSource class Settings(BaseSettings): api_key: str debug: bool = False @classmethod def settings_customise_sources( cls, settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings, ): # JSON config has highest priority, then init, env, etc. return ( JsonConfigSettingsSource(settings_cls, json_file='config.json'), init_settings, env_settings, dotenv_settings, file_secret_settings, ) # Priority: config.json > init kwargs > environment > .env > secrets settings = Settings(api_key='default') ``` -------------------------------- ### Example Secret File Content Source: https://github.com/pydantic/pydantic-settings/blob/main/docs/index.md A secret file contains only the raw value, with the filename serving as the configuration key. ```text super_secret_database_password ``` -------------------------------- ### Define environment variables for nested models Source: https://github.com/pydantic/pydantic-settings/blob/main/docs/index.md Example environment variables demonstrating JSON-encoded strings and nested structure definitions. ```bash export V0=0 export SUB_MODEL='{"v1": "json-1", "v2": "json-2"}' export SUB_MODEL__V2=nested-2 export SUB_MODEL__V3=3 export SUB_MODEL__DEEP__V4=v4 ``` -------------------------------- ### Install Google Cloud Secret Manager dependency Source: https://github.com/pydantic/pydantic-settings/blob/main/docs/index.md Install the required package to enable GCP Secret Manager support in pydantic-settings. ```bash pip install "pydantic-settings[gcp-secret-manager]" ``` -------------------------------- ### Initialize BaseSettings Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/base_settings.md Constructor signature for BaseSettings, detailing configuration parameters for environment variables, CLI parsing, and secrets management. ```python def __init__( __pydantic_self__, _case_sensitive: bool | None = None, _nested_model_default_partial_update: bool | None = None, _env_prefix: str | None = None, _env_prefix_target: EnvPrefixTarget | None = None, _env_file: DotenvType | None = ENV_FILE_SENTINEL, _env_file_encoding: str | None = None, _env_ignore_empty: bool | None = None, _env_nested_delimiter: str | None = None, _env_nested_max_split: int | None = None, _env_parse_none_str: str | None = None, _env_parse_enums: bool | None = None, _cli_prog_name: str | None = None, _cli_parse_args: bool | list[str] | tuple[str, ...] | None = None, _cli_settings_source: CliSettingsSource[Any] | None = None, _cli_parse_none_str: str | None = None, _cli_hide_none_type: bool | None = None, _cli_avoid_json: bool | None = None, _cli_enforce_required: bool | None = None, _cli_use_class_docs_for_groups: bool | None = None, _cli_show_env_vars: bool | None = None, _cli_exit_on_error: bool | None = None, _cli_prefix: str | None = None, _cli_flag_prefix_char: str | None = None, _cli_implicit_flags: bool | Literal['dual', 'toggle'] | None = None, _cli_ignore_unknown_args: bool | None = None, _cli_kebab_case: bool | Literal['all', 'no_enums'] | None = None, _cli_shortcuts: Mapping[str, str | list[str]] | None = None, _secrets_dir: PathType | None = None, _build_sources: tuple[tuple[PydanticBaseSettingsSource, ...], dict[str, Any]] | None = None, **values: Any, ) -> None ``` -------------------------------- ### Basic BaseSettings usage Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/base_settings.md Initialize settings from environment variables with default values. ```python import os from pydantic_settings import BaseSettings class DatabaseSettings(BaseSettings): host: str = 'localhost' port: int = 5432 username: str = 'admin' password: str # Load from environment variables os.environ['PASSWORD'] = 'secret123' db = DatabaseSettings() # db.password == 'secret123' ``` -------------------------------- ### BaseSettings.__init__ Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/base_settings.md Initializes a new BaseSettings instance, allowing configuration of environment variable parsing, CLI argument handling, and secret directory paths. ```APIDOC ## BaseSettings.__init__ ### Description Initializes the settings object. This constructor accepts various configuration parameters to define how settings are loaded from environment variables, CLI arguments, and other sources. ### Parameters - **_case_sensitive** (bool) - Optional - Whether environment variable matching is case-sensitive. - **_env_prefix** (str) - Optional - Prefix for environment variables. - **_env_file** (DotenvType) - Optional - Path to a .env file. - **_cli_prog_name** (str) - Optional - Program name for CLI help messages. - **_cli_parse_args** (bool | list[str] | tuple[str, ...]) - Optional - CLI arguments to parse. - **_secrets_dir** (PathType) - Optional - Directory path to load secrets from. - ****values** (Any) - Optional - Additional keyword arguments for setting values. ``` -------------------------------- ### InitSettingsSource Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/settings_sources.md Loads settings from initialization keyword arguments. ```APIDOC ## InitSettingsSource ### Description Loads settings from initialization keyword arguments (__init__(**values)). ### Parameters - **init_kwargs** (dict[str, Any]) - Required - Values passed to __init__. - **nested_model_default_partial_update** (bool | None) - Optional - Flag for partial updates. ``` -------------------------------- ### Configure Development vs Production Settings Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/README.md Demonstrates using multiple env files and prefixes to manage configuration priority between development and production environments. ```python from pathlib import Path from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict( env_file=[Path('.env'), Path('.env.local')], env_prefix='MYAPP_', ) database_url: str api_key: str debug: bool = False log_level: str = 'INFO' # .env file — defaults # API_KEY=dev-key # LOG_LEVEL=DEBUG # .env.local file — local overrides # API_KEY=my-secret-key # Environment variables (production) — highest priority # MYAPP_API_KEY=prod-secret # MYAPP_LOG_LEVEL=WARNING ``` -------------------------------- ### Deep merge result example Source: https://github.com/pydantic/pydantic-settings/blob/main/docs/index.md The resulting configuration state when deep merging is enabled. ```toml hello = "world" [nested] foo = 3 bar = 2 ``` -------------------------------- ### Define InitSettingsSource Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/settings_sources.md Constructor signature for the initialization keyword arguments settings source. ```python class InitSettingsSource(PydanticBaseSettingsSource): def __init__( self, settings_cls: type[BaseSettings], init_kwargs: dict[str, Any], nested_model_default_partial_update: bool | None = None, _init_state: InitState | None = None, ) ``` -------------------------------- ### Define basic settings Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/README.md Inherit from BaseSettings to automatically load configuration from environment variables, .env files, and defaults. ```python from pydantic_settings import BaseSettings class Settings(BaseSettings): api_key: str debug: bool = False settings = Settings() # Loads from environment, .env, and defaults ``` -------------------------------- ### Configure Pyproject.toml Settings Sources Source: https://github.com/pydantic/pydantic-settings/blob/main/docs/index.md Demonstrates how to customize settings sources to load from specific tables or the root of a pyproject.toml file. ```python from pydantic_settings import ( BaseSettings, PydanticBaseSettingsSource, PyprojectTomlConfigSettingsSource, SettingsConfigDict, ) class Settings(BaseSettings): """Example loading values from the table used by default.""" field: str @classmethod def settings_customise_sources( cls, settings_cls: type[BaseSettings], init_settings: PydanticBaseSettingsSource, env_settings: PydanticBaseSettingsSource, dotenv_settings: PydanticBaseSettingsSource, file_secret_settings: PydanticBaseSettingsSource, ) -> tuple[PydanticBaseSettingsSource, ...]: return (PyprojectTomlConfigSettingsSource(settings_cls),) class SomeTableSettings(Settings): """Example loading values from a user defined table.""" model_config = SettingsConfigDict( pyproject_toml_table_header=('tool', 'some-table') ) class RootSettings(Settings): """Example loading values from the root of a pyproject.toml file.""" model_config = SettingsConfigDict(extra='ignore', pyproject_toml_table_header=()) ``` -------------------------------- ### Trigger IncompleteFieldDefinitionWarning Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/errors.md Example of a model definition that triggers the warning due to an unresolved forward reference. ```python from __future__ import annotations from pydantic_settings import BaseSettings class Settings(BaseSettings): # Forward reference: 'Database' is not yet defined db: Database # IncompleteFieldDefinitionWarning class Config: # This warning helps catch issues early pass class Database: host: str port: int ``` -------------------------------- ### Print and Format CLI Help Source: https://github.com/pydantic/pydantic-settings/blob/main/docs/index.md Access help information for settings classes or instances using print_help and format_help methods. ```python from pydantic_settings import BaseSettings, CliApp class Settings(BaseSettings, cli_prog_name='example'): def cli_cmd(self) -> None: # Will print help for the current command or subcommand instance. CliApp.print_help(self) # Will return formatted help for the current command or subcommand instance. CliApp.format_help(self) CliApp.run(Settings, cli_args=[]) """ usage: example [-h] options: -h, --help show this help message and exit """ # You can also print or format help on the class itself. print(CliApp.format_help(Settings)) """ usage: example [-h] options: -h, --help show this help message and exit """ ``` -------------------------------- ### Discover and Explicitly Path Pyproject.toml Source: https://github.com/pydantic/pydantic-settings/blob/main/docs/index.md Shows how to configure settings to search parent directories or use an absolute file path for the configuration file. ```python from pathlib import Path from pydantic_settings import ( BaseSettings, PydanticBaseSettingsSource, PyprojectTomlConfigSettingsSource, SettingsConfigDict, ) class DiscoverSettings(BaseSettings): """Example of discovering a pyproject.toml in parent directories in not in `Path.cwd()`.""" model_config = SettingsConfigDict(pyproject_toml_depth=2) @classmethod def settings_customise_sources( cls, settings_cls: type[BaseSettings], init_settings: PydanticBaseSettingsSource, env_settings: PydanticBaseSettingsSource, dotenv_settings: PydanticBaseSettingsSource, file_secret_settings: PydanticBaseSettingsSource, ) -> tuple[PydanticBaseSettingsSource, ...]: return (PyprojectTomlConfigSettingsSource(settings_cls),) class ExplicitFilePathSettings(BaseSettings): """Example of explicitly providing the path to the file to load.""" field: str @classmethod def settings_customise_sources( cls, settings_cls: type[BaseSettings], init_settings: PydanticBaseSettingsSource, env_settings: PydanticBaseSettingsSource, dotenv_settings: PydanticBaseSettingsSource, file_secret_settings: PydanticBaseSettingsSource, ) -> tuple[PydanticBaseSettingsSource, ...]: return ( PyprojectTomlConfigSettingsSource( settings_cls, Path('~/.config').resolve() / 'pyproject.toml' ), ) ``` -------------------------------- ### Load settings from .env file Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/base_settings.md Specify a path to a .env file for loading configuration values. ```python from pathlib import Path from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict( env_file=Path(__file__).parent / '.env' ) database_url: str api_key: str ``` -------------------------------- ### Configure Azure Key Vault as a settings source Source: https://github.com/pydantic/pydantic-settings/blob/main/docs/index.md Demonstrates how to implement settings_customise_sources to include AzureKeyVaultSettingsSource. Requires the AZURE_KEY_VAULT_URL environment variable and appropriate Azure credentials. ```python import os from azure.identity import DefaultAzureCredential from pydantic import BaseModel from pydantic_settings import ( AzureKeyVaultSettingsSource, BaseSettings, PydanticBaseSettingsSource, ) class SubModel(BaseModel): a: str class AzureKeyVaultSettings(BaseSettings): foo: str bar: int sub: SubModel @classmethod def settings_customise_sources( cls, settings_cls: type[BaseSettings], init_settings: PydanticBaseSettingsSource, env_settings: PydanticBaseSettingsSource, dotenv_settings: PydanticBaseSettingsSource, file_secret_settings: PydanticBaseSettingsSource, ) -> tuple[PydanticBaseSettingsSource, ...]: az_key_vault_settings = AzureKeyVaultSettingsSource( settings_cls, os.environ['AZURE_KEY_VAULT_URL'], DefaultAzureCredential(), ) return ( init_settings, env_settings, dotenv_settings, file_secret_settings, az_key_vault_settings, ) ``` -------------------------------- ### Configure TOML settings source Source: https://github.com/pydantic/pydantic-settings/blob/main/docs/index.md Demonstrates how to use TomlConfigSettingsSource by overriding settings_customise_sources in a BaseSettings class. ```python from pydantic import BaseModel from pydantic_settings import ( BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict, TomlConfigSettingsSource, ) class Nested(BaseModel): nested_field: str class Settings(BaseSettings): foobar: str nested: Nested model_config = SettingsConfigDict(toml_file='config.toml') @classmethod def settings_customise_sources( cls, settings_cls: type[BaseSettings], init_settings: PydanticBaseSettingsSource, env_settings: PydanticBaseSettingsSource, dotenv_settings: PydanticBaseSettingsSource, file_secret_settings: PydanticBaseSettingsSource, ) -> tuple[PydanticBaseSettingsSource, ...]: return (TomlConfigSettingsSource(settings_cls),) ``` -------------------------------- ### Define DotEnvSettingsSource Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/settings_sources.md Constructor signature for the .env file settings source. ```python class DotEnvSettingsSource(PydanticBaseEnvSettingsSource): def __init__( self, settings_cls: type[BaseSettings], env_file: DotenvType | None = None, env_file_encoding: str | None = None, case_sensitive: bool | None = None, env_prefix: str | None = None, env_prefix_target: EnvPrefixTarget | None = None, env_nested_delimiter: str | None = None, env_nested_max_split: int | None = None, env_ignore_empty: bool | None = None, env_parse_none_str: str | None = None, env_parse_enums: bool | None = None, _init_state: InitState | None = None, ) ``` -------------------------------- ### Define PyprojectTomlConfigSettingsSource Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/settings_sources.md Constructor signature for loading settings from pyproject.toml files. ```python class PyprojectTomlConfigSettingsSource(ConfigFileSourceMixin): def __init__( self, settings_cls: type[BaseSettings], pyproject_toml_depth: int = 2, pyproject_toml_table_header: tuple[str, ...] = (), ) ``` -------------------------------- ### Generate CLI Help Output Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/cli_app.md Displays the automatically generated help message for a Pydantic settings model. ```bash $ python main.py --help usage: main.py [-h] [--name NAME] [--count COUNT] options: -h, --help show this help message and exit --name NAME (default: 'test') --count COUNT (default: 1) ``` -------------------------------- ### EnvSettingsSource Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/settings_sources.md Loads settings from environment variables (os.environ). ```APIDOC ## EnvSettingsSource ### Description Loads settings from environment variables (os.environ). ### Parameters - **case_sensitive** (bool | None) - Optional - Match variable names case-sensitively. - **env_prefix** (str | None) - Optional - Prefix for variable names (e.g., 'APP_'). - **env_prefix_target** ('variable' | 'alias' | 'all') - Optional - Apply prefix to field names, aliases, or both. - **env_nested_delimiter** (str | None) - Optional - Delimiter for nested models (e.g., '__'). - **env_nested_max_split** (int | None) - Optional - Max nesting depth. - **env_ignore_empty** (bool | None) - Optional - Ignore empty string values. - **env_parse_none_str** (str | None) - Optional - String to parse as None (e.g., 'null'). - **env_parse_enums** (bool | None) - Optional - Parse enum names to values. ``` -------------------------------- ### Configure environment variable prefix Source: https://github.com/pydantic/pydantic-settings/blob/main/docs/index.md Shows how to set a prefix for all environment variables using the env_prefix configuration. ```python from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict(env_prefix='my_prefix_') auth_key: str = 'xxx' # will be read from `my_prefix_auth_key` ``` -------------------------------- ### Load settings from .env files Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/README.md Specify an env_file path in SettingsConfigDict to load configuration from a local file. ```python from pathlib import Path from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict( env_file=Path('.env'), env_file_encoding='utf-8', ) api_key: str database_url: str ``` ```text API_KEY=secret123 DATABASE_URL=postgresql://localhost:5432/mydb ``` -------------------------------- ### CliApp.run Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/cli_app.md Executes the CLI application based on a BaseSettings model. ```APIDOC ## CliApp.run(model, cli_args=None) ### Description Runs the CLI application defined by the provided Pydantic model. It parses command-line arguments and executes the corresponding logic. ### Parameters - **model** (BaseSettings) - Required - The Pydantic model class defining the CLI structure. - **cli_args** (list) - Optional - A list of strings representing command-line arguments. If not provided, defaults to sys.argv[1:]. ``` -------------------------------- ### DotEnvSettingsSource Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/settings_sources.md Loads settings from .env files. ```APIDOC ## DotEnvSettingsSource ### Description Loads settings from .env files. ### Parameters - **env_file** (Path | str | Sequence[Path | str] | None) - Optional - Path(s) to .env file(s). - **env_file_encoding** (str | None) - Optional - File encoding (e.g., 'utf-8'). ``` -------------------------------- ### Handle SettingsError during initialization Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/errors.md Demonstrates catching SettingsError and general exceptions when initializing a BaseSettings model with missing required fields. ```python from pydantic_settings import BaseSettings, SettingsError class Settings(BaseSettings): api_key: str try: settings = Settings() # api_key is required except SettingsError as e: print(f'Settings error: {e}') except Exception as e: # Also catches ValidationError from Pydantic print(f'Validation error: {e}') ``` -------------------------------- ### Define EnvSettingsSource Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/settings_sources.md Constructor signature for the environment variable settings source. ```python class EnvSettingsSource(PydanticBaseEnvSettingsSource): def __init__( self, settings_cls: type[BaseSettings], case_sensitive: bool | None = None, env_prefix: str | None = None, env_prefix_target: EnvPrefixTarget | None = None, env_nested_delimiter: str | None = None, env_nested_max_split: int | None = None, env_ignore_empty: bool | None = None, env_parse_none_str: str | None = None, env_parse_enums: bool | None = None, _init_state: InitState | None = None, ) ``` -------------------------------- ### Configure multiple TOML files Source: https://github.com/pydantic/pydantic-settings/blob/main/docs/index.md Shows how to provide a list of paths to the toml_file configuration for merging multiple files. ```python from pydantic import BaseModel from pydantic_settings import ( BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict, TomlConfigSettingsSource, ) class Nested(BaseModel): foo: int bar: int = 0 class Settings(BaseSettings): hello: str nested: Nested model_config = SettingsConfigDict( toml_file=['config.default.toml', 'config.custom.toml'] ) @classmethod def settings_customise_sources( cls, settings_cls: type[BaseSettings], init_settings: PydanticBaseSettingsSource, env_settings: PydanticBaseSettingsSource, dotenv_settings: PydanticBaseSettingsSource, file_secret_settings: PydanticBaseSettingsSource, ) -> tuple[PydanticBaseSettingsSource, ...]: return (TomlConfigSettingsSource(settings_cls),) ``` -------------------------------- ### Implement SecretVersion in Settings Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/types.md Demonstrates usage of SecretVersion within a custom settings source configuration. ```python from pydantic_settings import BaseSettings, AWSSecretsManagerSettingsSource, SecretVersion class Settings(BaseSettings): @classmethod def settings_customise_sources(cls, ...): # Load specific version of a secret aws_source = AWSSecretsManagerSettingsSource( cls, # Implementation would support version selection ) return (aws_source, ...) ``` -------------------------------- ### Implement CliSubCommand Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/cli_source.md Demonstrates using CliSubCommand to handle nested command logic. ```python from typing import Union from pydantic import BaseModel from pydantic_settings import BaseSettings, CliApp, CliSubCommand class CreateCmd(BaseModel): name: str def cli_cmd(self) -> None: print(f'Creating {self.name}') class Settings(BaseSettings): cmd: CliSubCommand[Union[CreateCmd, None]] = None def cli_cmd(self) -> None: if self.cmd: CliApp.run_subcommand(self) if __name__ == '__main__': CliApp.run(Settings, cli_args=['CreateCmd', '--name', 'item']) ``` -------------------------------- ### Implement a complete CLI application Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/cli_source.md Use CliSubCommand and CliPositionalArg to build complex CLI tools with subcommands and positional arguments. ```python from typing import Union from pydantic import BaseModel, Field from pydantic_settings import ( BaseSettings, CliApp, CliImplicitFlag, CliPositionalArg, CliSubCommand, SettingsConfigDict, ) class CreateArgs(BaseModel): name: CliPositionalArg[str] force: bool = False def cli_cmd(self) -> None: print(f'Creating {self.name} (force={self.force})') class DeleteArgs(BaseModel): id: int def cli_cmd(self) -> None: print(f'Deleting {self.id}') class App(BaseSettings): model_config = SettingsConfigDict( cli_prog_name='myapp', cli_implicit_flags=True, cli_kebab_case=True, cli_enforce_required=True, ) verbose: CliImplicitFlag[bool] = False command: CliSubCommand[Union[CreateArgs, DeleteArgs, None]] = None def cli_cmd(self) -> None: if self.verbose: print('Verbose mode enabled') if self.command: CliApp.run_subcommand(self) if __name__ == '__main__': CliApp.run(App) # Usage: # python app.py --verbose create MyItem # python app.py delete 123 # python app.py --help ``` -------------------------------- ### Configure Docker Environment Settings Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/README.md Shows how to integrate container-specific environment files and Docker secrets directory paths into a settings model. ```python from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict( env_prefix='MYAPP_', env_file='/etc/myapp/.env', # Container config secrets_dir='/run/secrets', # Docker Secrets ) database_url: str api_key: str # From /run/secrets/api_key jwt_secret: str # From /run/secrets/jwt_secret ``` -------------------------------- ### Define YamlConfigSettingsSource Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/settings_sources.md Constructor signature for loading settings from YAML files. ```python class YamlConfigSettingsSource(ConfigFileSourceMixin): def __init__( self, settings_cls: type[BaseSettings], yaml_file: ConfigFileSourceType | None = None, yaml_file_encoding: str | None = None, yaml_config_section: str | None = None, ) ``` -------------------------------- ### Define JsonConfigSettingsSource Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/settings_sources.md Constructor signature for loading settings from JSON files. ```python class JsonConfigSettingsSource(ConfigFileSourceMixin): def __init__( self, settings_cls: type[BaseSettings], json_file: ConfigFileSourceType | None = None, json_file_encoding: str | None = None, ) ``` -------------------------------- ### Define a Settings Class Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/README.md Create a configuration schema by subclassing BaseSettings. Fields are automatically populated from environment variables or other configured sources. ```python from pydantic_settings import BaseSettings class AppSettings(BaseSettings): database_url: str api_key: str debug: bool = False ``` -------------------------------- ### Handle missing environment files Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/errors.md Demonstrates that Pydantic Settings silently skips non-existent environment files by default. ```python from pathlib import Path from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict( env_file=Path('/nonexistent/.env') ) api_key: str # If env_file doesn't exist, it's silently skipped # (doesn't raise an error by default) settings = Settings(api_key='default') ``` -------------------------------- ### Load environment variables from files Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/configuration.md Specifies paths to .env files for loading configuration. Multiple files can be provided for cascading overrides. ```python env_file: Path | str | Sequence[Path | str] | None = None ``` ```python from pathlib import Path from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict( env_file='.env' ) api_key: str # Loads from .env file in current directory ``` ```python class Settings(BaseSettings): model_config = SettingsConfigDict( env_file=['.env', '.env.local', '.env.secrets'] ) api_key: str # Files loaded in order; later files override earlier ones ``` ```text # Comments with # API_KEY=secret123 DATABASE_URL=postgresql://localhost:5432/mydb DEBUG=true ``` -------------------------------- ### Initialize CliSettingsSource Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/cli_source.md The constructor for configuring how command-line arguments are parsed and mapped to a Pydantic settings model. ```python class CliSettingsSource(PydanticBaseSettingsSource, Generic[T]): def __init__( self, settings_cls: type[BaseSettings], cli_prog_name: str | None = None, cli_parse_args: bool | list[str] | tuple[str, ...] | None = None, cli_parse_none_str: str | None = None, cli_hide_none_type: bool | None = None, cli_avoid_json: bool | None = None, cli_enforce_required: bool | None = None, cli_use_class_docs_for_groups: bool | None = None, cli_show_env_vars: bool | None = None, cli_exit_on_error: bool = True, cli_prefix: str = '', cli_flag_prefix_char: str = '-', cli_implicit_flags: bool | Literal['dual', 'toggle'] | None = None, cli_ignore_unknown_args: bool | None = None, cli_kebab_case: bool | Literal['all', 'no_enums'] | None = None, cli_shortcuts: Mapping[str, str | list[str]] | None = None, case_sensitive: bool | None = None, _env_settings_source: EnvSettingsSource | None = None, _init_state: InitState | None = None, ) ``` -------------------------------- ### Accessing resources with Traversable Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/types.md Demonstrates using importlib.resources.files to locate configuration files within a package for use with YamlConfigSettingsSource. ```python from importlib.resources import files from pydantic_settings import BaseSettings, YamlConfigSettingsSource class Settings(BaseSettings): @classmethod def settings_customise_sources(cls, ...): yaml_source = YamlConfigSettingsSource( cls, yaml_file=files('mypackage').joinpath('config.yaml') ) return (yaml_source, ...) ``` -------------------------------- ### Define Configuration with BaseSettings Source: https://github.com/pydantic/pydantic-settings/blob/main/docs/index.md Create a settings model inheriting from BaseSettings to automatically read environment variables. Use Field aliases and model_config to customize mapping and prefixes. ```python from collections.abc import Callable from typing import Any from pydantic import ( AliasChoices, AmqpDsn, BaseModel, Field, ImportString, PostgresDsn, RedisDsn, ) from pydantic_settings import BaseSettings, SettingsConfigDict class SubModel(BaseModel): foo: str = 'bar' apple: int = 1 class Settings(BaseSettings): auth_key: str = Field(validation_alias='my_auth_key') # (1)! api_key: str = Field(alias='my_api_key') # (2)! redis_dsn: RedisDsn = Field( 'redis://user:pass@localhost:6379/1', validation_alias=AliasChoices('service_redis_dsn', 'redis_url'), # (3)! ) pg_dsn: PostgresDsn = 'postgres://user:pass@localhost:5432/foobar' amqp_dsn: AmqpDsn = 'amqp://user:pass@localhost:5672/' special_function: ImportString[Callable[[Any], Any]] = 'math.cos' # (4)! # to override domains: # export my_prefix_domains='["foo.com", "bar.com"]' domains: set[str] = set() # to override more_settings: # export my_prefix_more_settings='{"foo": "x", "apple": 1}' more_settings: SubModel = SubModel() model_config = SettingsConfigDict(env_prefix='my_prefix_') # (5)! print(Settings().model_dump()) ``` -------------------------------- ### Define TomlConfigSettingsSource Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/settings_sources.md Constructor signature for loading settings from TOML files. ```python class TomlConfigSettingsSource(ConfigFileSourceMixin): def __init__( self, settings_cls: type[BaseSettings], toml_file: ConfigFileSourceType | None = None, toml_table_header: tuple[str, ...] = (), ) ``` -------------------------------- ### Display environment variables in help Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/cli_source.md Set cli_show_env_vars=True in SettingsConfigDict to include environment variable names in the generated help text. ```python from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict( env_prefix='APP_', cli_show_env_vars=True, ) api_key: str # Help text shows: --api-key APP_API_KEY (env: APP_API_KEY) ``` -------------------------------- ### Define and parse CLI subcommands Source: https://github.com/pydantic/pydantic-settings/blob/main/docs/index.md Demonstrates defining subcommands with CliSubCommand and positional arguments with CliPositionalArg, and retrieving them using get_subcommand. ```python import sys from pydantic import BaseModel from pydantic_settings import ( BaseSettings, CliPositionalArg, CliSubCommand, SettingsError, get_subcommand, ) class Init(BaseModel): directory: CliPositionalArg[str] class Clone(BaseModel): repository: CliPositionalArg[str] directory: CliPositionalArg[str] class Git(BaseSettings, cli_parse_args=True, cli_exit_on_error=False): clone: CliSubCommand[Clone] init: CliSubCommand[Init] # Run without subcommands sys.argv = ['example.py'] cmd = Git() assert cmd.model_dump() == {'clone': None, 'init': None} try: # Will raise an error since no subcommand was provided get_subcommand(cmd).model_dump() except SettingsError as err: assert str(err) == 'Error: CLI subcommand is required {clone, init}' # Will not raise an error since subcommand is not required assert get_subcommand(cmd, is_required=False) is None # Run the clone subcommand sys.argv = ['example.py', 'clone', 'repo', 'dest'] cmd = Git() assert cmd.model_dump() == { 'clone': {'repository': 'repo', 'directory': 'dest'}, 'init': None, } # Returns the subcommand model instance (in this case, 'clone') assert get_subcommand(cmd).model_dump() == { 'directory': 'dest', 'repository': 'repo', } ``` -------------------------------- ### Define custom settings sources Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/README.md Override settings_customise_sources to inject custom configuration providers like JSON files. ```python from pydantic_settings import BaseSettings, JsonConfigSettingsSource, EnvSettingsSource class Settings(BaseSettings): api_key: str @classmethod def settings_customise_sources( cls, settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings, ): return ( JsonConfigSettingsSource(settings_cls, json_file='config.json'), init_settings, env_settings, dotenv_settings, file_secret_settings, ) ``` -------------------------------- ### Project File Structure Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/README.md Visual representation of the repository layout and documentation organization. ```text output/ ├── README.md (this file) ├── api-reference/ │ ├── base_settings.md │ ├── cli_app.md │ ├── cli_source.md │ └── settings_sources.md ├── types.md ├── configuration.md └── errors.md ``` -------------------------------- ### Generate CLI help text Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/cli_source.md Help text is automatically generated using field descriptions and types defined in the Pydantic model. ```python from pydantic import Field from pydantic_settings import BaseSettings class Settings(BaseSettings): api_key: str = Field(description='API key for authentication') retries: int = Field(default=3, description='Number of retries') # --help output: # --api-key API_KEY API key for authentication (required) # --retries RETRIES Number of retries (default: 3) ``` -------------------------------- ### Implement Boolean Flags Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/cli_source.md Demonstrates different boolean flag behaviors in a settings model. ```python from pydantic_settings import BaseSettings, CliImplicitFlag, CliToggleFlag, CliDualFlag class Settings(BaseSettings): # Requires explicit: --verbose true or --verbose false verbose: CliExplicitFlag[bool] = False # Implicit: --debug or --no-debug based on default debug: CliToggleFlag[bool] = False # Always both: --strict and --no-strict strict: CliDualFlag[bool] = False # Usage: # python app.py --verbose true --debug --strict ``` -------------------------------- ### Handle Conditional Settings Sources Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/errors.md Override settings_customise_sources to conditionally include configuration files only if they exist. ```python from pydantic_settings import BaseSettings, JsonConfigSettingsSource, EnvSettingsSource class Settings(BaseSettings): api_key: str @classmethod def settings_customise_sources( cls, settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings, ): sources = [init_settings] try: sources.append(JsonConfigSettingsSource(settings_cls, json_file='config.json')) except FileNotFoundError: # config.json missing, skip it pass sources.extend([env_settings, dotenv_settings, file_secret_settings]) return tuple(sources) ``` -------------------------------- ### Configure BaseSettings with SettingsConfigDict Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/base_settings.md Define model configuration using SettingsConfigDict to control environment variable loading behavior. ```python from pydantic import ConfigDict from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict( env_file='.env', env_file_encoding='utf-8', env_prefix='APP_', case_sensitive=False, ) api_key: str debug: bool = False ``` -------------------------------- ### Run a CLI application with CliApp.run Source: https://github.com/pydantic/pydantic-settings/blob/main/docs/index.md Executes a BaseSettings model as a CLI application by providing arguments directly. The cli_cmd method is invoked after model instantiation. ```python from pydantic_settings import BaseSettings, CliApp class Settings(BaseSettings): this_foo: str def cli_cmd(self) -> None: # Print the parsed data print(self.model_dump()) #> {'this_foo': 'is such a foo'} # Update the parsed data showing cli_cmd ran self.this_foo = 'ran the foo cli cmd' s = CliApp.run(Settings, cli_args=['--this_foo', 'is such a foo']) print(s.model_dump()) #> {'this_foo': 'ran the foo cli cmd'} ``` -------------------------------- ### Instantiate Settings with Secrets Directory Source: https://github.com/pydantic/pydantic-settings/blob/main/docs/index.md Override or provide the secrets directory at runtime using the _secrets_dir keyword argument. ```python settings = Settings(_secrets_dir='/var/run') ``` -------------------------------- ### Registering a TOML settings source Source: https://github.com/pydantic/pydantic-settings/blob/main/docs/index.md Use settings_customise_sources to define custom priority for settings sources. This implementation replaces default sources with a TomlConfigSettingsSource. ```python from pydantic_settings import ( BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict, TomlConfigSettingsSource, ) class Settings(BaseSettings): field: str model_config = SettingsConfigDict( toml_file='config.toml', toml_table_header=('my-table',) ) @classmethod def settings_customise_sources( cls, settings_cls: type[BaseSettings], init_settings: PydanticBaseSettingsSource, env_settings: PydanticBaseSettingsSource, dotenv_settings: PydanticBaseSettingsSource, file_secret_settings: PydanticBaseSettingsSource, ) -> tuple[PydanticBaseSettingsSource, ...]: return (TomlConfigSettingsSource(settings_cls),) ``` ```toml # config.toml [my-table] field = "value from my-table" ``` -------------------------------- ### Configure CLI Settings Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/cli_app.md Configures CLI behavior using SettingsConfigDict within a BaseSettings model. ```python class Settings(BaseSettings): model_config = SettingsConfigDict( cli_prog_name='myapp', # Program name cli_hide_none_type=False, # Show None in help cli_avoid_json=False, # Show JSON in help cli_use_class_docs_for_groups=True, # Use docstrings cli_enforce_required=False, # Require all fields ) ``` -------------------------------- ### Implement a custom settings source Source: https://github.com/pydantic/pydantic-settings/blob/main/docs/index.md Override settings_customise_sources to inject a custom source class that handles specific field parsing logic. ```python import json import os from typing import Any from pydantic.fields import FieldInfo from pydantic_settings import ( BaseSettings, EnvSettingsSource, PydanticBaseSettingsSource, ) class MyCustomSource(EnvSettingsSource): def prepare_field_value( self, field_name: str, field: FieldInfo, value: Any, value_is_complex: bool ) -> Any: if field_name == 'numbers': return [int(x) for x in value.split(',')] return json.loads(value) class Settings(BaseSettings): numbers: list[int] @classmethod def settings_customise_sources( cls, settings_cls: type[BaseSettings], init_settings: PydanticBaseSettingsSource, env_settings: PydanticBaseSettingsSource, dotenv_settings: PydanticBaseSettingsSource, file_secret_settings: PydanticBaseSettingsSource, ) -> tuple[PydanticBaseSettingsSource, ...]: return (MyCustomSource(settings_cls),) os.environ['numbers'] = '1,2,3' print(Settings().model_dump()) #> {'numbers': [1, 2, 3]} ``` -------------------------------- ### Define AzureKeyVaultSettingsSource Source: https://github.com/pydantic/pydantic-settings/blob/main/_autodocs/api-reference/settings_sources.md Constructor signature for the Azure Key Vault settings source. ```python class AzureKeyVaultSettingsSource(ConfigFileSourceMixin): def __init__( self, settings_cls: type[BaseSettings], azure_credential: Any | None = None, vault_url: str | None = None, ) ```