Skip to content

Cannot override env var when creating model  #180

@chbndrhnns

Description

@chbndrhnns

I expect a field value given while creating a model instance takes precedence over an existing environment variable.

It seems this is not possible here:

from pydantic import AnyHttpUrl, Field
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    abc: AnyHttpUrl = Field(validation_alias="my_abc")

    model_config = SettingsConfigDict(populate_by_name=True, extra="allow")


def test_(monkeypatch):
    monkeypatch.setenv("MY_ABC", "http://localhost.com/")

    assert (
        str(Settings(abc="http://prod.localhost.com/").abc)
        == "http://prod.localhost.com/"
    )

One workaround is to use the validation alias when creating the instance:

from pydantic import AnyHttpUrl, Field
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    abc: AnyHttpUrl = Field(validation_alias="my_abc")

    model_config = SettingsConfigDict(populate_by_name=True, extra="allow")


def test_(monkeypatch):
    monkeypatch.setenv("MY_ABC", "http://localhost.com/")

    assert (
        str(Settings(my_abc="http://prod.localhost.com/").abc)
        == "http://prod.localhost.com/"
    )

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions