Skip to content

Instantly share code, notes, and snippets.

@bmritz
Last active August 3, 2023 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmritz/63d986934d46d4b43251b0dcce88454a to your computer and use it in GitHub Desktop.
Save bmritz/63d986934d46d4b43251b0dcce88454a to your computer and use it in GitHub Desktop.
Define and read env vars
"""
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)))
@bmritz
Copy link
Author

bmritz commented May 10, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment