0

I want to make a package that works out of the box with reasonable default variables, like defining some servers, ports etc. so that the code works for an average user like he expects it without further configuration. But I want this environment variables to be overriden if a .env file exists in order to allow configuration for other environments. I read that python-dotenv load_values will use defaults if no .env file exists, but there is no example on pypi how that would set up ideally.

4
  • 1
    Did you see the example involving the construction of a dict using dotenv_values and os.environ? Commented Jan 20, 2023 at 18:16
  • Do you mean the second block in other usecases? Commented Jan 20, 2023 at 18:39
  • @chepner I tried to answer it myself with your hint. Maybe you can have a look. Commented Jan 20, 2023 at 19:07
  • 1
    That's exactly right. It's not for dotenv to provide defaults, but for the application to use dotenv to override defaults. Commented Jan 20, 2023 at 19:09

3 Answers 3

2

Reading the comment of @chepner I think there might be a solution using merge. Didn't know about that feature yet.

from dotenv import dotenv_values


default_envs = {"MY_SERVER": "https://my-server.com"}
config = {
    **default_envs,
    **dotenv_values
}

This might be nice, because it allows for partial override and I don't need to go through all variables.

Comments are welcome.

Sign up to request clarification or add additional context in comments.

2 Comments

Note: dotenv_values is a function, did you perhaps forget to put the brackets for the function call in the answer?
You are probably right. Don't use that solution and went with using toml for config.
1

i think this way would work.

default_dict = {'API_KEY':'test'} #e.x for an api_key 

try:
    load_dotenv(find_dotenv())
    api_key = os.getenv("API_KEY")
except:
    api_key = default_dict['API_KEY']

3 Comments

That would be an idea, thx.
Don't use a bare except: at least use except Exception, if not an even more specific exception class for what you expect could be raised.
os.getenv("API_KEY", default_dict['API_KEY'] removes the need for the try-except.
1

python_dotenv is just convenient way to load variable to environment

You can add an option to override an already existing env variable:

load_dotenv(override=True)

The order how env are defined can be found here.

To load the default value, just use os.getenv implementation

os.getenv(key, default = 'string value, or define None')

Although, you might not define value in order to make this work (define only key, without using =)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.