Skip to content

Instantly share code, notes, and snippets.

@rmariano
Created May 28, 2025 14:22
Show Gist options
  • Save rmariano/c043c4a2c8c870c61f88a013b61d2dca to your computer and use it in GitHub Desktop.
Save rmariano/c043c4a2c8c870c61f88a013b61d2dca to your computer and use it in GitHub Desktop.
class EnvironmentVariable:
"""A descriptor that helps fetching environment variables.
To be used like
class Environment:
LOG_LEVEL = EnvironmentVariable(default="INFO")
CONFIG_PATH = EnvironmentVariable(is_required=True)
Then you can do:
env = Environment()
env.LOG_LEVEL # will get the environment variable, or the default it not set
env.CONFIG_PATH # Will get the value from the environment variable, or fail if not set
"""
def __init__(self, is_required: bool = False, default: str | None = None) -> None:
self.name = None
self.is_required = is_required
self._default = default
def __get__(self, instance, owner):
return self.get()
def __set_name__(self, owner, name):
self.name = name
def get(self) -> str:
value = os.getenv(self.name)
if not value and self.is_required:
self.fail()
if not value and self._default is None:
self.fail()
return str(value) or self._default
def is_set(self) -> bool:
return bool(os.getenv(self.name) or self._default)
def fail(self):
logger.error("Missing required environment variable: %r", self.name)
raise ValueError(f"{self.name!r} is not set")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment