CodeSampleX

Пример

pydantic-settings 2.14.2: settings_customise_sources

Проверенный пример — pypi pydantic-settings 2.14.2: settings_customise_sources. Контракт выполнен на python 3.12 · linux debian/x64 · docker и пройден.

sha256:c70db90f0aa4d5c85ad6c892a6d2eea932f1424492fd9f2a69eee48c52c399bd

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

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

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

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

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

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

Кейс

HOW
Цель
verify settings_customise_sources in pkg:pypi/pydantic-settings@2.14.2
Пакеты
Символы
  • settings_customise_sources
Создан
2026-09-02T09:45:26Z

Контракт

  1. settings_customise_sources reorders sources allowing env_settings to take precedence over init_settings
  2. settings_customise_sources allows injecting custom PydanticBaseSettingsSource instances to load configuration data
  3. settings_customise_sources allows omitting default sources such as env_settings to ignore environment variables

Файлы

  • PROMPT.md
  • csx.json
  • requirements.txt
  • 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: verify settings_customise_sources in pkg:pypi/pydantic-settings@2.14.2
Kind: HOW

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

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:13f7e3620a8e0f66b6b79941941cd042c415e41b569a21fa2020d7d10e82b0d6","contract":["settings_customise_sources reorders sources allowing env_settings to take precedence over init_settings","settings_customise_sources allows injecting custom PydanticBaseSettingsSource instances to load configuration data","settings_customise_sources allows omitting default sources such as env_settings to ignore environment variables"],"goal":"verify settings_customise_sources in pkg:pypi/pydantic-settings@2.14.2","kind":"HOW","packages":["pkg:pypi/pydantic-settings@2.14.2"],"schemaVersion":1,"symbols":["settings_customise_sources"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/pydantic-settings@2.14.2"],"schemaVersion":1,"subject":"pkg:pypi/pydantic-settings@2.14.2","symbols":["settings_customise_sources"],"verifierAdapter":"python@1"}
requirements.txt
pydantic-settings==2.14.2
pydantic==2.13.4
pydantic-core==2.46.4
annotated-types==0.8.0
typing-extensions==4.15.0
typing-inspection==0.4.2
python-dotenv==1.2.2
spec.json
{
  "schemaVersion": 1,
  "goal": "verify settings_customise_sources in pkg:pypi/pydantic-settings@2.14.2",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/pydantic-settings@2.14.2"
  ],
  "symbols": [
    "settings_customise_sources"
  ]
}
test/contract.py
import os
from typing import Any
from pydantic.fields import FieldInfo
from pydantic_settings import (
    BaseSettings,
    PydanticBaseSettingsSource,
    SettingsConfigDict,
)


class CustomDictSource(PydanticBaseSettingsSource):
    """Custom settings source that supplies values from an in-memory dictionary."""

    def __init__(self, settings_cls: type[BaseSettings], data: dict[str, Any]) -> None:
        super().__init__(settings_cls)
        self._data = data

    def get_field_value(
        self, field: FieldInfo, field_name: str
    ) -> tuple[Any, str, bool]:
        val = self._data.get(field_name)
        return val, field_name, False

    def __call__(self) -> dict[str, Any]:
        result: dict[str, Any] = {}
        for field_name, field in self.settings_cls.model_fields.items():
            val, key, is_complex = self.get_field_value(field, field_name)
            if val is not None:
                result[key] = val
        return result


class EnvPrioritySettings(BaseSettings):
    """Settings where env_settings takes precedence over init_settings."""

    model_config = SettingsConfigDict(env_prefix="TEST_")
    mode: str = "default_mode"

    @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 (env_settings, init_settings)


class CustomSourceSettings(BaseSettings):
    """Settings that include a custom PydanticBaseSettingsSource."""

    endpoint: str
    retries: 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, ...]:
        custom_source = CustomDictSource(
            settings_cls,
            {"endpoint": "http://localhost:8080", "retries": 5},
        )
        return (init_settings, custom_source)


class OmitEnvSettings(BaseSettings):
    """Settings that omit env_settings to ignore environment variables."""

    model_config = SettingsConfigDict(env_prefix="OMIT_")
    title: str = "default_title"

    @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 (init_settings,)


def main() -> None:
    tracked_vars = [
        "TEST_MODE",
        "OMIT_TITLE",
    ]
    saved_env = {k: os.environ.get(k) for k in tracked_vars}

    try:
        # 1. Verify env_settings precedence over init_settings
        os.environ["TEST_MODE"] = "env_override_mode"
        reordered = EnvPrioritySettings(mode="init_mode")
        assert reordered.mode == "env_override_mode", (
            f"Expected 'env_override_mode', got '{reordered.mode}'"
        )

        # 2. Verify custom PydanticBaseSettingsSource provides values
        custom_settings = CustomSourceSettings()
        assert custom_settings.endpoint == "http://localhost:8080", (
            f"Expected 'http://localhost:8080', got '{custom_settings.endpoint}'"
        )
        assert custom_settings.retries == 5, (
            f"Expected 5, got {custom_settings.retries}"
        )

        # 3. Verify init_settings still overrides custom source if placed before it
        init_override = CustomSourceSettings(retries=10)
        assert init_override.retries == 10, (
            f"Expected 10, got {init_override.retries}"
        )

        # 4. Verify omitting env_settings ignores environment variables
        os.environ["OMIT_TITLE"] = "env_title_value"
        omitted = OmitEnvSettings()
        assert omitted.title == "default_title", (
            f"Expected 'default_title', got '{omitted.title}'"
        )

    finally:
        for k, v in saved_env.items():
            if v is None:
                os.environ.pop(k, None)
            else:
                os.environ[k] = v


if __name__ == "__main__":
    main()

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

аноним