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

1"""

2 Loads loaders based on Python version.

3"""

4

5 import typing

6

7# tomli used for every Python version now.

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

9 from .register import LOADERS, T_loader, register_loader

10

11

12@typing.overload

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

14 """

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

16 """

17

18

19@typing.overload

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

21 """

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

23 """

24

25

26@typing.overload

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

28 """

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

30 """

31

32

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

34 """

35 Get the right loader for a specific extension.

36 """

37 extension = extension.removeprefix(".")

38

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

40 return loader

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

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

43 else:

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

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

46

47

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