Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
env.py87 linesDownload Raw Back to utils
1"""Utilities for environment variables."""2 3from __future__ import annotations4 5import os6from typing import Any7 8 9def env_var_is_set(env_var: str) -> bool:10    """Check if an environment variable is set.11 12    Args:13        env_var: The name of the environment variable.14 15    Returns:16        `True` if the environment variable is set, `False` otherwise.17    """18    return env_var in os.environ and os.environ[env_var] not in {19        "",20        "0",21        "false",22        "False",23    }24 25 26def get_from_dict_or_env(27    data: dict[str, Any],28    key: str | list[str],29    env_key: str,30    default: str | None = None,31) -> str:32    """Get a value from a dictionary or an environment variable.33 34    Args:35        data: The dictionary to look up the key in.36        key: The key to look up in the dictionary.37 38            This can be a list of keys to try in order.39        env_key: The environment variable to look up if the key is not40            in the dictionary.41        default: The default value to return if the key is not in the dictionary42            or the environment.43 44    Returns:45        The dict value or the environment variable value.46    """47    if isinstance(key, (list, tuple)):48        for k in key:49            if value := data.get(k):50                return str(value)51 52    if isinstance(key, str) and key in data and data[key]:53        return str(data[key])54 55    key_for_err = key[0] if isinstance(key, (list, tuple)) else key56 57    return get_from_env(key_for_err, env_key, default=default)58 59 60def get_from_env(key: str, env_key: str, default: str | None = None) -> str:61    """Get a value from a dictionary or an environment variable.62 63    Args:64        key: The key to look up in the dictionary.65        env_key: The environment variable to look up if the key is not66            in the dictionary.67        default: The default value to return if the key is not in the dictionary68            or the environment.69 70    Returns:71        The value of the key.72 73    Raises:74        ValueError: If the key is not in the dictionary and no default value is75            provided or if the environment variable is not set.76    """77    if env_value := os.getenv(env_key):78        return env_value79    if default is not None:80        return default81    msg = (82        f"Did not find {key}, please add an environment variable"83        f" `{env_key}` which contains it, or pass"84        f" `{key}` as a named parameter."85    )86    raise ValueError(msg)87 
codekingpro/portable-devtools · Team Ai