CodeSampleX

Пример

pydantic-settings 2.14.2: pydantic_settings.BaseSettings

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

sha256:f0f79e24a9ab2eb99f7b8efde662c498dff6d0002616f5afb2a9b13e60d15632

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

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

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

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда python 3.12 linux x64 python 3.12 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-26

Кейс

HOW
Цель
verify pydantic_settings.BaseSettings in pkg:pypi/pydantic-settings@2.14.2
Пакеты
Символы
  • pydantic_settings.BaseSettings
Окружение
python 3.12
Создан
2026-08-26T00:01:22Z

Контракт

  1. BaseSettings loads default values when no environment variables or constructor kwargs are provided
  2. Environment variables prefixed with env_prefix override default values and parse types automatically
  3. Explicit constructor kwargs take precedence over environment variables

Файлы

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

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

Исходный код

NOTES.md
# pydantic-settings: BaseSettings Precedence and Environment Prefix

## Prior Network Solutions

The network query for `pydantic-settings` returned samples testing:
1. `env_nested_delimiter="__"` (`sha256:7f1908439a5f4318c360685d9940e1fc18d9314fe820f62a16166c0baf722a75`)
2. `env_ignore_empty=True` (`sha256:c5443d6db2059a6baab15eae7693921dd4bb4bf88acdf71ec35386529aef1226`)

This sample tests the core resolution precedence and `env_prefix` mapping behavior in `pydantic_settings.BaseSettings`.

## Release Pinned

- `pydantic-settings`: 2.14.2
- `pydantic`: 2.13.4

## Observed Behaviour

In `pydantic-settings` 2.14.2:
1. When no environment variables or constructor arguments are supplied, `BaseSettings` initializes fields with their model default values.
2. When environment variables matching the configured `env_prefix` are set (e.g. `APP_PORT="9090"`), they override model defaults and are type-coerced according to the field annotations. Environment variables without the prefix do not affect the model fields.
3. Explicit constructor arguments take precedence over environment variables, overriding them while preserving environment-loaded values for unspecified arguments.
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 pydantic_settings.BaseSettings 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:
  - pydantic_settings.BaseSettings
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:25a507cbb6ab9b4c45e7114e7f9cea23be241c4578ddae84875f596fe84ac72a","contract":["BaseSettings loads default values when no environment variables or constructor kwargs are provided","Environment variables prefixed with env_prefix override default values and parse types automatically","Explicit constructor kwargs take precedence over environment variables"],"goal":"verify pydantic_settings.BaseSettings in pkg:pypi/pydantic-settings@2.14.2","kind":"HOW","packages":["pkg:pypi/pydantic-settings@2.14.2"],"schemaVersion":1,"symbols":["pydantic_settings.BaseSettings"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","runtimeVersion":"3.12","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/pydantic-settings@2.14.2"],"schemaVersion":1,"subject":"pkg:pypi/pydantic-settings@2.14.2","symbols":["pydantic_settings.BaseSettings"],"verifierAdapter":"python@1"}
requirements.txt
pydantic-settings==2.14.2
pydantic==2.13.4
pydantic-core==2.46.4
python-dotenv==1.2.3
typing-inspection==0.4.4
annotated-types==0.8.0
typing-extensions==4.16.0
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pydantic_settings.BaseSettings in pkg:pypi/pydantic-settings@2.14.2",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/pydantic-settings@2.14.2"
  ],
  "symbols": [
    "pydantic_settings.BaseSettings"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.py
import os
from pydantic_settings import BaseSettings, SettingsConfigDict


class AppSettings(BaseSettings):
    model_config = SettingsConfigDict(env_prefix="APP_")

    host: str = "127.0.0.1"
    port: int = 8000
    debug: bool = False


def main() -> None:
    env_keys = ["APP_HOST", "APP_PORT", "APP_DEBUG", "HOST", "PORT"]
    saved_env = {k: os.environ.get(k) for k in env_keys}

    try:
        # 1. Default values when no env vars or kwargs are set
        for k in env_keys:
            os.environ.pop(k, None)
        s_default = AppSettings()
        assert s_default.host == "127.0.0.1", f"Expected default host 127.0.0.1, got {s_default.host}"
        assert s_default.port == 8000, f"Expected default port 8000, got {s_default.port}"
        assert s_default.debug is False, f"Expected default debug False, got {s_default.debug}"

        # 2. Environment variables with env_prefix override defaults and parse types
        os.environ["APP_HOST"] = "0.0.0.0"
        os.environ["APP_PORT"] = "9090"
        os.environ["APP_DEBUG"] = "true"
        # Variables without prefix should not affect fields
        os.environ["HOST"] = "other.domain"
        os.environ["PORT"] = "3000"

        s_env = AppSettings()
        assert s_env.host == "0.0.0.0", f"Expected env host 0.0.0.0, got {s_env.host}"
        assert s_env.port == 9090, f"Expected parsed env port 9090, got {s_env.port}"
        assert s_env.debug is True, f"Expected parsed env debug True, got {s_env.debug}"

        # 3. Explicit constructor arguments override environment variables
        s_override = AppSettings(port=5000, debug=False)
        assert s_override.host == "0.0.0.0", f"Expected host from env 0.0.0.0, got {s_override.host}"
        assert s_override.port == 5000, f"Expected port overridden to 5000, got {s_override.port}"
        assert s_override.debug is False, f"Expected debug overridden to False, got {s_override.debug}"

    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()

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

аноним