Skip to content

env_proxy.env_proxy

env_proxy

EnvProxy creates a proxy to environmental variables with typehinting and type conversion.

EnvProxy

EnvProxy(
    prefix: str | None = None,
    uppercase: bool = True,
    underscored: bool = True,
)

A proxy to environmental variables with typehinting and type conversion.

Source code in env_proxy/env_proxy.py
def __init__(self, prefix: str | None = None, uppercase: bool = True, underscored: bool = True) -> None:
    self.prefix = prefix
    self.uppercase = uppercase
    self.underscored = underscored

get_any

get_any(key: str, default: T) -> Any | T
get_any(key: str) -> Any
get_any(key: str, default: T | Sentinel = UNSET) -> Any | T

Get value from env typed as Any.

If default is not given and the key does not exist, ValueError is raised.

Source code in env_proxy/env_proxy.py
def get_any(self, key: str, default: T | Sentinel = UNSET) -> Any | T:
    """Get value from env typed as Any.

    If default is not given and the key does not exist, ValueError is raised.
    """
    value = self._get_raw(key)
    if value is None:
        return self._resolve_default(key, default)
    return value

get_bool

get_bool(key: str, default: T) -> bool | T
get_bool(key: str) -> bool
get_bool(
    key: str, default: T | Sentinel = UNSET
) -> bool | T

Get bool value from the environment.

Case-insensitive check for truthy and falsy strings is performed to determine the boolean value.

Truthy values: yes, true, 1, on, enable, enabled, allow Falsy values: no, false, 0, off, disable, disabled, deny

If default is not given and the key does not exist, ValueError is raised.

Source code in env_proxy/env_proxy.py
def get_bool(self, key: str, default: T | Sentinel = UNSET) -> bool | T:
    """Get bool value from the environment.

    Case-insensitive check for truthy and falsy strings is performed to determine the boolean value.

    Truthy values: yes, true, 1, on, enable, enabled, allow
    Falsy values: no, false, 0, off, disable, disabled, deny

    If default is not given and the key does not exist, ValueError is raised.
    """
    value = self._get_raw(key)
    if value is None:
        return self._resolve_default(key, default)
    if value.lower() in bool_truthy:
        return True
    if value.lower() in bool_falsy:
        return False
    raise EnvValueError(key, value, "bool")

get_str

get_str(key: str, default: T) -> str | T
get_str(key: str) -> str
get_str(key: str, default: T | Sentinel = UNSET) -> str | T

Get str value from environment.

If default is not given and the key does not exist, ValueError is raised.

Source code in env_proxy/env_proxy.py
def get_str(self, key: str, default: T | Sentinel = UNSET) -> str | T:
    """Get str value from environment.

    If default is not given and the key does not exist, ValueError is raised.
    """
    value = self._get_raw(key)
    if value is None:
        return self._resolve_default(key, default)
    if isinstance(value, str):
        return value
    return str(value)  # pragma: no cover, unreachable

get_int

get_int(key: str, default: T) -> int | T
get_int(key: str) -> int
get_int(key: str, default: T | Sentinel = UNSET) -> int | T

Get value from the environment as int type. If default is not given and the key does not exist, ValueError is raised.

Source code in env_proxy/env_proxy.py
def get_int(self, key: str, default: T | Sentinel = UNSET) -> int | T:
    """Get value from the environment as int type.
    If default is not given and the key does not exist, ValueError is raised.
    """
    value = self._get_raw(key)
    if value is None:
        return self._resolve_default(key, default)
    try:
        return int(value)
    except ValueError as error:
        raise EnvValueError(key, value, "int") from error

get_float

get_float(key: str, default: T) -> float | T
get_float(key: str) -> float
get_float(
    key: str, default: T | Sentinel = UNSET
) -> float | T

Get value from the environment as float type.

If default is not given and the key does not exist, ValueError is raised.

