Skip to content

Instantly share code, notes, and snippets.

@janaSunrise
Created December 8, 2025 17:51
Show Gist options
  • Select an option

  • Save janaSunrise/d22e4a245a54ae7c0b51a91ee7673064 to your computer and use it in GitHub Desktop.

Select an option

Save janaSunrise/d22e4a245a54ae7c0b51a91ee7673064 to your computer and use it in GitHub Desktop.
typesafe `.env` config loader
import os
from collections.abc import Callable
from pathlib import Path
from typing import NewType, TypeVar, cast, overload
T = TypeVar("T")
Undefined = NewType("Undefined", object)
_UNDEFINED = cast("Undefined", object())
class UndefinedValueError(Exception):
"""Raised when a required config value is not found."""
class _Env:
def __init__(self, env_file: str = ".env"):
self._loaded = False
self.load(env_file)
def load(self, env_file: str) -> None:
if self._loaded:
return
path = Path(env_file)
if path.exists():
with Path.open(path) as f:
for line in f:
stripped_line = line.strip()
if not stripped_line or stripped_line.startswith("#"):
continue
if "=" not in stripped_line:
continue
key, value = stripped_line.split("=", 1)
key = key.strip()
value = value.strip().strip('"').strip("'")
# Don't override existing environment variables
if key not in os.environ:
os.environ[key] = value
self._loaded = True
# No cast and optional default
@overload
def get(
self, key: str, *, cast: None = None, default: T | Undefined = _UNDEFINED,
) -> str | T:
...
# With cast and optional default
@overload
def get(
self,
key: str,
*,
cast: Callable[[str], T],
default: T | Undefined = _UNDEFINED,
) -> T:
...
def get(
self,
key: str,
*,
cast: Callable[[str], object] | None = None,
default: object = _UNDEFINED,
) -> object:
value = os.getenv(key)
if value is None:
if default is _UNDEFINED:
raise UndefinedValueError(
f"Configuration key '{key}' not found and no default provided",
)
return default
if cast is None:
return value
try:
return cast(value)
except (ValueError, TypeError) as exc:
raise ValueError(f"Failed to cast '{key}={value}' using {cast}: {exc}") from exc
# Singleton instance
env = _Env()
# Type converters
def to_bool(value: str) -> bool:
return value.lower() in ("true", "1", "yes", "on")
def to_int(value: str) -> int:
return int(value)
def to_float(value: str) -> float:
return float(value)
Copyright 2025 Sunrit Jana <warriordefenderz@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment