CodeSampleX

Exemple

pydantic-settings 2.14.2: BaseSettings environment variable parsing with SettingsConfigDict

Échantillon vérifié pour pypi pydantic-settings 2.14.2: BaseSettings environment variable parsing with SettingsConfigDict. Le contrat s'est exécuté sur…

sha256:9a61f55667b44868a6ad1da2ae05e5c068410fcf30ddd7d252d3a7fa73da739b

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré python linux 24 · ubuntu · glibc 2.39 x64 python python pip

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-20

Cas

HOW
Objectif
BaseSettings environment variable parsing with SettingsConfigDict
Paquets
Symboles
  • BaseSettings
Environnement
python
Créé
2026-08-20T02:42:39Z

Contrat

  1. BaseSettings loads configuration fields from prefixed environment variables
  2. BaseSettings applies default field values and type conversions when environment variables are omitted

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code source

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: BaseSettings environment variable parsing with SettingsConfigDict
Kind: HOW

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

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:453d62c79ca483f013310489e16953c0a132cfd1118a66db4ff3a15199fbdc6a","contract":["BaseSettings loads configuration fields from prefixed environment variables","BaseSettings applies default field values and type conversions when environment variables are omitted"],"goal":"BaseSettings environment variable parsing with SettingsConfigDict","kind":"HOW","packages":["pkg:pypi/pydantic-settings@2.14.2"],"schemaVersion":1,"symbols":["BaseSettings"]},"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":["BaseSettings"],"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
typing-extensions==4.16.0
typing-inspection==0.4.4
sample.py
"""Sample demonstrating environment variable parsing using Pydantic Settings."""

from typing import List
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict


class DatabaseSettings(BaseSettings):
    """Database connection and pool configuration."""

    model_config = SettingsConfigDict(
        env_prefix="DB_",
        case_sensitive=False,
    )

    host: str = "localhost"
    port: int = 5432
    name: str = "app_db"
    pool_size: int = Field(default=10, ge=1, le=100)


class AppSettings(BaseSettings):
    """Application settings populated from environment variables."""

    model_config = SettingsConfigDict(
        env_prefix="APP_",
        case_sensitive=False,
    )

    app_name: str = "ExampleService"
    environment: str = "development"
    debug: bool = False
    allowed_hosts: List[str] = Field(default_factory=lambda: ["localhost", "127.0.0.1"])


def load_application_settings() -> AppSettings:
    """Instantiate and return the current AppSettings."""
    return AppSettings()


def load_database_settings() -> DatabaseSettings:
    """Instantiate and return the current DatabaseSettings."""
    return DatabaseSettings()


if __name__ == "__main__":
    app_cfg = load_application_settings()
    db_cfg = load_database_settings()
    print(f"Loaded {app_cfg.app_name} (env={app_cfg.environment}, debug={app_cfg.debug})")
    print(f"Database target: {db_cfg.host}:{db_cfg.port}/{db_cfg.name}")
spec.json
{
  "schemaVersion": 1,
  "goal": "BaseSettings environment variable parsing with SettingsConfigDict",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/pydantic-settings@2.14.2"
  ],
  "symbols": [
    "BaseSettings"
  ]
}
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, DatabaseSettings, load_application_settings, load_database_settings


def test_environment_variable_override():
    # Assertion 1: BaseSettings loads configuration fields from prefixed environment variables
    os.environ["APP_APP_NAME"] = "CustomService"
    os.environ["APP_ENVIRONMENT"] = "production"
    os.environ["APP_DEBUG"] = "true"
    os.environ["APP_ALLOWED_HOSTS"] = '["api.example.com", "admin.example.com"]'

    os.environ["DB_HOST"] = "db.example.com"
    os.environ["DB_PORT"] = "5433"
    os.environ["DB_NAME"] = "custom_db"
    os.environ["DB_POOL_SIZE"] = "25"

    try:
        app_cfg = load_application_settings()
        assert app_cfg.app_name == "CustomService"
        assert app_cfg.environment == "production"
        assert app_cfg.debug is True
        assert app_cfg.allowed_hosts == ["api.example.com", "admin.example.com"]

        db_cfg = load_database_settings()
        assert db_cfg.host == "db.example.com"
        assert db_cfg.port == 5433
        assert db_cfg.name == "custom_db"
        assert db_cfg.pool_size == 25
    finally:
        # Clean up modified environment variables
        for key in [
            "APP_APP_NAME",
            "APP_ENVIRONMENT",
            "APP_DEBUG",
            "APP_ALLOWED_HOSTS",
            "DB_HOST",
            "DB_PORT",
            "DB_NAME",
            "DB_POOL_SIZE",
        ]:
            os.environ.pop(key, None)


def test_default_fallbacks_and_types():
    # Assertion 2: BaseSettings applies default field values and type conversions when environment variables are omitted
    for key in [
        "APP_APP_NAME",
        "APP_ENVIRONMENT",
        "APP_DEBUG",
        "APP_ALLOWED_HOSTS",
        "DB_HOST",
        "DB_PORT",
        "DB_NAME",
        "DB_POOL_SIZE",
    ]:
        os.environ.pop(key, None)

    app_cfg = load_application_settings()
    assert app_cfg.app_name == "ExampleService"
    assert app_cfg.environment == "development"
    assert app_cfg.debug is False
    assert app_cfg.allowed_hosts == ["localhost", "127.0.0.1"]

    db_cfg = load_database_settings()
    assert db_cfg.host == "localhost"
    assert db_cfg.port == 5432
    assert db_cfg.name == "app_db"
    assert db_cfg.pool_size == 10


def main():
    test_environment_variable_override()
    test_default_fallbacks_and_types()
    print("Contract verification passed.")


if __name__ == "__main__":
    main()

Seeder d'origine

anonyme