Coverage for /var/devmt/py/utils4_1.8.0/utils4/config.py: 100%

22 statements  

« prev     ^ index     » next       coverage.py v7.6.9, created at 2025-08-26 21:39 +0100

1# -*- coding: utf-8 -*- 

2""" 

3:Purpose: Small helper module designed to load a program's JSON-based 

4 config file. 

5 

6:Developer: J Berendt 

7:Email: support@s3dev.uk 

8 

9:Comments: n/a 

10 

11:Example: 

12 To load a program's JSON-based config file:: 

13 

14 >>> from utils4 import config 

15 

16 >>> cfg = config.loadconfig() 

17 >>> my_param = cfg['my_param'] 

18 

19""" 

20 

21import os 

22import sys 

23import json 

24from utils4.dict2obj import Dict2Obj 

25 

26 

27def loadconfig(filename: str='config.json', return_as_obj: bool=False): 

28 """Load a program's JSON config file and return it as a dict or object. 

29 

30 Args: 

31 filename (str, optional): File name or (preferably) the 

32 **explicit** full file path path of the JSON config file to 

33 be loaded. Defaults to 'config.json'. 

34 return_as_object (bool, optional): If True, the dictionary is 

35 converted into an object, where the dictionary key/values 

36 are object attribute/values. Defaults to False. 

37 

38 :Design: 

39 By default, this function will search the program's directory 

40 for a file named ``config.json``. If the config file lives 

41 somewhere else, or you're using an IDE to develop, the safest 

42 option is to **explicitly define the path to the config file**. 

43 

44 If a path is found in the passed parameter, this path is used, 

45 and the function does not have to try and work out where the 

46 config file lives. 

47 

48 The ``return_as_obj`` parameter tells the function to convert 

49 and return the JSON file into an object, rather than a 

50 dictionary. This enables you to access the values from object 

51 attributes, rather than from dictionary keys. See use option 2. 

52 

53 :Assumptions: 

54 * The config file is a JSON file. 

55 * The config file lives in the program directory. 

56 

57 :Examples: 

58 

59 Option 1: Return the config file as a **dict**:: 

60 

61 >>> from utils4 import config 

62 

63 >>> cfg = config.loadconfig() 

64 >>> my_param = cfg['my_param'] 

65 

66 

67 Option 2: Return the config file as an **object**:: 

68 

69 >>> from utils4 import config 

70 

71 >>> cfg = config.loadconfig(return_as_object=True) 

72 >>> my_param = cfg.my_param 

73 

74 """ 

75 # Filename only. 

76 if os.path.dirname(filename) == '': 

77 progdir = os.path.dirname(os.path.realpath(sys.argv[0])) 

78 path_base = progdir if sys.argv[0] != '' else os.getcwd() 

79 fullpath = os.path.join(path_base, filename) 

80 # Full path. 

81 else: 

82 fullpath = filename 

83 if _file_exists(fullpath=fullpath): 

84 if return_as_obj: 

85 return Dict2Obj(source='json', filepath=fullpath) 

86 return _fromjson(filepath=fullpath) 

87 return None # pragma: nocover (unreachable due to raised IOError) 

88 

89def _file_exists(fullpath: str) -> bool: 

90 """Test if the requested config file exists. 

91 

92 Args: 

93 fullpath (str): Full path to the file being tested. 

94 

95 Raises: 

96 IOError: If the file does not exist. 

97 

98 Returns: 

99 bool: True of the file exists, otherwise False. 

100 

101 """ 

102 exists = os.path.exists(fullpath) 

103 if not exists: 

104 raise IOError(f'The config file ({fullpath}) could not be found.') 

105 return exists 

106 

107def _fromjson(filepath: str) -> dict: 

108 """Extract values from the JSON file. 

109 

110 Args: 

111 filepath (str): Full path to the file to be read. 

112 

113 Returns: 

114 dict: JSON file content as a dictionary. 

115 

116 """ 

117 with open(filepath, 'r', encoding='utf-8') as f: 

118 return json.load(f)