CodeSampleX

Пример

pydantic-settings 2.14.2: Load configuration from TOML files using TomlConfigSettingsSource

Проверенный пример — pypi pydantic-settings 2.14.2: Load configuration from TOML files using TomlConfigSettingsSource. Контракт выполнен на python 3.12 …

sha256:217839a42198920d4d0d18b731068271eb2dc9c3492754b030994902f23d7612

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда python linux 24 · ubuntu · glibc 2.39 x64 python python pip

Среды запусков проверки

Окружение Контракт Этапы Запуск
python 3.12 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-alpine@sha256:d09d15e60962…
2026-08-27

Кейс

HOW
Цель
Load configuration from TOML files using TomlConfigSettingsSource
Пакеты
Символы
  • TomlConfigSettingsSource
Окружение
python
Создан
2026-08-27T19:29:57Z

Контракт

  1. TomlConfigSettingsSource loads configuration values from a TOML file
  2. TomlConfigSettingsSource allows init arguments and higher-priority sources to override values from the TOML file

Файлы

  • PROMPT.md
  • csx.json
  • requirements.txt
  • sample.py
  • spec.json
  • test/contract.py

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: Load configuration from TOML files using TomlConfigSettingsSource
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/pydantic-settings@2.14.2
Demonstrate these symbols/APIs:
  - TomlConfigSettingsSource

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:7c159ae7304e320c79b09b49bdfc4cfbdbc0e36ed47aaca632dfb224d208d688","contract":["TomlConfigSettingsSource loads configuration values from a TOML file","TomlConfigSettingsSource allows init arguments and higher-priority sources to override values from the TOML file"],"goal":"Load configuration from TOML files using TomlConfigSettingsSource","kind":"HOW","packages":["pkg:pypi/pydantic-settings@2.14.2"],"schemaVersion":1,"symbols":["TomlConfigSettingsSource"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","language":"python","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/pydantic-settings@2.14.2"],"schemaVersion":1,"symbols":["TomlConfigSettingsSource"],"verifierAdapter":"python@1"}
requirements.txt
annotated-types==0.8.0
pydantic==2.13.4
pydantic-core==2.46.4
pydantic-settings==2.14.2
python-dotenv==1.2.3
tomli==2.2.1
typing-extensions==4.16.0
typing-inspection==0.4.4
sample.py
"""Sample demonstrating TOML configuration loading with TomlConfigSettingsSource in Pydantic Settings."""

from typing import Tuple, Type
from pydantic import BaseModel, Field
from pydantic_settings import (
    BaseSettings,
    PydanticBaseSettingsSource,
    SettingsConfigDict,
    TomlConfigSettingsSource,
)


class DatabaseConfig(BaseModel):
    """Database connection configuration."""

    host: str = "localhost"
    port: int = 5432
    database_name: str = "default_db"


class AppSettings(BaseSettings):
    """Application settings loaded from TOML file with fallback defaults and source customization."""

    model_config = SettingsConfigDict(
        toml_file="config.toml",
        toml_file_encoding="utf-8",
    )

    app_name: str = "DefaultApp"
    environment: str = "development"
    debug: bool = False
    database: DatabaseConfig = Field(default_factory=DatabaseConfig)

    @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, ...]:
        """Customise settings sources to include TomlConfigSettingsSource."""
        return (
            init_settings,
            TomlConfigSettingsSource(settings_cls),
            env_settings,
            dotenv_settings,
            file_secret_settings,
        )


def load_application_settings(**kwargs) -> AppSettings:
    """Instantiate and return AppSettings."""
    return AppSettings(**kwargs)


if __name__ == "__main__":
    settings = load_application_settings()
    print(f"Loaded {settings.app_name} (env={settings.environment}, debug={settings.debug})")
    print(f"Database: {settings.database.host}:{settings.database.port}/{settings.database.database_name}")
spec.json
{
  "schemaVersion": 1,
  "goal": "Load configuration from TOML files using TomlConfigSettingsSource",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/pydantic-settings@2.14.2"
  ],
  "symbols": [
    "TomlConfigSettingsSource"
  ]
}
test/contract.py
import os
import sys

# Ensure project root is on sys.path for local module imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sample import AppSettings, load_application_settings


def test_toml_config_loading():
    # Assertion 1: TomlConfigSettingsSource loads configuration values from a TOML file
    toml_content = """app_name = "SampleTomlService"
environment = "staging"
debug = true

[database]
host = "db.example.com"
port = 5433
database_name = "service_db"
"""

    config_path = "config.toml"
    with open(config_path, "w", encoding="utf-8") as f:
        f.write(toml_content)

    try:
        settings = load_application_settings()
        assert settings.app_name == "SampleTomlService"
        assert settings.environment == "staging"
        assert settings.debug is True
        assert settings.database.host == "db.example.com"
        assert settings.database.port == 5433
        assert settings.database.database_name == "service_db"
    finally:
        if os.path.exists(config_path):
            os.remove(config_path)


def test_init_arg_override_precedence():
    # Assertion 2: TomlConfigSettingsSource allows init arguments and higher-priority sources to override values from the TOML file
    toml_content = """app_name = "BaseApp"
environment = "production"
debug = false

[database]
host = "db.example.com"
port = 5432
database_name = "prod_db"
"""

    config_path = "config.toml"
    with open(config_path, "w", encoding="utf-8") as f:
        f.write(toml_content)

    try:
        settings = load_application_settings(
            app_name="OverriddenApp",
            debug=True,
        )
        assert settings.app_name == "OverriddenApp"
        assert settings.environment == "production"
        assert settings.debug is True
        assert settings.database.host == "db.example.com"
        assert settings.database.port == 5432
    finally:
        if os.path.exists(config_path):
            os.remove(config_path)


def main():
    test_toml_config_loading()
    test_init_arg_override_precedence()
    print("Contract verification passed.")


if __name__ == "__main__":
    main()

Исходный сидер

аноним