Pydantic settings review

Give me a local only review of https://github.com/br3ndonland/fastenv/pull/46. The code is mostly technically correct and passing the tests, so I don't need you to focus so much on correctness. In this review, I'd like you to focus on making this PR "code like me." I put a great deal of craftsmanship into this repo, and with the large amount of code in this PR, I'm worried that some of that craftsmanship may be lost. To understand this "craftsmanship," look at files like `fastenv/dotenv.py`, `tests/test_dotenv.py`, `fastenv/cloud/object_storage.py`, `tests/cloud/test_object_storage.py`, and the related docs. I'm interested in questions like: - Is the code concise and elegant? - Do the tests have intelligible docstrings? - Do the tests test public APIs? - Do the tests avoid overly specific test assertions? - Do the docs adequately explain this code in a friendly, informal manner?

Review of PR #46 (local only, nothing posted)

Tests pass locally (hatch run pytest tests/settings tests/test_fastapi.py: 201 passed). I compared the PR against fastenv/dotenv.py, fastenv/settings/starlette_config.py, tests/test_dotenv.py, tests/cloud/test_object_storage.py, and the existing docs. Short answer: the code is capable, but it reads like a port of pydantic-settings' internals rather than a fastenv module. The biggest craftsmanship losses are (1) every file source implemented twice, sync and async, (2) tests that assert on internals and sequence lists instead of outcomes, and (3) docs that read as a compliance statement rather than a tutorial.

Source: one async implementation, not two parallel ones

Your siblings have one I/O path. dotenv.py is async-only; StarletteConfig has a single async _load_files and the constructor wraps it with anyio.run. This PR implements file reading twice in five places: DotEnvSettingsSource._read_env_files vs load (sources 695-732), SecretsSettingsSource.__call__ vs load (sources 803-899), _ConfigFileSettingsSource._load_files vs load (providers 52-99), PyprojectTomlConfigSettingsSource.__init__ vs load (providers 171-212), and NestedSecretsSettingsSource._load_env_vars vs load (providers 298-377). Roughly a third of the two source modules is this duplication, and each pair has already drifted slightly (the sync secrets lookup goes through find_case_path, the async one inlines a different comparison).

I understand why: pydantic-settings compat requires Settings() to work inside a running loop (test_settings_inside_running_event_loop), so anyio.run is off the table. But the fix for that constraint doesn't have to be two implementations. Two options that keep one code path:

  • Make sources lazy. Nothing reads files in __init__; __call__ reads synchronously and load reads asynchronously, but both call the same _read(path_bytes) parsing step, and the only duplicated part is the one-line read. This also deletes DEFER_SETTINGS_IO entirely, because that ContextVar exists only to suppress the eager I/O the constructors currently do.
  • Or keep eager sync I/O and have load call the sync reader with anyio.to_thread.run_sync. Less pure, but it is one implementation and still non-blocking.

Either way, the isinstance(x, (str, os.PathLike)) list-normalization appears 10 times and the directory walk for secrets appears 4 times. Those want a helper the way dotenv.py has _set_dotenv_source.

Source: the load() machinery is clever where fastenv is clear

BaseSettings.load needs cls(**values) to run a custom __init__ but skip source loading. The PR achieves this with a __new__ override, a _PreparedSettings dataclass, a _PREPARED_SETTINGS ContextVar, plus the separate DEFER_SETTINGS_IO ContextVar, with the rationale spread over four comments (pydantic_settings.py 95-110, 175-210, 263-268). It took me three reads. Nothing in dotenv.py or object_storage.py needs the reader to hold this much state in their head. If the lazy-sources change above lands, one ContextVar goes away. For what remains, a single _LoadContext object with a docstring describing the lifecycle (set in load, claimed in __new__, consumed in __init__) would be far kinder than two unrelated ContextVars.

Source: module layout and imports don't match the house

  • fastenv has one module per integration: starlette_config.py, object_storage.py. This PR adds three pydantic_settings* modules that mirror upstream's sources/providers layout. "Providers" and "sources" are both settings sources; the split exists to dodge a circular import, which the PR then dodges again with a function-local import in _settings_sources (pydantic_settings.py 331). Merge the file sources into pydantic_settings_sources.py, or move the "configured file without a source" warning out of BaseSettings.
  • pydantic_settings.py uses relative imports; starlette_config.py and dotenv.py use from fastenv.utilities import ....
  • Siblings import modules (import os, import dataclasses, os.PathLike, dataclasses.dataclass). The PR mixes from os import PathLike, from pathlib import Path, from dataclasses import dataclass with import dataclasses in the same package. from enum import Enum inside _enum_value (sources 545) should be at the top.
  • Siblings use targeted inline # pyright: ignore[...]; the PR disables reportAny/reportExplicitAny file-wide in all three source modules.
  • dotenv.py and starlette_config.py log every load and error through fastenv.utilities.logger. The PR never logs. Reading a dotenv file, a secrets directory, or a TOML file should produce the same fastenv loaded ... line users already get.
  • Option resolution (config.get(name, default) if value is None else value) is written inline about 15 times in the providers; PydanticBaseEnvSettingsSource._option already exists and the providers don't use it. NestedSecretsSettingsSource.__init__ is 70 lines of this.

Source: docstrings and the public surface

ObjectStorageConfig has a paragraph docstring and reference URLs; every public function in dotenv.py is documented. Here, SettingsConfigDict declares 25 options with no documentation for any, and most public methods (get_field_value, __call__, explode_env_vars, next_field) have none. A short docstring per source class explaining what it reads and what it returns would match the house.

fastenv/__init__.py grows __all__ by 15 names, including NoDecode, ForceDecode, IncompleteFieldDefinitionWarning, InitSettingsSource, PydanticBaseSettingsSource. The root today exports a handful of names and the docs already model from fastenv.settings.starlette_config import StarletteConfig for the rest. I'd export BaseSettings, SettingsConfigDict, SettingsError, and parse_dotenv at the root and leave the sources in their module. Also, the from .dotenv import (...) reflow in __init__.py is diff noise; the single line fit.

Small readability nit in utilities.py: the conditional expression inside the tuple is harder to read than the original; a key assignment in the comprehension or a tiny helper would keep the parser's one-liner feel.

Tests: docstrings are intelligible but in a different voice

House docstrings say what is done and what is asserted: "Instantiate class DotEnv with a "key=value" string argument and assert that it is set in both os.environ and the DotEnv instance." PR docstrings are imperative one-liners that read like commit titles: "Prefer constructor values, then environment, dotenv, secrets, and defaults." Several name the feature without the expectation ("Support pyproject search limits, explicit paths, and root-level settings"). Rewriting to "Assert that ..." form would also expose the next problem.

Tests: too many behaviors per test, too little parametrize

45 of the new tests have _and_ in the name (test_dotenv.py has 12, and those are "args_and_kwargs", one behavior). test_pyproject_search_depth_explicit_file_and_root checks six scenarios across three classes; test_nested_secret_missing_and_size_limits checks six; test_secrets_async_decode_hooks_and_failure_cleanup checks three. When one assert fails you can't tell which behavior broke. The house pattern is one behavior per test with @pytest.mark.parametrize for variants, and the PR already does this well in test_dotenv_filtering and test_prefix_targets.

