Coverage for /home/runner/.local/share/hatch/env/virtual/importnb/KA2AwMZG/test.stdlib/lib/python3.9/site-packages/importnb/loaders.py: 92%

1 from .loader import Loader, SourceModule 1 ctx 1a

2 from dataclasses import dataclass, field 1 ctx 1a

3 from types import ModuleType 1 ctx 1a

4

5

6 class DataModule(SourceModule): 1 ctx 1a

7 def _repr_json_(self): 1 ctx 1a

8 return self.data, dict(root=repr(self), expanded=False)

9

10

11@dataclass 1 ctx 1a

12 class DataStreamLoader(Loader): 1 ctx 1a

13 """an import loader for data streams"""

14

15 module_type: ModuleType = field(default=DataModule) 1 ctx 1a

16

17 def exec_module(self, module): 1 ctx 1a

18 with open(module.__file__, "rb") as file: 1 ctx 1a

19 module.data = self.get_data_loader()(file) 1 ctx 1a

20 return module 1 ctx 1a

21

22 def get_data_loader(self): 1 ctx 1a

23 raise NotImplementedError("load_data not implemented.")

24

25

26@dataclass 1 ctx 1a

27 class Json(DataStreamLoader): 1 ctx 1a

28 """an import loader for json files"""

29

30 extensions: tuple = field(default_factory=[".json"].copy) 1 ctx 1a

31

32 def get_data_loader(self): 1 ctx 1a

33 from json import load 1 ctx 1a

34

35 return load 1 ctx 1a

36

37

38@dataclass 1 ctx 1a

39 class Yaml(DataStreamLoader): 1 ctx 1a

40 """an import loader for yml and yaml"""

41

42 extensions: tuple = field(default_factory=[".yml", ".yaml"].copy) 1 ctx 1a

43

44 def get_data_loader(self): 1 ctx 1a

45 try: 1 ctx 1a

46 from ruamel.yaml import YAML 1 ctx 1a

47

48 yaml = YAML(typ="safe", pure=True) 1 ctx 1a

49 safe_load = yaml.load 1 ctx 1a

50 except ModuleNotFoundError:

51 from yaml import safe_load

52 # probably want an error message about how to fix this if we cant find yamls

53 return safe_load 1 ctx 1a

54

55

56@dataclass 1 ctx 1a

57 class Toml(DataStreamLoader): 1 ctx 1a

58 """an import loader for toml"""

59

60 extensions: tuple = field(default_factory=[".toml"].copy) 1 ctx 1a

61

62 def get_data_loader(self): 1 ctx 1a

63 try: 1 ctx 1a

64 from tomllib import load 1 ctx 1a

65 except ModuleNotFoundError: 1 ctx 1a

66 from tomli import load 1 ctx 1a

67 return load 1 ctx 1a