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
« 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.
6:Developer: J Berendt
7:Email: support@s3dev.uk
9:Comments: n/a
11:Example:
12 To load a program's JSON-based config file::
14 >>> from utils4 import config
16 >>> cfg = config.loadconfig()
17 >>> my_param = cfg['my_param']
19"""
21import os
22import sys
23import json
24from utils4.dict2obj import Dict2Obj
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.
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.
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**.
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.
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.
53 :Assumptions:
54 * The config file is a JSON file.
55 * The config file lives in the program directory.
57 :Examples:
59 Option 1: Return the config file as a **dict**::
61 >>> from utils4 import config
63 >>> cfg = config.loadconfig()
64 >>> my_param = cfg['my_param']
67 Option 2: Return the config file as an **object**::
69 >>> from utils4 import config
71 >>> cfg = config.loadconfig(return_as_object=True)
72 >>> my_param = cfg.my_param
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)
89def _file_exists(fullpath: str) -> bool:
90 """Test if the requested config file exists.
92 Args:
93 fullpath (str): Full path to the file being tested.
95 Raises:
96 IOError: If the file does not exist.
98 Returns:
99 bool: True of the file exists, otherwise False.
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
107def _fromjson(filepath: str) -> dict:
108 """Extract values from the JSON file.
110 Args:
111 filepath (str): Full path to the file to be read.
113 Returns:
114 dict: JSON file content as a dictionary.
116 """
117 with open(filepath, 'r', encoding='utf-8') as f:
118 return json.load(f)