Skip to content

Commit

Permalink
Load variables from envrion with exception handling
Browse files Browse the repository at this point in the history
  • Loading branch information
kmagusiak committed Jul 5, 2022
1 parent ecc0605 commit 0584dd8
Showing 1 changed file with 20 additions and 6 deletions.
26 changes: 20 additions & 6 deletions alphaconf/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,25 @@ def _load_dotenv(self, load_dotenv: Optional[bool] = None):
raise
_log.debug('dotenv is not installed')

def __load_environ(self, prefixes: Iterable[str]) -> DictConfig:
"""Load environment variables into a dict configuration"""
from yaml.error import YAMLError # type: ignore

trans = str.maketrans('_', '.', '"\\=')
dotlist = [
(name.lower().translate(trans), value)
for name, value in os.environ.items()
if name.startswith(tuple(prefixes))
]
conf = OmegaConf.create({})
for name, value in dotlist:
try:
conf.merge_with_dotlist(["%s=%s" % (name, value)])
except YAMLError:
# if cannot load the value as a dotlist, just add the string
OmegaConf.update(conf, name, value)
return conf

def _get_configurations(
self,
env_prefixes: Union[bool, Iterable[str]] = True,
Expand Down Expand Up @@ -210,12 +229,7 @@ def _get_configurations(
prefixes = None
if prefixes:
_log.debug('Loading env configuration from prefixes %s' % (prefixes,))
dotlist = [
"%s=\"%s\"" % (name.lower().replace('_', '.').replace('"', '\\"'), value)
for name, value in os.environ.items()
if name.startswith(prefixes)
]
yield OmegaConf.from_dotlist(dotlist)
yield self.__load_environ(prefixes)

def setup_configuration(
self,
Expand Down

0 comments on commit 0584dd8

Please sign in to comment.