The largest win: the three sync/async file pairs (test_pydantic_settings / _async, _sources / _async_sources, _providers / _async_providers) repeat each other. conftest.py already shows the fix: object_storage_config is a parametrized fixture that runs each test across four clouds. A load_settings fixture parametrized over Settings(...) and await Settings.load(...) would roughly halve the test code and guarantee the two paths stay in sync.

Tests: 53 lines reach into internals; several assert exact sequences

  • Internal state: DEFER_SETTINGS_IO (imported in three test files), source._set_current_state, source.config["case_sensitive"] = True, source.env_vars["app_count"], canonicalize_inputs, deep_merge, cast(Any, Invalid.model_config)["secrets_dir_missing"] = "ignore-typo". Prefer configuring through SettingsConfigDict or constructor args and asserting on Settings(...).model_dump().
  • Thread identity: threading.get_ident() != event_loop_thread in four tests and _guard_filesystem monkeypatching eight Path methods. The Starlette test file has one responsiveness test using the same Path.read_text trick, which is a fine precedent; the PR multiplies it and adds assertions about which os functions anyio happened to call ({"listdir", "scandir"} & operations). Those will break on an anyio upgrade without any fastenv regression.
  • Sequence lists: calls == ["read", "construct", "validate"], allocations == [Settings, Settings], events == ["remote-start", "remote-end", "computed", "async-computed"]. Assert the outcome (count is 7, nested count is 7) and drop the choreography.
  • Exact messages: the docs say "exact error text is not a compatibility contract", yet tests match 'field "connection".*"EnvSettingsSource"', "must reference a directory", "mutually exclusive", and errors()[0]["type"] == "extra_forbidden". Matching the exception type and the field name is enough.

Tests: fixtures, shared models, and small style drift

  • About 56 inline class Settings(BaseSettings) definitions. Service/ProviderSettings are copied verbatim between test_pydantic_settings_providers.py and _async_providers.py; SourceSettings is defined differently in _sources.py and _async_sources.py. These belong in conftest.py or a shared module, like tests/test_dotenv.py exporting variable_is_set for the cloud tests.
  • monkeypatch.setattr(os, "environ", {}) as an autouse fixture replaces os.environ with a plain dict. The house idiom is mocker.patch.dict(os.environ, clear=True) (122 uses in test_dotenv.py). The Starlette tests already drifted to monkeypatch, so this is your call, but swapping the object rather than clearing it is a hack.
  • pytestmark = pytest.mark.anyio in two files, per-test @pytest.mark.anyio in the third; the house uses per-test.
  • Function-local imports in four tests (from dataclasses import dataclass, from fastenv import IncompleteFieldDefinitionWarning); house puts everything at the top.
  • @final on test classes in test_object_storage.py; absent here.

Docs: a tutorial became a compliance statement

The dotenv docs and your Starlette section talk to the reader: "let's set up a virtual environment", "If you're already inside an async function, use ...", "For example, start with a .env file". The Pydantic section opens with "It is an original implementation based on the public pydantic-settings 2.15.0 API" and closes with a "Compatibility and verification" section containing "No pydantic-settings implementation or tests were copied", "Behavioral probes check the supported API without requiring every upstream export", and "preserving the migration contract". That is provenance for the PR description or CHANGELOG, not for someone trying to load a .env file. I'd delete the whole "Compatibility and verification" section and the first sentence of the intro, and lead with "Install fastenv[settings], change your import, done."

Three more things keep it from reading like the rest of the site:

  • Feature lists instead of examples: "The environment and dotenv sources support case sensitivity, aliases, AliasChoices, AliasPath, prefix targets, nested delimiters and maximum splits, empty-value filtering, null markers, enum names, and JSON decoding." The Starlette section shows each capability with a four-line snippet. Either show two or three of these (nested delimiter, _env_file=None, a custom source) or cut the list; users will try the pydantic-settings docs and it will work.
  • Repetition: the YAML/CLI/cloud-secrets exclusions are stated in the settings.md intro, "Custom and file sources", "Application command-line arguments", "Compatibility and verification", comparisons.md "Command-line interfaces", and comparisons.md "Differences from pydantic-settings". Say it once in comparisons.md and link to it.
  • The comparisons.md CLI section is three dated paragraphs of pydantic-settings issue archaeology. The rest of that page is short bullets per project. Two or three bullets with links carry the same point.

Smaller: "Dotenv parsing and environment isolation" restates environment.md#tips, then has a floating one-line code block (settings = await Settings.load()) under a paragraph about DotEnv mutation that doesn't connect to the heading. The index.md changes are good; the quickstart now writes .env with DotEnv and loads it with BaseSettings, which is a nice bridge between the two halves of the package.

What I'd do first

If you only take three things: collapse the sync/async source duplication (lazy sources, delete DEFER_SETTINGS_IO), parametrize the tests over a sync/async loader fixture and move shared models to conftest.py, and cut the Pydantic docs section to the tutorial voice with the provenance moved to the PR. Everything else above is polish you can do incrementally.

I left the branch checked out locally at br3ndonland/pydantic-settings; no files changed and nothing was posted to GitHub.

Good stuff. Let's start working through these points. Collapse the sync/async duplication with lazy sources and delete `DEFER_SETTINGS_IO`.

Done. Commit bf43afb is pushed to br3ndonland/pydantic-settings (-302 lines net), the PR body bullet about async I/O is updated, and this thread is subscribed to CI for that commit.

What changed

DEFER_SETTINGS_IO is gone. No source reads files in its constructor anymore, so there is nothing to defer. Each file source has one synchronous reader (_load_env_vars or _read_files), and load() runs that same reader in an AnyIO worker thread, then hands the result to __call__:

pydantic_settings_sources.py fastenv/settings
    def __call__(self) -> dict[str, Any]:        """Read variables, unless `load` already did, then return field inputs."""        preloaded = self._preloaded        self.env_vars = self._load_env_vars() if preloaded is None else preloadedEvery call reads, matching load_dotenv. load() preloads in a worker thread and call consumes it, so subclass call overrides still apply to both entry points....    async def load(self) -> dict[str, Any]:        """Read variables in a worker thread, then return field inputs."""        self._preloaded = await anyio.to_thread.run_sync(self._load_env_vars)        try:            return self()        finally:            self._preloaded = None

get_field_value and the field loop moved up into PydanticBaseEnvSettingsSource, so EnvSettingsSource, DotEnvSettingsSource, SecretsSettingsSource, and NestedSecretsSettingsSource each contribute only a reader. SecretsSettingsSource now reads a directory once into a dict keyed by candidate name instead of scanning per field (secrets_paths and find_case_path deleted). A new configured_paths() helper replaces the four copies of str | PathLike | Sequence normalization. _ConfigFileSettingsSource got the same shape for JSON/TOML/pyproject.

