|
1 | 1 | import os
|
2 | 2 | from typing import Any
|
3 | 3 |
|
4 |
| -from dotenv import load_dotenv |
| 4 | +from dotenv import find_dotenv, load_dotenv |
5 | 5 |
|
6 | 6 |
|
7 | 7 | class EnvironmentVariableGetter:
|
8 | 8 | @staticmethod
|
9 |
| - def get(name_of_variable: str, default_value: Any = None) -> str: |
| 9 | + def get(name_of_variable: str, default_value: Any = None) -> bool | str: |
10 | 10 | """
|
| 11 | + Gets the value of an environment variable. |
| 12 | +
|
| 13 | + The method attempts to retrieve the value of the provided environment variable. If the variable exists, it's |
| 14 | + retrieved and, if applicable, converted to a boolean. If the variable doesn't exist, an optional default value |
| 15 | + is returned. If neither the variable is set nor a default value is provided, it raises a RuntimeError. |
| 16 | + The method also processes and gives precedence to variables defined in an `.env.override` file. |
| 17 | +
|
11 | 18 | Args:
|
12 |
| - name_of_variable: The name of the environment variable to be retrieved. |
13 |
| - default_value: Optional; The default value to return if the environment variable is not set. |
| 19 | + name_of_variable (str): The name of the environment variable to query. |
| 20 | + default_value (Any, optional): The fallback value to return if the environment variable is not set. |
14 | 21 |
|
15 | 22 | Returns:
|
16 |
| - The value of the environment variable cast to a boolean if possible, otherwise returns its string value or the default value. |
| 23 | + bool | str: The retrieved environment variable value, either as a boolean (if applicable) or string. |
17 | 24 |
|
18 | 25 | Raises:
|
19 |
| - RuntimeError: If the environment variable is not set and no default value is provided. |
| 26 | + RuntimeError: If the specified environment variable is not found and no default value is provided. |
20 | 27 | """
|
21 | 28 | load_dotenv(override=True)
|
22 | 29 |
|
| 30 | + # Load variables from .env.override with higher priority |
| 31 | + load_dotenv(dotenv_path=find_dotenv(".env.override"), override=True) |
| 32 | + |
23 | 33 | try:
|
24 | 34 | value = os.environ[name_of_variable]
|
| 35 | + if value == "": |
| 36 | + raise KeyError() |
25 | 37 | return EnvironmentVariableGetter._cast_string_to_bool(value)
|
26 | 38 | except KeyError:
|
27 | 39 | if default_value is not None:
|
|
0 commit comments