1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Do we need to run load_dotenv() in every module?

Discussão em 'Python' iniciado por Stack, Setembro 12, 2024.

  1. Stack

    Stack Membro Participativo

    I have a .env defined with the following content:

    env=loc


    I have three python module that make use of this variable.

    ├── __init__.py
    ├── cli.py
    |── settings.py
    ├── commands
    │ ├── __init__.py
    │ └── output.py


    settings.py:

    from dotenv import load_dotenv

    load_dotenv()

    if not os.getenv("env"):
    raise TypeError("'env' variable not found in .env file")


    output.py:

    import os

    def output():
    return getenv("env")


    cli.py:

    import settings
    from commands.output import output
    import os

    CURR_ENV = getenv("env")
    print(CURR_ENV)
    print(output())


    Output:

    loc
    None


    Why is the output from output.py not loc? The environment variables were loaded when load_dotenv() was run for the first time.

    Do I have to run load_dotenv() every time I need to access the environment variables?

    Continue reading...

Compartilhe esta Página