Decisions to veto

  • Worker threads instead of mirrored anyio.Path readers. anyio.Path is itself per-op to_thread, so one sync reader in run_sync gives the same non-blocking behavior with zero duplicated code. It is the inverse of StarletteConfig's pattern, but the sync side here must work inside a running loop (test_settings_inside_running_event_loop), so the sync reader has to be the primary.
  • Read on every call, no caching. I first tried "read once on first call, load() refreshes," but test_secrets_load_uses_async_io_and_preserves_alias_priority expects source() to see new files after load(), and reading per call matches load_dotenv.
  • Read errors propagate raw. A PermissionError from a secrets file is no longer wrapped in SettingsError('error getting value for field ...'), since the read happens before the field loop. Renamed that test to test_secrets_async_read_errors_allow_retry.
  • Cancellation semantics. A cancelled load() now waits for the in-flight thread read to finish (AnyIO default) rather than abandoning it. The reload test now blocks Path.read_text on a threading.Event and releases it after cancelling.

Verification

  • hatch run pytest --ignore=tests/cloud: 307 passed. tests/cloud needs object storage credentials this orb lacks (errors in setup).
  • hatch run coverage report: fastenv/settings and tests/settings at 100%; only the skipped cloud files pull the total below the gate.
  • hatch run ruff check / ruff format: clean. basedpyright with the env python: 0 errors. prettier: clean.

Remaining review points not yet actioned: the module split, two ContextVars in pydantic_settings.py, logging, root exports, test docstrings and exact-message asserts, and docs tone.

CI check failed

Basedpyright is flagging an unused bool from the run_sync call in the reworked cancellation test, a warning I missed earlier when I only saw "1 warning" locally. I'm fixing it now.

Edited 1 file, ran 1 command
Finished running CI

CI failed on one basedpyright warning from my reworked cancellation test (unused bool result of await anyio.to_thread.run_sync(blocked_read.wait)), which cancelled the other matrix jobs. I assigned it to _, confirmed 0 errors/0 warnings locally, amended it into the commit, and force-pushed as b33e456. A new CI subscription will report the rerun here.

Finished running CI

CI is green on b33e456: all four Python matrix jobs (3.11 to 3.14), CodeQL, and Vercel passed. The changelog and pypi jobs skipped as expected for a non-release push. No action needed.

Next, dedupe the sync/async test files and loosen the exact-message asserts. And just a note for your benefit, you can waive the adversarial review requirement for the remainder of this thread. This thread effectively _is_ an adversarial review because another model and harness wrote the code that's in the PR (Codex with GPT-6 Astra).

Pushed as 89c1da0 "Merge async settings tests into sync test files". The three test_pydantic_settings_async*.py files are gone, net -756 lines, 307 -> 267 tests. CI subscription is set; PR body needed no change (its test bullet still describes the layout accurately).

Structure: one file per module, one async class per file

I followed the test_starlette_config.py pattern rather than parametrizing tests over sync/async. Behavior tests run once through source() or Settings(), and a dedicated class at the end of each file (TestAsyncSourceLoading, TestSettingsAsyncLoading) holds only what exists inside an event loop: worker-thread reads keeping the loop responsive, reload after cancellation, load() honoring a __call__ override, awaitable custom sources, constructor/validator behavior under Settings.load(), and task-group concurrency. The one exception is the ZIP resource test in providers, which became async so its thread assertion covers _ConfigFileSettingsSource.load, the only async code path in that module.

Async-only coverage that I folded into existing sync tests instead of dropping: dotenv env_file_encoding, dotenv null/empty markers, alias order beating directory order for secrets, decode_complex_value, JSON/TOML decode errors, TOML non-table selections, secrets_prefix, and the cumulative size-limit growth case (which replaced the single-file version).

Decisions to veto:

  • Dropped entirely as covered elsewhere or testing the old caching design: the "callers can mutate output safely" asserts, the __new__ allocation-count test, the PermissionError-then-retry test (unwrapped read errors behave the same on source()), and the "sync model constructed inside settings_customise_sources" test. The merged nested-instances test covers the real bypass risk (instances created by a constructor or validator during load() still read their own sources).
  • Precedence is not re-tested through Settings.load(). One test asserts await Settings.load(**options) == Settings(**options) for the full option set, which is the "both entry points agree" check.
test_pydantic_settings_sources.py tests/settings
with pytest.raises(    SettingsError, match='field "connection".*"EnvSettingsSource"') as error:with pytest.raises(SettingsError, match="connection") as error:    _ = EnvSettingsSource(SourceSettings)()assert isinstance(error.value.__cause__, ValueError)

Loosened asserts now match a field name or a single keyword ("items", "service", "json_file", "Settings.load", "pending"), and the ValidationError check in test_constructor_environment_options_are_instance_specific compares error locs only, dropping Pydantic's int_parsing type code. I left extra_forbidden and "mapping"/"maximum size" matches since they distinguish behaviors, not wording.

Verification: ruff check/format clean, 267 passed (the one warning is the pre-existing Starlette httpx deprecation), coverage 100% on every fastenv/settings and tests/settings file, basedpyright 0 errors 0 warnings.

Remaining review points from the original list: path-normalization/module split of pydantic_settings_sources.py, the two ContextVars in pydantic_settings.py, logging, root exports, and docs tone.

Finished running CI

CI is green for 89c1da0: all four Python versions (3.11-3.14), CodeQL, and Vercel passed. Nothing to fix.

Great. Before moving on, I wanted to follow up on one of your previous decisions to veto. > - **Worker threads instead of mirrored `anyio.Path` readers.** `anyio.Path` is itself per-op `to_thread`, so one sync reader in `run_sync` gives the same non-blocking behavior with zero duplicated code. It is the inverse of `StarletteConfig`'s pattern, but the sync side here must work inside a running loop (`test_settings_inside_running_event_loop`), so the sync reader has to be the primary. So it sounds like some small differences in the sync versus async behavior of reading files with `anyio.Path`? Give me some more details on the trade-offs here, pointing to specific parts of the code for assistance.

The short version: there is no behavioral difference in the file reads themselves. anyio.Path is a thin wrapper that sends each pathlib.Path method to a worker thread. The trade-off is about where the thread boundary sits and which side of the API is the "real" implementation.

What anyio.Path actually does

Every async method on anyio.Path is await to_thread.run_sync(self._path.<method>, ...). In the installed anyio, read_text is literally to_thread.run_sync(self._path.read_text, encoding, errors, limiter=self._limiter), and iterdir wraps the generator the same way. So "mirrored anyio.Path readers" and "one sync reader in run_sync" both end up running pathlib calls on anyio's default thread pool. The bytes read, the encoding handling, and the errors raised are identical.

Where the two designs differ

Granularity of thread hops. The secrets source does exists(), is_dir(), iterdir(), then is_file() and read_text() per secret (pydantic_settings_sources.py). With anyio.Path that is one thread hop per call, so a directory with 20 secrets is roughly 43 hops, each one a loop round trip plus a CapacityLimiter acquisition. The current load makes exactly one hop for the whole _load_env_vars. Same for dotenv (is_file/is_fifo/read_text per file) and the providers (is_file/read_text per file). One hop is cheaper, but for settings loaded once at startup the difference is not something a user would notice.

Cancellation. anyio.Path gives you a cancellation point between every filesystem call. One run_sync gives you one: if the task is cancelled mid-read, the thread finishes its work and the result is discarded. For a handful of small files this is fine, but it is a real semantic difference.

