# Core Settings Management

Central BaseSettings class and configuration management providing the foundation for all settings functionality. This module handles source customization, validation, type safety, and the core configuration loading mechanism.

## Capabilities

### BaseSettings Class

The main base class for creating settings models with support for multiple configuration sources, automatic validation, and extensive customization options.

```python { .api }
class BaseSettings(BaseModel):
    """
    Base class for settings, allowing values to be overridden by multiple sources.
    
    All configuration options can be set via model_config or constructor parameters.
    """
    
    def __init__(
        self,
        _case_sensitive: bool | None = None,
        _nested_model_default_partial_update: bool | None = None,
        _env_prefix: str | None = None,
        _env_file: DotenvType | None = None,
        _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 | 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_exit_on_error: bool | None = None,
        _cli_prefix: str | None = None,
        _cli_flag_prefix_char: str | None = None,
        _cli_implicit_flags: bool | None = None,
        _cli_ignore_unknown_args: bool | None = None,
        _cli_kebab_case: bool | None = None,
        _cli_shortcuts: Mapping[str, str | list[str]] | None = None,
        _secrets_dir: PathType | None = None,
        **values: Any,
    ) -> None:
        """
        Initialize settings with configuration options.
        
        Parameters:
        - _case_sensitive: Whether env/CLI variables should be read case-sensitively
        - _nested_model_default_partial_update: Allow partial updates on nested models
        - _env_prefix: Prefix for all environment variables
        - _env_file: Env file(s) to load from
        - _env_file_encoding: Encoding for env files
        - _env_ignore_empty: Ignore empty environment variables
        - _env_nested_delimiter: Delimiter for nested env values
        - _env_nested_max_split: Maximum nesting for env values
        - _env_parse_none_str: String to parse as None
        - _env_parse_enums: Parse enum field names to values
        - _cli_prog_name: CLI program name for help text
        - _cli_parse_args: CLI arguments to parse
        - _cli_settings_source: Custom CLI settings source
        - _cli_parse_none_str: CLI string to parse as None
        - _cli_hide_none_type: Hide None in CLI help
        - _cli_avoid_json: Avoid JSON in CLI help
        - _cli_enforce_required: Enforce required fields in CLI
        - _cli_use_class_docs_for_groups: Use class docs in CLI groups
        - _cli_exit_on_error: Exit on CLI parsing errors
        - _cli_prefix: CLI arguments prefix
        - _cli_flag_prefix_char: CLI flag prefix character
        - _cli_implicit_flags: Convert bool fields to CLI flags
        - _cli_ignore_unknown_args: Ignore unknown CLI args
        - _cli_kebab_case: Use kebab-case for CLI args
        - _cli_shortcuts: CLI argument shortcuts mapping
        - _secrets_dir: Directory for secret files
        - **values: Additional field values
        """
    
    @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, ...]:
        """
        Define the sources and their order for loading settings values.
        
        Parameters:
        - settings_cls: The Settings class
        - init_settings: The InitSettingsSource instance
        - env_settings: The EnvSettingsSource instance
        - dotenv_settings: The DotEnvSettingsSource instance
        - file_secret_settings: The SecretsSettingsSource instance
        
        Returns:
        Tuple of sources in priority order
        """
```

### Settings Configuration

Configuration dictionary that defines all available settings options and their default values.

```python { .api }
class SettingsConfigDict(ConfigDict):
    """Configuration dictionary for BaseSettings with all available options."""
    
    case_sensitive: bool
    nested_model_default_partial_update: bool | None
    env_prefix: str
    env_file: DotenvType | None
    env_file_encoding: str | None
    env_ignore_empty: bool
    env_nested_delimiter: str | None
    env_nested_max_split: int | None
    env_parse_none_str: str | None
    env_parse_enums: bool | None
    cli_prog_name: str | None
    cli_parse_args: bool | list[str] | tuple[str, ...] | None
    cli_parse_none_str: str | None
    cli_hide_none_type: bool
    cli_avoid_json: bool
    cli_enforce_required: bool
    cli_use_class_docs_for_groups: bool
    cli_exit_on_error: bool
    cli_prefix: str
    cli_flag_prefix_char: str
    cli_implicit_flags: bool | None
    cli_ignore_unknown_args: bool | None
    cli_kebab_case: bool | None
    cli_shortcuts: Mapping[str, str | list[str]] | None
    secrets_dir: PathType | None
    json_file: PathType | None
    json_file_encoding: str | None
    yaml_file: PathType | None
    yaml_file_encoding: str | None
    yaml_config_section: str | None
    pyproject_toml_depth: int
    pyproject_toml_table_header: tuple[str, ...]
    toml_file: PathType | None
    enable_decoding: bool
```

### Source Base Classes

Base classes that all settings sources inherit from, providing common functionality and interfaces.

```python { .api }
class PydanticBaseSettingsSource:
    """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): ...
```

### Utility Functions

Core utility functions for settings management and source handling.

```python { .api }
def get_subcommand(
    model: PydanticModel, 
    is_required: bool = True, 
    cli_exit_on_error: bool | None = None
) -> Optional[PydanticModel]:
    """
    Get the subcommand from a model.
    
    Parameters:
    - model: The model to get the subcommand from
    - is_required: Whether a subcommand is required
    - cli_exit_on_error: Whether to exit on error
    
    Returns:
    The subcommand model if found, otherwise None
    """
```

## Usage Examples

### Basic Settings Class

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

class DatabaseSettings(BaseSettings):
    host: str = "localhost"
    port: int = 5432
    username: str = Field(..., description="Database username")
    password: str = Field(..., description="Database password")
    database: str = Field(..., description="Database name")
    
    model_config = SettingsConfigDict(
        env_prefix='DB_',
        case_sensitive=False,
        env_file='.env'
    )

# Load from environment variables like DB_HOST, DB_PORT, etc.
db_settings = DatabaseSettings()
```

### Custom Source Ordering

```python
class AppSettings(BaseSettings):
    debug: bool = False
    log_level: str = "INFO"
    
    @classmethod
    def settings_customise_sources(
        cls,
        settings_cls,
        init_settings,
        env_settings, 
        dotenv_settings,
        file_secret_settings,
    ):
        # Custom ordering: init args, secrets, env vars, .env file
        return (
            init_settings,
            file_secret_settings,
            env_settings,
            dotenv_settings,
        )

settings = AppSettings(debug=True)  # init_settings takes precedence
```

### Nested Configuration

```python
from pydantic import BaseModel

class DatabaseConfig(BaseModel):
    host: str = "localhost"
    port: int = 5432
    ssl: bool = False

class RedisConfig(BaseModel):
    host: str = "localhost"
    port: int = 6379
    db: int = 0

class AppSettings(BaseSettings):
    app_name: str = "MyApp"
    database: DatabaseConfig = DatabaseConfig()
    redis: RedisConfig = RedisConfig()
    
    model_config = SettingsConfigDict(
        env_nested_delimiter='__',
        case_sensitive=False
    )

# Environment variables: DATABASE__HOST, DATABASE__PORT, REDIS__HOST, etc.
settings = AppSettings()
```