1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Why is pydantic_settings not parsing the correct dotenv file?

Discussão em 'Python' iniciado por Stack, Setembro 15, 2025.

  1. Stack

    Stack Membro Participativo

    I have a FastAPI app written in Python. I want to have 2 environments for the app: dev and local. For managing the environments, I have kept 2 files namely .local.env and .dev.env. Also I have a standalone .env file, which I later plan to use for production purposes.

    I am unable to parse a particular dot env file even after explicitly mentioning it.

    My approach is to write a class as follows:

    # config.py file

    from pydantic_settings import BaseSettings, SettingsConfigDict

    class EnvironmentSettings(BaseSettings):
    APP_ENV: str
    APP_DB_URL: str
    # .... and so on...

    # Experiment 1: no luck!
    model_config = SettingsConfigDict(env_file=".local.env")

    # Experiment 2: Settings priorities - still no luck!
    model_config = SettingsConfigDict(env_file=(".local.env", ".env"))

    # Experiment 3: using relative path of the file.
    model_config = SettingsConfigDict(env_file="..//.local.env")

    # Experiment 4: using absolute path of the file.
    model_config = SettingsConfigDict(env_file="C:\\myproject\\.local.env")

    # Experiment 5: Using the old format but not luck.
    class Config:
    env_file=".local.env"


    In all cases it is parsing the contents of the standalone .env file every time - why?

    Provided the folder structure is as follows:

    myproject
    |___ app
    |____|___ config.py
    |___.env
    |___.local.env
    |___.dev.env


    Info: Python 3.12.8 and pydantic_settings >2.9.1

    Continue reading...

Compartilhe esta Página