# Pydantic Settings

Settings management using Pydantic with support for multiple configuration sources including environment variables, configuration files, CLI arguments, and cloud secret management services. This library provides type-safe configuration handling with automatic validation, parsing, and serialization capabilities for enterprise applications and microservices.

## Package Information

- **Package Name**: pydantic-settings
- **Language**: Python
- **Installation**: `pip install pydantic-settings`

## Core Imports

```python
from pydantic_settings import BaseSettings, SettingsConfigDict
```

For specific sources and functionality:

```python
from pydantic_settings import (
    EnvSettingsSource,
    DotEnvSettingsSource,
    JsonConfigSettingsSource,
    YamlConfigSettingsSource,
    CliSettingsSource,
    AWSSecretsManagerSettingsSource,
    AzureKeyVaultSettingsSource,
    GoogleSecretManagerSettingsSource,
    SettingsError
)
```

## Basic Usage

```python
from pydantic_settings import BaseSettings
from pydantic import Field

class AppSettings(BaseSettings):
    app_name: str = "My App"
    debug: bool = False
    database_url: str = Field(..., description="Database connection URL")
    api_key: str = Field(..., description="API key for external service")
    
    model_config = SettingsConfigDict(
        env_prefix='MYAPP_',
        env_file='.env'
    )

# Settings loaded from env vars, .env file, and init arguments
settings = AppSettings()
print(f"App: {settings.app_name}, Debug: {settings.debug}")

# Override with explicit values
settings = AppSettings(debug=True, database_url="postgresql://localhost/dev")
```

## Architecture

Pydantic Settings uses a source-based architecture where configuration values are loaded from multiple sources in priority order:

- **Settings Sources**: Pluggable sources like environment variables, files, CLI args, cloud services
- **Source Priority**: Customizable ordering via `settings_customise_sources()` method
- **Type Safety**: Full Pydantic validation with automatic type conversion and error reporting
- **Configuration Management**: Unified interface for complex configuration scenarios across environments

The library is designed for maximum flexibility in enterprise applications, supporting everything from simple environment variable loading to complex multi-source configuration with cloud secret management integration.

## Capabilities

### Core Settings Management

Central BaseSettings class and configuration management providing the foundation for all settings functionality including source customization, validation, and type safety.

```python { .api }
class BaseSettings:
    def __init__(self, **kwargs): ...
    @classmethod
    def settings_customise_sources(cls, settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings) -> tuple: ...

class SettingsConfigDict:
    case_sensitive: bool
    env_prefix: str
    env_file: str | None
    cli_parse_args: bool | list[str] | None
    secrets_dir: str | None
```

[Core Settings](./core-settings.md)

### Environment and File Sources

Load configuration from environment variables, .env files, and various configuration file formats including JSON, YAML, TOML, and Docker/Kubernetes secrets.

```python { .api }
class EnvSettingsSource: ...
class DotEnvSettingsSource: ...
class JsonConfigSettingsSource: ...
class YamlConfigSettingsSource: ...
class TomlConfigSettingsSource: ...
class SecretsSettingsSource: ...
```

[Environment and File Sources](./env-file-sources.md)

### Command Line Interface

CLI argument parsing and settings generation with support for subcommands, flags, positional arguments, and running Pydantic models as CLI applications.

```python { .api }
class CliSettingsSource: ...
class CliApp:
    @staticmethod
    def run(model_cls, cli_args=None, **kwargs): ...
    @staticmethod  
    def run_subcommand(model, **kwargs): ...

# CLI annotations
CliSubCommand = Annotated[Union[T, None], _CliSubCommand]
CliPositionalArg = Annotated[T, _CliPositionalArg]
CliImplicitFlag = Annotated[bool, _CliImplicitFlag]
CliExplicitFlag = Annotated[bool, _CliExplicitFlag]
```

[Command Line Interface](./cli.md)

### Cloud Secret Management

Integration with major cloud providers' secret management services including AWS Secrets Manager, Azure Key Vault, and Google Secret Manager.

```python { .api }
class AWSSecretsManagerSettingsSource: ...
class AzureKeyVaultSettingsSource: ...
class GoogleSecretManagerSettingsSource: ...
```

[Cloud Secret Management](./cloud-secrets.md)

## Types

```python { .api }
class SettingsError(ValueError):
    """Base exception for settings-related errors."""

# Type aliases and definitions
PathType = Union[Path, str, Sequence[Union[Path, str]]]
DotenvType = Union[Path, str, Sequence[Union[Path, str]]]
PydanticModel = TypeVar('PydanticModel', bound=Union[PydanticDataclass, BaseModel])
EnvNoneType = str  # Special string type for environment None values

# Base Settings Source Classes
class PydanticBaseSettingsSource:
    """Abstract base class for all settings sources."""
    def __init__(self, settings_cls: type[BaseSettings]): ...
    def __call__(self) -> dict[str, Any]: ...
    def __repr__(self) -> str: ...

class PydanticBaseEnvSettingsSource(PydanticBaseSettingsSource):
    """Base class for environment-based settings sources."""
    def __init__(
        self,
        settings_cls: type[BaseSettings],
        case_sensitive: bool | None = None,
        env_prefix: str | None = None,
    ): ...

class DefaultSettingsSource(PydanticBaseSettingsSource):
    """Source for default field values."""
    def __init__(
        self,
        settings_cls: type[BaseSettings],
        nested_model_default_partial_update: bool | None = None,
    ): ...

class InitSettingsSource(PydanticBaseSettingsSource):
    """Source for initialization arguments."""
    def __init__(
        self,
        settings_cls: type[BaseSettings],
        init_kwargs: dict[str, Any],
        nested_model_default_partial_update: bool | None = None,
    ): ...

class ConfigFileSourceMixin:
    """Mixin for configuration file sources."""
    def __init__(self, **kwargs): ...

# Decoding control annotations
class NoDecode:
    """Annotation to prevent decoding of a field value."""

class ForceDecode:
    """Annotation to force decoding of a field value."""

# Constants  
DEFAULT_PATH: PathType = Path('')
ENV_FILE_SENTINEL: DotenvType = Path('')
CLI_SUPPRESS: str  # From argparse.SUPPRESS

# Utility Functions
def get_subcommand(model, is_required=True, cli_exit_on_error=None) -> Optional[PydanticModel]: ...
def read_env_file(file_path, *, encoding=None, case_sensitive=False, ignore_empty=False, parse_none_str=None) -> Mapping[str, str | None]:
    """
    Read and parse environment files.
    
    Note: This function is deprecated and will be removed in the next version.
    Use DotEnvSettingsSource._static_read_env_file if needed.
    """

# Version
__version__: str = "2.10.1"
```