config - Adds support for automatically reading an application’s config file

Library providing JSON-based config file loading functionality.

Purpose:

Small helper module designed to load a program’s JSON-based config file.

Platform:

Linux/Windows | Python 3.6+

Developer:

J Berendt

Email:

support@s3dev.uk

Comments:

n/a

Example:

To load a program’s JSON-based config file:

>>> from utils4 import config

>>> cfg = config.loadconfig()
>>> my_param = cfg['my_param']
config._file_exists(fullpath: str) bool[source]

Test if the requested config file exists.

Parameters:

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

Raises:

IOError – If the file does not exist.

Returns:

True of the file exists, otherwise False.

Return type:

bool

config._fromjson(filepath: str) dict[source]

Extract values from the JSON file.

Parameters:

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

Returns:

JSON file content as a dictionary.

Return type:

dict

config.loadconfig(filename: str = 'config.json', return_as_obj: bool = False)[source]

Load a program’s JSON config file and return it as a dict or object.

Parameters:
  • filename (str, optional) – File name or (preferably) the explicit full file path path of the JSON config file to be loaded. Defaults to ‘config.json’.

  • return_as_object (bool, optional) – If True, the dictionary is converted into an object, where the dictionary key/values are object attribute/values. Defaults to False.

Design:

By default, this function will search the program’s directory for a file named config.json. If the config file lives somewhere else, or you’re using an IDE to develop, the safest option is to explicitly define the path to the config file.

If a path is found in the passed parameter, this path is used, and the function does not have to try and work out where the config file lives.

The return_as_obj parameter tells the function to convert and return the JSON file into an object, rather than a dictionary. This enables you to access the values from object attributes, rather than from dictionary keys. See use option 2.

Assumptions:
  • The config file is a JSON file.

  • The config file lives in the program directory.

Examples:

Option 1: Return the config file as a dict:

>>> from utils4 import config

>>> cfg = config.loadconfig()
>>> my_param = cfg['my_param']

Option 2: Return the config file as an object:

>>> from utils4 import config

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