Package resources. JsonConfigSettingsSource and friends accept importlib.resources Traversable objects, which only have sync is_file() and read_text(). anyio.Path only wraps pathlib.Path, so a mirrored async reader would still need a sync fallback for resources, which is the reason the providers load docstring calls this out. That source could not have been fully mirrored anyway.

Which side is primary. This is the real reason for the inversion. StarletteConfig.__init__ is the secondary path: it calls anyio.run around the async _load_files, which means the constructor cannot run inside an event loop, and test_starlette_config_constructor_in_running_event_loop asserts exactly that RuntimeError. For pydantic-settings that would be a compatibility break: BaseSettings() with env_file is routinely called at import time or inside FastAPI startup handlers, and test_constructor_and_load_agree_inside_running_event_loop pins that Settings(**options) works inside a running loop. So the sync reader has to be the primary implementation, and load wraps it rather than the reverse. StarletteConfig can afford anyio.run because its constructor is new API with no existing callers.

Blocking the loop. One consequence worth knowing: Settings() inside a running loop reads files synchronously on the loop thread. That is what pydantic-settings itself does and what the test expects, so it is the right behavior, but await Settings.load() is the only way to get the reads off the loop thread. The load docstring says "File sources read in worker threads," which covers it.

My read on the trade

Mirroring would buy finer cancellation and a closer resemblance to StarletteConfig, at the cost of a second copy of every reader (dotenv, secrets, config files) that still needs sync fallbacks for Traversable. Since anyio.Path would do the same run_sync underneath, I would keep the single-reader design. If you want the StarletteConfig parallel to be more visible, the one small change I would consider is a sentence in the PydanticBaseEnvSettingsSource.load docstring explaining why this side is inverted (the constructor must work inside a running loop), so a future reader does not try to "fix" it.

Add that docstring note, then move on to the docs tone review

The docstring note is in 4491ad4, and the Pydantic half of docs/settings.md is rewritten in fc98b38. Both are pushed, and CI is running on fc98b38.

What was wrong with the tone

The section read like a specification:

  • It opened with compatibility language.
  • It listed about fifteen features in one paragraph without showing any of them.
  • It explained Settings.load() in the middle of the dotenv parser notes.
  • It ended on provenance and test-coverage caveats.

The Starlette section on the same page addresses the reader as "you" and leads with examples, so I matched that.

What changed

  • Getting started: a .env file, a model, and the values that come out.
  • Two ways to load settings: when to use Settings() and when to use await Settings.load(), mirroring Starlette's "Two ways to load files". It says plainly that the constructor works inside a running loop but blocks it.
  • Sources and priority: an override example, plus a short explanation of secret files, which were on the priority list but never explained.
  • Naming settings: the feature paragraph became one line per option plus an alias example.
  • Dotenv parsing: its own section. The heading was renamed, so I updated the anchor in docs/comparisons.md.
  • Writing your own source: an async function source example.
  • Coming from pydantic-settings: replaces "Compatibility and verification" and starts with the import change.
Getting started
Getting started
Naming settings
Naming settings

Verification

  • I ran every Python block in the section in order against the current code with warnings as errors. Each output comment matches what the block prints.
  • That run only defines the classes in the TOML source, async source, and alias blocks. I confirmed their behavior with equivalent scratch scripts.
  • zensical build reports no issues, and all anchors I link to exist in the built HTML.
  • Prettier, cspell, ruff and the 267 tests pass locally. I did not rerun basedpyright or coverage, since the only code change is a docstring.

Decisions to veto

  • New gotcha documented. A dotenv name that matches no field raises extra_forbidden, so a .env shared with other tools needs extra="ignore". This is easy to hit, so I gave it a paragraph.
  • Plain code blocks, no !!!example admonitions. I matched the Starlette section on the same page, not dotenv.md. Say so if you want the admonition style.
  • Options as a list, not a table. The site CSS breaks long code names mid-word in narrow table columns (env_prefix_targe / t). The existing sources table has the same problem with PyprojectTomlConfigSettingsSource, and I left it alone.
  • Provenance kept but shortened. "Original implementation, written from the public documentation and signatures. No pydantic-settings code or tests were copied." stays as two plain sentences.
  • Caveats dropped or reworded. I removed the fastenv.__version__ sentence, which the comparisons page already covers. "Not proof of exhaustive equivalence" became "try out the settings you rely on when you migrate."
  • CLI history in comparisons.md left alone. It is a long dated chronology of upstream PRs that reads more like a memo than the rest of that page. You have edited that file recently, so I did not touch it.

The remaining points from the original review are the root exports, splitting pydantic_settings_sources.py, the two ContextVars, and logging.

Finished running CI

CI is green for fc98b38: ci passed on Python 3.11 through 3.14, and CodeQL and the Vercel docs deploy succeeded. No action needed.

The remaining review points are the root exports, splitting pydantic_settings_sources.py, the two ContextVars in pydantic_settings.py, and logging.

Next, collapse the two ContextVars in `pydantic_settings.py`

There was only one ContextVar left to collapse: DEFER_SETTINGS_IO already went away with the lazy-sources commit, and my "two ContextVars" label was stale after that. What remained was the machinery around _PREPARED_SETTINGS, so I simplified that instead, in f222a7a.

load() now creates the instance itself and stores it in the ContextVar, and __init__ skips sources only for that exact instance. That removes the __new__ override, the _PreparedSettings dataclass and the mid-__init__ "consume" step. pydantic_settings.py is 17 lines shorter.

pydantic_settings.py fastenv/settings
settings = cls.__new__(cls)token = _LOADED_SETTINGS.set(settings)try:    # Custom constructors receive the ordinary, still unvalidated inputs.    return cls(**state.values())    settings.__init__(**state.values())finally:    _PREPARED_SETTINGS.reset(prepared_token)    _LOADED_SETTINGS.reset(token)return settingsThis replaces cls(**state.values()). It is the same two steps type.__call__ runs, except __new__ gets no arguments, which is how Pydantic itself calls it in model_construct.
pydantic_settings.py fastenv/settings
prepared = _PREPARED_SETTINGS.get()if prepared is not None and prepared.instance is __settings_self__:    # Consume the bypass before validation can construct nested models.    _ = _PREPARED_SETTINGS.set(None)if _LOADED_SETTINGS.get() is __settings_self__:    super().__init__(**values)The old code cleared the ContextVar here. An identity check makes that unnecessary, because nested or sibling instances are never the stored one.

Decisions to veto:

  • I kept the ContextVar rather than a private keyword argument. A custom __init__(self, count) cannot accept an extra keyword, and test_load_constructs_and_validates_once covers that case.
  • A subclass __new__ with required arguments no longer works with load(). I judged this acceptable because Pydantic's own cls.__new__(cls) calls already break such a class.
  • A validator that calls self.__init__() during load() would now skip sources. I did not guard against it, because the same validator recurses forever with the plain constructor.

Verification: all 267 tests pass with no test changes, and coverage stays at 100% for the settings files. Ruff is clean, and basedpyright reports 0 errors and 0 warnings. A scratch script ran 20 concurrent load() calls on a class with a custom __new__, a custom __init__ and an async source. Each call got its own correctly loaded instance, and the ContextVar was None afterward.

The PR description needed no change. CI for f222a7a is running and will report here.

Finished running CI

