Skip to content

Commit

Permalink
feat: dynamic configuration (#30)
Browse files Browse the repository at this point in the history
We allow for placeholders in prefixes and variable name to allow
for the definition of dynamic configuration.
  • Loading branch information
P403n1x87 authored Dec 8, 2023
1 parent 11581fc commit eae2fe1
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
10 changes: 8 additions & 2 deletions envier/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,11 @@ def _retrieve(self, env: "Env", prefix: str) -> T:
source = env.source

full_name = prefix + _normalized(self.name)
raw = source.get(full_name)
raw = source.get(full_name.format(**env.dynamic))
if raw is None and self.deprecations:
for name, deprecated_when, removed_when in self.deprecations:
full_deprecated_name = prefix + _normalized(name)
raw = source.get(full_deprecated_name)
raw = source.get(full_deprecated_name.format(**env.dynamic))
if raw is not None:
deprecated_when_message = (
" in version %s" % deprecated_when
Expand Down Expand Up @@ -217,9 +217,15 @@ def __init__(
self,
source: t.Optional[t.Dict[str, str]] = None,
parent: t.Optional["Env"] = None,
dynamic: t.Optional[t.Dict[str, str]] = None,
) -> None:
self.source = source or os.environ
self.parent = parent
self.dynamic = (
{k.upper(): v.upper() for k, v in dynamic.items()}
if dynamic is not None
else {}
)

self._full_prefix: str = (
parent._full_prefix if parent is not None else ""
Expand Down
13 changes: 13 additions & 0 deletions tests/test_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,3 +344,16 @@ def validate(value):
Config()
else:
assert Config().foo == value


def test_env_dynamic(monkeypatch):
monkeypatch.setenv("FOO_PFX_BAR_VAR", "24")

class Config(Env):
__prefix__ = "foo.{prefix}"

foobar = Env.var(int, "{dyn}.var", default=42)

config = Config(dynamic={"prefix": "pfx", "dyn": "bar"})

assert config.foobar == 24

0 comments on commit eae2fe1

Please sign in to comment.