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

18 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-19 17:38 +0200

1""" 

2Logic for the TypedConfig inheritable class. 

3""" 

4 

5import typing 

6 

7from .core import T_data, all_annotations, check_type, is_optional, load_into 

8from .errors import ConfigErrorExtraKey, ConfigErrorInvalidType 

9 

10C = typing.TypeVar("C", bound=typing.Any) 

11 

12 

13class TypedConfig: 

14 """ 

15 Can be used instead of load_into. 

16 """ 

17 

18 @classmethod 

19 def load( 

20 cls: typing.Type[C], data: T_data, key: str = None, init: dict[str, typing.Any] = None, strict: bool = True 

21 ) -> C: 

22 """ 

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

24 

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

26 """ 

27 return load_into(cls, data, key=key, init=init, strict=strict) 

28 

29 def update(self, strict: bool = True, allow_none: bool = False, **values: typing.Any): 

30 annotations = all_annotations(self.__class__) 

31 

32 for key, value in values.items(): 

33 if value is None and not allow_none: 

34 continue 

35 

36 if strict and key not in annotations: 

37 raise ConfigErrorExtraKey(cls=self.__class__, key=key, value=value) 

38 

39 if strict and not check_type(value, annotations[key]) and not (value is None and allow_none): 

40 raise ConfigErrorInvalidType(expected_type=annotations[key], key=key, value=value) 

41 

42 setattr(self, key, value)