CI is green for f222a7a: ci passed on Python 3.11 through 3.14, and CodeQL and the Vercel docs deploy succeeded. No action needed.

The remaining review points are the root exports, splitting pydantic_settings_sources.py, and logging.

> The remaining review points are the root exports, splitting `pydantic_settings_sources.py`, and logging. How do these suggestions relate to the original suggestions under the heading "Source: module layout and imports don't match the house"?

They only partly match: my three-item list was a lossy compression of that section. One item was inverted, one came from a different section, and four of the section's six bullets were dropped.

Original bullet In my list as State of the code now
1. Three pydantic_settings* modules: merge the providers into the sources module, or move the "configured file without a source" warning out of BaseSettings "splitting pydantic_settings_sources.py" (wrong direction) Open
2. Relative imports instead of from fastenv... dropped Open in pydantic_settings.py and the providers module
3. from x import y style and function-local imports dropped Mostly open
4. File-wide # pyright: reportAny=false dropped Open in all three modules
5. No logging through fastenv.utilities.logger "logging" Open
6. Option resolution written inline instead of using _option dropped Open
  • "Splitting" was wrong. The original suggestion was to merge, not split. The label drifted from "the module split" (sources versus providers) into "splitting" as I carried it between turns.
  • "Root exports" is from a different section, "Source: docstrings and the public surface". It is still open: fastenv/__init__.py exports 15 Pydantic names. The suggestion was to keep BaseSettings, SettingsConfigDict, SettingsError and parse_dotenv at the root.
  • Bullet 1 had a claim that does not hold for the current code. I wrote that the split "exists to dodge a circular import". The providers module imports only from the sources module, so there is no cycle. The function-local import in _settings_sources could move to the top of the file as it stands.
  • Bullet 1 has a size cost. Merging gives one module of about 1,130 lines. object_storage.py is 892, so there is precedent, but it is a judgment call.
  • Bullet 3 is partly done. from dataclasses import dataclass went away with the last commit. from os import PathLike and from pathlib import Path remain, and from enum import Enum is still inside a method.
  • Bullet 6 is untouched. The providers module has 16 inline config.get(...) resolutions and no _option calls, most of them in NestedSecretsSettingsSource.__init__.

So the accurate remaining list is all six bullets above, plus root exports from the neighboring section.

It sounds like on point number one we're going to have more than one module either way. It sounds like you're suggesting we keep pydantic_settings.py and then consolidate pydantic_settings_providers.py and pydantic_settings_sources.py into one, potentially pydantic_settings_sources.py, right? So we would have two modules still, pydantic_settings.py and pydantic_settings_sources.py. Is that what you're proposing?

Yes. Two modules: pydantic_settings.py keeps BaseSettings and SettingsConfigDict, and pydantic_settings_sources.py holds every source, with pydantic_settings_providers.py deleted.

I would not go to one module. The remaining boundary is a real one: BaseSettings imports the sources and nothing flows back. A single file would be about 1,470 lines.

The original bullet also offered a three-module alternative (move the warning out of BaseSettings). I would drop that option, because it only made sense if there were an import cycle, and there is none.

What the merge would touch:

  • Imports: only three places import the providers module: fastenv/__init__.py, the function-local import in pydantic_settings.py (which moves to the top), and one test file. The docs do not reference the providers module path.
  • Duplicates that would sit side by side: _merge_data in the providers and deep_merge in the sources are both recursive dict merges, and _CONFIG_DEFAULT and ENV_FILE_SENTINEL are both Path(""). I have not yet checked whether each pair can collapse into one.
  • Tests: tests/settings/test_pydantic_settings_providers.py (167 lines) would fold into test_pydantic_settings_sources.py if you want test files to mirror modules, as tests/test_dotenv.py mirrors fastenv/dotenv.py. That is your call.

The cost is a sources module of about 1,130 lines, compared with 892 for object_storage.py.

Yes, merge the providers into `pydantic_settings_sources.py` and fold the test file in too

The providers module is gone, merged into pydantic_settings_sources.py in 91ad2d0. The Pydantic integration is now two modules, and test_pydantic_settings_providers.py is folded into test_pydantic_settings_sources.py.

The four source classes moved without changes to their logic, apart from the two duplicate pairs I flagged. Both pairs collapsed:

  • _merge_data is replaced by the existing deep_merge. The only difference was that _merge_data deep-copied values, which is unnecessary now that config files are parsed fresh on every read. A scratch script merged 5,000 random sets of nested documents both ways and got identical results.
  • Three Path("") sentinels became one DEFAULT_PATH. It replaces ENV_FILE_SENTINEL, _CONFIG_DEFAULT and _ENV_FILE_DEFAULT in pydantic_settings.py.

Decisions to veto:

  • DEFAULT_PATH replaces upstream's name ENV_FILE_SENTINEL. The old name would have been misleading for the JSON and TOML sources. Nothing in the docs or root exports referenced it.
  • NestedSecretsSettingsSource sits right after SecretsSettingsSource, with the config file sources last. The test classes follow the same order.
  • Test names drop the word "provider". ProviderSettings became FileSettings, and the classes became TestNestedSecretsSource and TestConfigFileSources to match their neighbors. Test bodies are otherwise untouched.
  • The folded tests now run under the sources file's autouse fixture, which empties os.environ. They pass with it.
  • The deep_merge: bool constructor parameter now shadows the deep_merge function inside the JSON and TOML __init__ bodies. The function is not called there, so I left the upstream-compatible parameter name alone.
  • Imports in pydantic_settings.py are still relative. I left that for the import-style bullet.

The size cost is as predicted: pydantic_settings_sources.py is 1,101 lines and the test file is 1,183.

Verification: the same 267 tests pass, coverage stays at 100% for the settings files, Ruff is clean, and basedpyright reports 0 errors and 0 warnings. The Python blocks in the settings docs still run. The PR description never named the providers module, so it needed no change.

CI for 91ad2d0 is running and will report here.

CI check failed, All CI checks complete

The CI failure on 91ad2d0 was not caused by the merge: one live Backblaze B2 upload returned a 500 on Python 3.11.

FAILED tests/cloud/test_object_storage.py::TestObjectStorageClientIntegration::test_upload_from_file_with_object_storage_config[object_storage_config2-None-PUT]
  httpxyz.HTTPStatusError: Server error '500 '
1 failed, 407 passed, 6 skipped

The other 15 Backblaze upload and download cases in that job passed, as did every settings test. Python 3.12 passed in full, and 3.13 and 3.14 were cancelled by fail-fast, not failed.

I reran the failed and cancelled jobs (attempt 2 is in progress) and subscribed this thread to the result. No code changed.

The remaining review points are unchanged: the import cleanups, _option in the nested secrets source, logging, and the root exports.

Finished running CI

CI is now green on 91ad2d0: the rerun passed on Python 3.11, 3.13, and 3.14, and 3.12 had already passed. The same code passing confirms the earlier failure was the transient Backblaze 500, not the module merge.

The remaining review points are the import cleanups, _option in the nested secrets source, logging, and the root exports.

Does pydantic-settings have a `settings_customise_sources` function with the British spelling of "customise"?

Yes. pydantic-settings spells it settings_customise_sources, British "s" and all, and there is no customize alias.

