Coverage for src/configuraptor/abs.py: 100%

1"""

2 Contains the Abstract config class shared by TypedConfig and BinaryConfig.

3"""

4 import os

5 import types

6 import typing

7 from pathlib import Path

8

9 import dotenv

10

11# T is a reusable typevar

12 T = typing.TypeVar("T")

13# t_typelike is anything that can be type hinted

14 T_typelike: typing.TypeAlias = type | types.UnionType # | typing.Union

15# t_data is anything that can be fed to _load_data

16 T_data_types = str | Path | bytes | dict[str, typing.Any] | None

17 T_data = T_data_types | list[T_data_types]

18

19# c = a config class instance, can be any (user-defined) class

20 C = typing.TypeVar("C")

21# type c is a config class

22 Type_C = typing.Type[C]

23

24

25 class AbstractTypedConfig:

26 """

27 These functions only exist on the class, not on instances.

28 """

29

30 @classmethod

31 def load(

32 cls: typing.Type[C],

33 data: T_data = None,

34 key: str = None,

35 init: dict[str, typing.Any] = None,

36 strict: bool = True,

37 lower_keys: bool = False,

38 convert_types: bool = False,

39 ) -> C:

40 """

41 Load a class' config values from the config file.

42

43 SomeClass.load(data, ...) = load_into(SomeClass, data, ...).

44 """

45 from .core import load_into

46

47 return load_into(

48 cls, data, key=key, init=init, strict=strict, lower_keys=lower_keys, convert_types=convert_types

49 )

50

51 @classmethod

52 def from_env(

53 cls: typing.Type[C],

54 load_dotenv: str | bool = False,

55 init: dict[str, typing.Any] = None,

56 strict: bool = True,

57 convert_types: bool = False,

58 ) -> C:

59 """

60 Create an instance of the typed config class by loading environment variables and initializing \

61 object attributes based on those values.

62

63 Args:

64 cls (typing.Type[C]): The class to create an instance of.

65 init (dict[str, typing.Any], optional): Additional initialization data to be used

66 in the object creation. Defaults to None.

67 strict (bool, optional): If True, raise an error if any required environment variable

68 is missing. Defaults to True.

69 convert_types (bool, optional): If True, attempt to convert environment variable values

70 to the appropriate Python types. Defaults to False.

71 load_dotenv (str | bool, optional): Path to a dotenv file or True to load the default

72 dotenv file. If False, no dotenv file will be loaded. Defaults to False.

73

74 Returns:

75 C: An instance of the class `C` with attributes initialized based on the environment variables.

76 """

77 from .core import load_into

78

79 if load_dotenv:

80 dotenv_path = load_dotenv if isinstance(load_dotenv, str) else None

81 dotenv.load_dotenv(dotenv_path)

82

83 data = {**os.environ}

84

85 return load_into(cls, data, lower_keys=True, init=init, strict=strict, convert_types=convert_types)