Skip to content

Commit

Permalink
Experimental work on a prefix class, inspired by pypi:env.
Browse files Browse the repository at this point in the history
  • Loading branch information
jaraco committed May 29, 2023
1 parent b099cc2 commit 787aaf3
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions jaraco/env.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,39 @@
import collections
import os


class Prefix(collections.abc.Mapping):
"""
>>> setenv = getfixture('monkeypatch').setenv
>>> setenv('JARACO_ENV_FOO', 'foo')
>>> setenv('JARACO_ENV_BAR', 'bar')
>>> env = Prefix('jaraco_env_')
>>> dict(env)
{'foo': 'foo', 'bar': 'bar'}
>>> bool(env.check('foo', expect='foo'))
True
"""

def __init__(self, value):
self.value = value.lower()

def __iter__(self):
return (
val.lower().removeprefix(self.value)
for val in os.environ
if val.lower().startswith(self.value)
)

def __len__(self):
return len(tuple(iter(self)))

def __getitem__(self, key):
return os.environ[self.value.upper() + key.upper()]

def check(self, *args, **kwargs):
return Check(*args, lookup=self, **kwargs)


class Check:
"""
Check if an environment variable meets a certain expectation.
Expand Down

0 comments on commit 787aaf3

Please sign in to comment.