Source code in env_proxy/env_proxy.py
def get_float(self, key: str, default: T | Sentinel = UNSET) -> float | T:
    """Get value from the environment as float type.

    If default is not given and the key does not exist, ValueError is raised.
    """
    value = self._get_raw(key)
    if value is None:
        return self._resolve_default(key, default)
    try:
        return float(value)
    except ValueError as error:
        raise EnvValueError(key, value, "float") from error

get_list

get_list(
    key: str,
    default: T,
    *,
    separator: str = ",",
    strip: bool = True,
) -> list[str] | T
get_list(
    key: str, *, separator: str = ",", strip: bool = True
) -> list[str]
get_list(
    key: str,
    default: T | Sentinel = UNSET,
    *,
    separator: str = ",",
    strip: bool = True,
) -> list[str] | T

Get a list of string values from the environment.

The list is expected to be separated by separator (defaults to comma ,). List items are stripped of leading and trailing whitespace by default.

If default is not given and the key does not exist, ValueError is raised.

Source code in env_proxy/env_proxy.py
def get_list(
    self, key: str, default: T | Sentinel = UNSET, *, separator: str = ",", strip: bool = True
) -> list[str] | T:
    """Get a list of string values from the environment.

    The list is expected to be separated by `separator` (defaults to comma `,`).
    List items are stripped of leading and trailing whitespace by default.

    If default is not given and the key does not exist, ValueError is raised.
    """
    value = self._get_raw(key)
    if value is None:
        return self._resolve_default(key, default)

    values = value.split(separator)
    if strip:
        values = list(map(str.strip, values))
    return values

get_json

get_json(key: str, default: T) -> Any | T
get_json(key: str) -> Any
get_json(
    key: str, default: T | Sentinel = UNSET
) -> Any | T

Get a JSON value and parse it using :func:json.loads.

If the key is missing and no default is given, raises :class:EnvKeyMissingError. If the value is present but is not valid JSON, :class:json.JSONDecodeError (itself a :class:ValueError subclass) is propagated unchanged — this is the one documented deviation from env-proxy's EnvProxyError-only contract. See :mod:env_proxy.exceptions for details.

Source code in env_proxy/env_proxy.py
def get_json(self, key: str, default: T | Sentinel = UNSET) -> Any | T:
    """Get a JSON value and parse it using :func:`json.loads`.

    If the key is missing and no default is given, raises
    :class:`EnvKeyMissingError`. If the value is present but is not
    valid JSON, :class:`json.JSONDecodeError` (itself a
    :class:`ValueError` subclass) is propagated unchanged — this is
    the one documented deviation from env-proxy's
    ``EnvProxyError``-only contract. See
    :mod:`env_proxy.exceptions` for details.
    """
    value = self._get_raw(key)
    if value is None:
        return self._resolve_default(key, default)

    return json.loads(value)

apply_env

apply_env(**env: str) -> Iterator[None]

A context manager that temporarily sets the specified environment variables to the given values. When the context is exited, the original environment variables are restored.

Parameters:

Name Type Description Default
**env str

Arbitrary keyword arguments where the key is the environment variable name and the value is the environment variable value to set.

{}
Example

with apply_env(MY_VAR='value'): # MY_VAR is set to 'value' within this block ...

MY_VAR is restored to its original value after the block

Source code in env_proxy/env_proxy.py
@contextmanager
def apply_env(**env: str) -> Iterator[None]:
    """A context manager that temporarily sets the specified environment
    variables to the given values. When the context is exited, the original environment
    variables are restored.

    Args:
        **env: Arbitrary keyword arguments where the key is the environment variable name
               and the value is the environment variable value to set.

    Example:
        with apply_env(MY_VAR='value'):
            # MY_VAR is set to 'value' within this block
            ...
        # MY_VAR is restored to its original value after the block

    """
    original_env: dict[str, str] = {}
    for key, value in env.items():
        if (original_value := os.getenv(key)) is not None:
            original_env[key] = original_value
        os.environ[key] = value
    yield
    for key in env:
        if key in original_env:
            os.environ[key] = original_env[key]
        else:
            if key in os.environ:
                del os.environ[key]