简体   繁体   中英

Default variables with python-dotenv

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.

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']

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM