Coverage for src/configuraptor/abs.py: 100%
24 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-11-09 11:17 +0100
« prev ^ index » next coverage.py v7.2.7, created at 2023-11-09 11:17 +0100
1"""
2Contains the Abstract config class shared by TypedConfig and BinaryConfig.
3"""
4import os
5import types
6import typing
7from pathlib import Path
9import dotenv
11# T is a reusable typevar
12T = typing.TypeVar("T")
13# t_typelike is anything that can be type hinted
14T_typelike: typing.TypeAlias = type | types.UnionType # | typing.Union
15# t_data is anything that can be fed to _load_data
16T_data_types = str | Path | bytes | dict[str, typing.Any] | None
17T_data = T_data_types | list[T_data_types]
19# c = a config class instance, can be any (user-defined) class
20C = typing.TypeVar("C")
21# type c is a config class
22Type_C = typing.Type[C]
25class AbstractTypedConfig:
26 """
27 These functions only exist on the class, not on instances.
28 """
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.
43 SomeClass.load(data, ...) = load_into(SomeClass, data, ...).
44 """
45 from .core import load_into
47 return load_into(
48 cls, data, key=key, init=init, strict=strict, lower_keys=lower_keys, convert_types=convert_types
49 )
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.
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.
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
79 if load_dotenv:
80 dotenv_path = load_dotenv if isinstance(load_dotenv, str) else None
81 dotenv.load_dotenv(dotenv_path)
83 data = {**os.environ}
85 return load_into(cls, data, lower_keys=True, init=init, strict=strict, convert_types=convert_types)