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.
Asked
Active
Viewed 589 times
0
-
1Did you see the example involving the construction of a dict using `dotenv_values` and `os.environ`? – chepner Jan 20 '23 at 18:16
-
Do you mean the second block in other usecases? – FordPrefect Jan 20 '23 at 18:39
-
@chepner I tried to answer it myself with your hint. Maybe you can have a look. – FordPrefect Jan 20 '23 at 19:07
-
1That's exactly right. It's not for `dotenv` to provide defaults, but for the application to *use* `dotenv` to override defaults. – chepner Jan 20 '23 at 19:09
2 Answers
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']

Amin S
- 546
- 1
- 14
-
-
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. – chepner Jan 20 '23 at 18:45
1
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.

FordPrefect
- 320
- 2
- 11