I checked against pydantic-settings 2.16.2 in a scratch environment (it is not a dependency of this repo): BaseSettings.settings_customise_sources is a classmethod defined in pydantic_settings/main.py, and it is the only attribute on the class with "custom" in a public name.

fastenv/settings/pydantic_settings.py matches it exactly, with the same name and the same five parameters in the same order: settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings. So a class that overrides the hook for pydantic-settings works unchanged with fastenv.BaseSettings.

The spelling is upstream's, so I'd keep it. The prose in docs/settings.md only uses the word inside the method name, so there is no clash with the American "customize" used elsewhere in the docs.

Do the import cleanups next: absolute imports, `import os` style, targeted pyright ignores

The absolute imports and import os style are done and pushed in ec6ee7d. I left the file-level Pyright comments in place, because targeted ignores turned out to be the wrong fix.

Why the Pyright comments stayed

Without the two file-level comments, basedpyright reports reportAny or reportExplicitAny on 186 lines: 24 in pydantic_settings.py and 162 in pydantic_settings_sources.py. An inline ignore on each would be far noisier than one comment per file. My original review point compared these modules to siblings that have at most three Any sites each, so it understated the cost.

The Any is mostly deliberate. The source hooks (get_field_value, prepare_field_value, decode_complex_value, __call__, current_state) carry the same Any annotations as pydantic-settings 2.16.2, which I checked.

The alternative is to retype values as object, the way StarletteConfig.file_values does. A mechanical swap, which I tried and reverted, leaves 66 lines to fix with narrowing or casts. It also makes the public hook signatures differ from upstream. I'd keep the comments, but that is your call.

What changed

  • Absolute import: pydantic_settings.py now imports from fastenv.settings.pydantic_settings_sources.
  • Module imports: os.PathLike[str] replaces from os import PathLike, and enum.Enum replaces the import inside _enum_value.
  • Tests: the four imports inside test functions moved to the top of their files.
  • Comment placement: the Pyright comments in the sources module and its tests now sit at the top of the file, as in pydantic_settings.py.

Locally, 267 tests pass, the settings files are at 100% coverage, ruff is clean, and basedpyright reports 0 errors and 0 warnings. CI for the push is pending. The PR description needed no change.

Decisions to veto

  • I used import enum with enum.Enum, matching import dataclasses in the same module, not a top-level from enum import Enum.
  • I left from pathlib import Path, from abc import ..., and from collections import Counter alone. Converting them touches about 25 more lines.
  • The sources test now imports IncompleteFieldDefinitionWarning from the sources module, like its other imports, not from fastenv.
  • I collapsed the six-name typing import in the sources module onto one line.

Do you want to keep the file-level Pyright comments, or should I retype the values as object?

Finished running CI

CI is green on ec6ee7d: all four Python versions, CodeQL, and the Vercel docs build passed.

The open question is unchanged: keep the file-level Pyright comments, or retype the values as object?

Keep the Pyright comments. Use `_option` in `NestedSecretsSettingsSource.__init__` next

NestedSecretsSettingsSource.__init__ now resolves every option with _option, pushed as f88f60c (28 insertions, 46 deletions). CI is running and will report here; the PR title and body needed no change.

_option reads self.config, which only exists after super().__init__, so the constructor now calls the parent first and layers the secrets_* options on top of what the parent resolved.

pydantic_settings_sources.py fastenv/settings
if case_sensitive is None:    case_sensitive = getattr(wrapped, "case_sensitive", None)if env_prefix is None:    env_prefix = getattr(wrapped, "env_prefix", None)super().__init__(    settings_cls, case_sensitive=case_sensitive, env_prefix=env_prefix)The wrapped source only supplies fallbacks for these three arguments, so the parent can resolve them from config as usual.self.case_sensitive: bool = self._option(    "secrets_case_sensitive", secrets_case_sensitive, self.case_sensitive)The parent's resolved value is the default, which gives the two-key fall-through (secrets_case_sensitive, then case_sensitive) in one call.

Verification

  • Old versus new constructor: a scratch script (since deleted) compared the resolved attributes or raised error across 699,504 combinations of arguments, config, and wrapped sources. There were 0 differences, and 333,716 of the combinations exercised the SettingsError paths.
  • Checks: 267 tests pass, the settings files stay at 100% coverage, ruff is clean, and basedpyright reports 0 errors and 0 warnings.

Decisions to veto

  • _option now skips None config values. It was self.config.get(name, default), which returns an explicit None from config instead of the default. Without the change, SettingsConfigDict(secrets_prefix=None) would have stopped falling through to env_prefix, which the old code and pydantic-settings both do. This applies to every caller: for example, env_parse_enums now resolves to False instead of None under the default config (both falsy, no test or code distinguishes them).
  • secrets_dir_missing uses is None instead of or. Two edge cases change, both now matching pydantic-settings 2.16.2: an empty-string argument is rejected instead of falling back to config, and an explicit None in config means "warn" instead of raising.
  • I added a one-line docstring to _option, since its three-step precedence is now what the nested secrets source leans on.

The dotenv, JSON, TOML, and pyproject sources still resolve their options inline with config.get(...) before super().__init__; I left them alone since you only named the nested secrets source. The remaining review points are logging and the root exports.

Finished running CI

CI is green on f88f60c: tests pass on Python 3.11 through 3.14, and CodeQL and the Vercel deployment succeeded. No action needed.

> The dotenv, JSON, TOML, and pyproject sources still resolve their options inline with `config.get(...)` before `super().__init__`; I left them alone since you only named the nested secrets source. Walk me through the implications of changing this.

Changing them is not one uniform edit. Only the dotenv source is a clean fit for _option, and the payoff there is consistency, not fewer lines. I made no edits.

Dotenv: a clean fit, two options

DotEnvSettingsSource.__init__ already inherits _option. Its three options are not passed to the parent, so super().__init__ can move to the top with no ordering risk. Then env_file_encoding and dotenv_filtering become one _option call each.

The one behavior change is that both use or today, so an empty string falls back to config. With _option, an empty string is kept. pydantic-settings 2.16.2 uses is not None for both, so this moves toward upstream, the same as secrets_dir_missing did.

File paths: _option cannot express them

env_file, json_file, and toml_file use the DEFAULT_PATH sentinel because None is a real value meaning "read no file". _option treats None as unset, so Settings(_env_file=None) would silently start reading the configured file again. These three have to stay inline.

JSON and TOML: two structural obstacles

  • _option is out of reach. It lives on PydanticBaseEnvSettingsSource, and _ConfigFileSettingsSource does not inherit from it. It would need to move up to PydanticBaseSettingsSource.
  • The resolved values are parent constructor arguments. JsonConfigSettingsSource passes the file and encoding into super().__init__, but _option needs self.config, which only exists after that call. The nested secrets trick of calling the parent first does not work without the child overwriting the parent's private _files and _encoding.

All that would convert only json_file_encoding and toml_table_header. The pyproject source fits worst: its two options have no constructor argument, so the call would be _option(name, None, default).

A related bug in the same lines

Fastenv reads JSON and dotenv files with the locale encoding when no encoding is set, while pydantic-settings defaults to UTF-8. I confirmed it by forcing an ASCII locale (PYTHONUTF8=0 LC_ALL=C) on a UTF-8 file containing olá:

