Coverage for src/configuraptor/loaders/__init__.py: 100%

1"""

2 Loads loaders based on Python version.

3"""

4 import typing

5

6# tomli used for every Python version now.

7 from .loaders_shared import dotenv, ini, json, toml, yaml

8 from .register import LOADERS, T_loader, register_loader

9

10

11@typing.overload

12 def get(extension: str, default: T_loader) -> T_loader:

13 """

14 When setting a loader function as default, a loader will always be returned.

15 """

16

17

18@typing.overload

19 def get(extension: str, default: None) -> T_loader | None:

20 """

21 When setting None as the default, either a loader or none will be returned.

22 """

23

24

25@typing.overload

26 def get(extension: str, default: typing.Type[Exception] = ValueError) -> T_loader:

27 """

28 When not setting a default, a loader will be returned or an exception will be thrown.

29 """

30

31

32 def get(extension: str, default: T_loader | None | typing.Type[Exception] = ValueError) -> T_loader | None:

33 """

34 Get the right loader for a specific extension.

35 """

36 extension = extension.removeprefix(".")

37

38 if loader := LOADERS.get(extension):

39 return loader

40 elif default and isinstance(default, type) and issubclass(default, Exception):

41 raise default(f"Invalid extension {extension}")

42 else:

43 # can't be an exeption because the above clause makes sure of that. So tell mypy with cast:

44 return typing.cast(typing.Optional[T_loader], default)

45

46

47 __all__ = ["get", "toml", "json", "yaml", "dotenv", "ini", "register_loader"]