Spaces:
Running
Running
File size: 2,153 Bytes
5fd16e5 a9f1179 5fd16e5 a9f1179 5fd16e5 a9f1179 5fd16e5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
import os
from typing import Any
class Constants:
"""A class to hold constants used in the library. This class can be subclassed to add more constants."""
EMPTY_STRING = ""
"""An empty string."""
SPACE_STRING = " "
"""The space character."""
COMMA = ","
"""The comma character."""
TRUE_VALUES_LIST = ["true", "yes", "t", "y", "on"]
"""A list of string values that are considered as True."""
EMPTY_LIST = []
"""An empty list."""
EMPTY_DICT = {}
"""An empty dictionary."""
CRLF = "\r\n"
"""The carriage return and line feed characters."""
LF = "\n"
"""The line feed character."""
def parse_env(
var_name: str,
default_value: str | None = None,
type_cast=str,
convert_to_list=False,
list_split_char=Constants.SPACE_STRING,
) -> Any | list[Any]:
"""
Parse an environment variable and return the value.
Args:
var_name (str): The name of the environment variable.
default_value (str | None): The default value to use if the environment variable is not set. Defaults to None.
type_cast (str): The type to cast the value to.
convert_to_list (bool): Whether to convert the value to a list.
list_split_char (str): The character to split the list on.
Returns:
(Any | list[Any]) The parsed value, either as a single value or a list. The type of the returned single
value or individual elements in the list depends on the supplied type_cast parameter.
"""
if os.getenv(var_name) is None and default_value is None:
raise ValueError(
f"Environment variable {var_name} does not exist and a default value has not been provided."
)
parsed_value = None
if type_cast is bool:
parsed_value = (
os.getenv(var_name, default_value).lower() in Constants.TRUE_VALUES_LIST
)
else:
parsed_value = os.getenv(var_name, default_value)
value: Any | list[Any] = (
type_cast(parsed_value)
if not convert_to_list
else [type_cast(v) for v in parsed_value.split(list_split_char)]
)
return value
|