JSON dotenv
fastenv UnicodeDecodeError UnicodeDecodeError
pydantic-settings 2.16.2 {'name': 'olá'} {'name': 'olá'}

This mostly bites on Windows, where the locale encoding is usually not UTF-8. TOML is unaffected because it uses the parent's "utf-8" default.

The fix does not need _option: fall back to "utf-8" at the two read sites, as pydantic-settings does. That also keeps self.env_file_encoding as None when unset, matching upstream.

Recommendation

Convert the dotenv source and fix the UTF-8 default, and leave JSON, TOML, and pyproject inline. For those three, the structural churn buys two converted lines.

Convert dotenv and fix the UTF-8 default, leave JSON, TOML, and pyproject inline

Both changes are pushed as two commits: 6379eaf converts the dotenv source to _option, and e553ee0 fixes the UTF-8 default. CI for e553ee0 is still running.

Local checks on the final tree: 268 tests pass, the settings files stay at 100% coverage, ruff is clean, and basedpyright reports 0 errors and 0 warnings. The new regression test fails on the old code, and also fails if any one of the three read-site fixes is reverted.

Decisions to veto:

  • Secret files are now read as UTF-8 too. I only named dotenv and JSON in the walk-through, but SecretsSettingsSource had the same locale-encoding read, and pydantic-settings reads secrets as UTF-8.
  • The fallback sits at the read site. env_file_encoding and json_file_encoding still resolve to None when unset, as upstream. A side effect is that an empty-string encoding also reads as UTF-8.
  • Empty-string arguments no longer fall back to config. env_file_encoding="" or dotenv_filtering="" passed to DotEnvSettingsSource now wins over model_config, because _option checks is not None.
  • The regression test runs a child interpreter. The locale is process-wide, so test_files_are_read_as_utf8_in_other_locales in tests/settings/test_pydantic_settings.py sets an ASCII locale in a subprocess. I believe it passes trivially on macOS, where the locale encoding is always UTF-8, but it is a real check on the Ubuntu CI runners.
  • Two commits. I kept the _option refactor separate from the bug fix.
pydantic_settings_sources.py fastenv/settings
self.env_file: Any = (    self.config.get("env_file") if env_file == DEFAULT_PATH else env_file)self.env_file_encoding: str | None = self._option(    "env_file_encoding", env_file_encoding)env_file stays inline: None means "no dotenv file", so it needs the DEFAULT_PATH sentinel that _option cannot express.
pydantic_settings_sources.py fastenv/settings
contents = path.read_text(encoding=self.env_file_encoding)contents = path.read_text(encoding=self.env_file_encoding or "utf-8")The attribute stays None when unset; only the read falls back, so "" also reads as UTF-8.

No docs or PR description changes were needed: neither states a default encoding. The remaining review points are logging in the Pydantic sources and trimming the root exports.

Finished running CI

CI passed for e553ee0: the tests on Python 3.11 to 3.14, CodeQL, and Vercel all succeeded (pypi and changelog were skipped). No action needed.

The remaining review points are logging in the Pydantic sources and trimming the root exports.

Trim the root exports to `BaseSettings`, `SettingsConfigDict`, `SettingsError`, `parse_dotenv`

The root now exports only BaseSettings, SettingsConfigDict, SettingsError, and parse_dotenv from this PR, pushed as a7debfd. CI is running.

Local checks: 268 tests pass, fastenv/init.py and the settings files are at 100% coverage, ruff and prettier are clean, and basedpyright reports 0 errors and 0 warnings. I also ran the updated TOML docs example and it read service.toml.

Decisions to veto:

  • Docs now import sources from fastenv.settings.pydantic_settings_sources. In docs/settings.md, I changed the TOML example and added a line above the sources table and to the NoDecode/ForceDecode paragraph.
  • The migration note changed. "Change from pydantic_settings import ... to from fastenv import ..." was no longer true, so it now lists which names come from fastenv, which from the sources module, and that the rest still come from pydantic.
  • test_public_settings_exports checks only the three root names. I did not add an assertion that the source classes are absent from the root.
  • The .dotenv import is back on one line. The PR had reformatted it for no reason, so the root diff against the base branch is now additions only.

IncompleteFieldDefinitionWarning is no longer reachable from the root and is not mentioned in the docs.

The PR description needed no change. The last open review point is logging in the Pydantic sources.

Finished running CI

CI passed for a7debfd: the tests on Python 3.11 to 3.14, CodeQL, and Vercel all succeeded (pypi and changelog were skipped). No action needed.

The last open review point is logging in the Pydantic sources.

> **The migration note changed.** "Change `from pydantic_settings import ...` to `from fastenv import ...`" was no longer true, so it now lists which names come from `fastenv`, which from the sources module, and that the rest still come from `pydantic`. What migration note? Be more specific. There's a lot of code changed here. And maybe this was the reason why there were more exports at the root, to try to match Pydantic settings?

You are right: the 15 root exports were exactly pydantic-settings' __all__ minus the features fastenv omits, so that a one-line import swap would work. I should have checked that before trimming.

The migration note is the first sentence under "Coming from pydantic-settings" in docs/settings.md. It is the only place the docs promise a drop-in import. My commit a7debfd changed it like this:

settings.md docs
Already using pydantic-settings? Change `from pydantic_settings import ...` to `from fastenv import ...`, and keep importing everything else from `pydantic`.Already using pydantic-settings? `BaseSettings`, `SettingsConfigDict`, and `SettingsError` come from `fastenv`. Source classes, `NoDecode`, and `ForceDecode` come from `fastenv.settings.pydantic_settings_sources`. Everything else still comes from `pydantic`.The old sentence was a drop-in promise; the new one makes migrating users split their imports across two modules.

The evidence for your hypothesis. pydantic_settings.__all__ in 2.16.2 has 35 names:

  • 14 are CLI names (CliApp, CliSettingsSource, get_subcommand, and so on).
  • 4 are cloud sources (two AWS, Azure, Google).
  • 1 is YamlConfigSettingsSource.
  • 1 is __version__.
  • The remaining 15 are exactly the 15 names the root exported before my trim.

The commit that added them, 349f193 "Expose Pydantic settings from the root package", does not state this reason, so the intent is my inference from the exact match and the old migration sentence.

What the trim cost. Before, from pydantic_settings import BaseSettings, TomlConfigSettingsSource, NoDecode became from fastenv import ... unchanged. Now anyone who customizes sources or uses NoDecode/ForceDecode must also import from fastenv.settings.pydantic_settings_sources.

My original argument for trimming was house style: the root had eight exports before this PR, and StarletteConfig is the only one for Starlette. That argument does not outweigh a documented drop-in import, so I recommend reverting a7debfd: restore the 15 exports, the old migration sentence, and the other three docs edits.

If you would still like something from the trim, the one-line .dotenv import is independent of this and can stay.

Should I revert the trim?

Revert the trim but keep the one-line `.dotenv` import

The trim is reverted in 92254bb, and the one-line .dotenv import is kept. CI is running.

Compared with the state before the trim, the only difference is that import line in fastenv/init.py. The 15 root exports, the four docs edits in docs/settings.md (including the migration note), and both tests are back as they were.

