Skip to content

env_prefix is ignored if pydantic_settings finds an env var without prefix #437

@hofrob

Description

@hofrob

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

When using env_prefix in a model_config, pydantic_settings will still load values from env vars that do not use the given prefix. Values from env vars without the prefix even have higher priority.

Example repo: https://github.com/hofrob/pydantic-settings-env-prefix

  • clone
  • run uv run hello

HELLO=ABC should just be ignored in my opinion (can't find anything definitive in the docs).

Example Code

import pydantic_settings


class Settings(pydantic_settings.BaseSettings):
    model_config = pydantic_settings.SettingsConfigDict(
        env_file=".env",
        extra="ignore",
        env_prefix="some_prefix_",
    )

    hello: str | None = None


def hello() -> None:
    print(Settings())

# this should only the show the value of `SOME_PREFIX_HELLO`
# output: hello='ABC'

Python, Pydantic & OS Version

pydantic version: 2.9.2
        pydantic-core version: 2.23.4
          pydantic-core build: profile=release pgo=false
                 install path: /path/to/pydantic-settings-env-prefix/.venv/lib/python3.12/site-packages/pydantic
               python version: 3.12.6 (main, Sep  9 2024, 22:11:19) [Clang 18.1.8 ]
                     platform: Linux-6.8.0-45-generic-x86_64-with-glibc2.39
             related packages: typing_extensions-4.12.2 pydantic-settings-2.5.2
                       commit: unknown

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions