Last active
August 3, 2023 13:16
-
-
Save bmritz/63d986934d46d4b43251b0dcce88454a to your computer and use it in GitHub Desktop.
Define and read env vars
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
All environment variable access should be performed via this module. | |
- allows tracing of where variables are used | |
- provide sensible defaults | |
- reduce string typos | |
Declare env vars below with default values. | |
""" | |
import os | |
import sys | |
import ast | |
SIZE = 10 | |
COLOR = 'red' | |
# Magic: Override locals with environment settings | |
for key, default_value in dict(locals()).items(): | |
if key in os.environ: | |
if isinstance(default_value, str): | |
setattr(sys.modules[__name__], key, os.getenv(key)) | |
else: | |
setattr(sys.modules[__name__], key, ast.literal_eval(os.getenv(key))) | |
# function for doing this from an importing function | |
# Experimental: I'm not sure if this works yet, use the above to be sure | |
import os | |
import sys | |
import inspect | |
def override_env_vars(): | |
"""Override the variables in the module in which this function is called with | |
the values from Env vars, if they exist""" | |
frm = inspect.stack()[1] | |
mod = inspect.getmodule(frm[0]) | |
# mod is the python module from which this function is called: | |
# https://stackoverflow.com/a/1095621/21188807 | |
# Magic: Override locals with environment settings | |
if key in os.environ: | |
if isinstance(default_value, str): | |
setattr(sys.modules[mod.__name__], key, os.getenv(key)) | |
else: | |
setattr(sys.modules[mod.__name__], key, ast.literal_eval(os.getenv(key))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Credit to @ddrscott https://gist.github.com/ddrscott/bfb971845bf09cbb387e007addda5b8c