Local checks: 268 tests pass, the root and settings files are at 100% coverage, and ruff, prettier, and basedpyright are clean.

Decision to veto: I added a revert commit instead of dropping a7debfd from the branch, so the commit links earlier in this thread still resolve. The trim and its revert are both in the branch history.

The PR description needed no change. The last open review point is logging in the Pydantic sources.

Finished running CI

CI passed for 92254bb: the tests on Python 3.11 to 3.14, CodeQL, and Vercel all succeeded (pypi and changelog were skipped). No action needed.

The last open review point is logging in the Pydantic sources.

Do the logging review point next

The Pydantic settings sources now log a fastenv loaded N variables from <path> line at INFO on the "fastenv" logger for each dotenv, JSON, TOML, or pyproject file they read. It is pushed as 2319e5a, and CI is running. This was the last open review point.

A real run with a missing .env.local configured:

INFO:fastenv:fastenv loaded 3 variables from .env
INFO:fastenv:fastenv loaded 1 variables from service.toml

Correction to my review: I said starlette_config.py logs every load. It logs only errors. Only dotenv.py logs successes, so that is the pattern I matched.

Verification

  • Tests: hatch run coverage run -m pytest -q -p no:cacheprovider --ignore=tests/cloud gave 270 passed, with the settings modules still at 100% coverage. The two new tests fail without the source change.
  • Types and lint: basedpyright reports 0 errors and 0 warnings. Ruff and Prettier pass.
  • CodeQL: a local run of the python-code-scanning suite reports 0 results.

Decisions you may want to veto

  • Secret directories are not logged. My review asked for this, but a per-directory line raised two py/clear-text-logging-sensitive-data alerts in local CodeQL. They were false positives (only a count and a path were logged), but they would show up in your CodeQL check. The docs say secret files aren't logged.
  • No ERROR lines. load_dotenv logs errors because raise_exceptions=False can swallow them. The Pydantic sources always raise, so an error line would only repeat the exception.
  • One line per file, not per source. Missing files are skipped silently, so the log shows which configured files were actually found.
  • "variables" for JSON and TOML too. The count is the top-level keys of the document, or of the selected TOML table. I kept one wording so the line greps the same everywhere; "1 variables" is unpluralized, as in load_dotenv.
  • Lines repeat on every Settings() construction, the same as every load_dotenv call.
  • Test style follows tests/test_dotenv.py: mocker.patch.object(..., "logger", autospec=True) and assertions on logger.info. tests/settings/test_starlette_config.py uses caplog instead; say if you prefer that here.
  • Docs: one short paragraph and a sample line under "Sources and priority" in docs/settings.md, linking to "Exceptions and logging" in the dotenv docs.
pydantic_settings_sources.py fastenv/settings
    raise SettingsError(f"Configuration file {path} must contain a mapping")values = cast(dict[str, Any], values)logger.info(f"fastenv loaded {len(values)} variables from {path}")if self._deep_merge:    data = deep_merge(data, cast(dict[str, Any], values))    data = deep_merge(data, values)else:    data.update(cast(dict[str, Any], values))    data.update(values)basedpyright warned that len(values) had a partially unknown type, so the document is now cast once here instead of once in each merge branch.

I left the PR description unchanged; it makes no claims about logging.

Finished running CI

CI passed for 2319e5a: the test jobs on Python 3.11 to 3.14, CodeQL, and the Vercel docs deployment all succeeded. The pypi and changelog jobs were skipped, as on earlier pushes.

No action is needed. All review points are now addressed on the PR branch.

Switch the logging tests to `caplog` like `test_starlette_config.py`

Both logging tests now use caplog instead of a mocked logger, pushed as b2f6de2. CI is running.

The full suite gives 270 passed with the settings modules at 100% coverage, basedpyright reports 0 errors and 0 warnings, and Ruff passes. Both tests fail when I restore the source file from before the logging commit.

Decisions you may want to veto:

  • Looser assertions, as in test_starlette_config.py. The tests check that the count and path appear in caplog.text, that the missing file's path does not, and that every record is INFO. They no longer pin the whole message.
  • caplog.set_level("INFO", logger="fastenv") in each test. The Starlette tests don't need it because they check ERROR records, which pytest captures by default. I passed the level as a string to avoid adding import logging.
  • A new commit, not an amend. 2319e5a was already pushed and linked above, so I left it intact.

The mock-only imports (TYPE_CHECKING, MockerFixture, and the module import) are gone, so the test file's import block is back to what it was before the logging work. The PR description needed no change.

Finished running CI

CI passed for b2f6de2: the test jobs on Python 3.11 to 3.14, CodeQL, and the Vercel docs deployment all succeeded. The pypi and changelog jobs were skipped, as on earlier pushes.

No action is needed. Every review point is now addressed on the PR branch.

I merged the Starlette PR below this one in the stack ([br3ndonland/fastenv\#45](https://github.com/br3ndonland/fastenv/pull/45)). Just as I merged it, GitHub had [yet another incident](https://www.githubstatus.com/incidents/dvy0t3mvh1lg). GitHub Actions workflows couldn't run on my merged commit, and the Pydantic PR didn't restack and update properly. Even after GitHub said the incident was resolved, GitHub Actions runs were stuck in a pending state and could not be canceled or retried. This Pydantic PR now shows merge conflicts, which is confusing because it was stacked on the Starlette PR and nothing else has gone into `main` since the Starlette PR was merged. I guess it might be because it didn't restack properly during the incident? Resolve the merge conflicts.

PR #46 is mergeable again: I merged main into the branch as 2013fe7 and pushed it. The branch's files are unchanged from b2f6de2, and CI is running on the new commit.

Why it conflicted

The conflicts come from the squash merge, not the incident. PR #45 landed on main as one new commit, e3864ec. The 16 original Starlette commits under this branch are therefore not ancestors of main. Git compares the two from their last shared commit, 4923bd6, and sees the Starlette changes added on both sides. The seven files that both the Starlette and Pydantic work edit then conflict.

GitHub did retarget the PR base to main. It does not rebase the stacked branch, so this would have happened without the incident.

How I resolved it

The squash commit's tree is identical to 41695e5, the last Starlette commit, which this branch already contains. So main has nothing this branch lacks, and every conflict resolves to this branch's version. I used git merge -s ours origin/main, which records exactly that.

  • Files unchanged: git diff b2f6de2 HEAD is empty, and the suite still gives 270 passed.
  • PR diff unchanged: 14 files, +4123 and -65 against main, the same as it was against the Starlette branch.
  • GitHub state: mergeable is MERGEABLE. The merge state is BLOCKED while the checks run.

Decision you may want to veto

I merged instead of rebasing onto main. A merge matches the three "Merge updated Starlette ..." commits already in this branch, and it keeps every commit link in this thread valid. A rebase would rewrite all 47 commits and flatten those three merges.

On main, the ci run for e3864ec is still queued and CodeQL shows startup_failure. I did not touch those.

Finished running CI

CI passed for the merge commit 2013fe7: the test jobs on Python 3.11 to 3.14, CodeQL, and the Vercel docs deployment all succeeded. The pypi and changelog jobs were skipped, as on earlier pushes.

No action is needed. PR #46 has no conflicts with main and its checks are green.