The pyconfigreader API Reference

ConfigReader

class pyconfigreader.reader.ConfigReader(filename='settings.ini', file_object=None, case_sensitive=False)[source]

A simple configuration reader class for performing basic config file operations including reading, setting and searching for values.

It is preferred that the value of filename be an absolute path. If filename is not an absolute path, then the configuration (ini) file will be saved at the Current Working directory (the value of getcwd()).

If file_object is an open file then filename shall point to it’s path

Usage:
>>> from pyconfigreader import ConfigReader
>>> config = ConfigReader(filename='config.ini')
>>> config.set('version', '2')  # Saved to section `main`
>>> config.set('Key', 'Value', section='Section')   # Creates a section `Section` on-the-fly
>>> config.set('name', 'main')
>>> name = config.get('name')
>>> default_section = config.get_items('main')
>>> config.close(save=True)  # Save on close
>>> # Or explicitly call
>>> # config.save()
>>> # config.close()
Parameters:
  • filename (str) – The name of the final config file. Defaults to settings.ini.
  • file_object (Union[_io.TextIOWrapper, TextIO, io.StringIO]) – A file-like object opened in mode w+. Defaults to a new StringIO object.
  • case_sensitive (bool) – Determines whether keys should retain their alphabetic cases or be converted to lowercase. Defaults to True.
Variables:
  • filename (str) – Path to the ini file
  • sections (OrderedDict) – The sections in the ini file
close(save=False)[source]

Close the file-like object

If save is True, the contents are written to the file on disk first .

Caution

Not closing the object might have it update any other instance created later on.

Parameters:save (bool) – write changes to disk
get(key, section=None, evaluate=True, default=None, default_commit=False)[source]

Return the value of the provided key

Returns None if the key does not exist. The section defaults to main if not provided. If the value of key does not exist and default is not None, the value of default is returned. And if default_commit is True, then the value of default is written to file on disk immediately.

If evaluate is True, the returned values are evaluated to Python data types int, float and boolean.

Changed in version 0.5.0: Expands shell variables while leaving unknown ones unchanged.

Changed in version 0.4.0: Raises NoOptionError when a non-existent key is fetched.

Changed in version 0.7.0: Replaced NoOptionError with MissingOptionError for py2.7 compatibility.

Parameters:
  • key (str) – The key name
  • section (str) – The name of the section, defaults to main
  • evaluate (bool) – Determines whether to evaluate the acquired values into Python literals
  • default (str) – The value to return if the key is not found
  • default_commit (bool) – Also write the value of default to ini file on disk
Raises:

MissingOptionError – When the key whose value is being fetched does not exist in the section

Returns:

The value that is mapped to the key or None if not found

Return type:

Union[str, int, float, bool, None]

get_items(section)[source]

Returns an OrderedDict of items (keys and their values) from a section

The values are evaluated into Python literals, if possible.

Returns None if section is not found.

Parameters:section (str) – The section from which items (key-value pairs) are to be read from
Returns:An dictionary of keys and their values
Return type:Union[OrderedDict, None]
load_env(environment=None, prefix='', commit=False)[source]

Load alphanumeric environment variables into configuration file

Default environment is provided by os.environ.

The prefix is used to filter keys in the environment which start with the value. This is an adaptive mode to to_env() which prepends the section to the key before loading it to the environment.

Parameters:
  • environment (os._Environ) – the environment to load from
  • prefix (str) – only keys which are prefixed with this string are loaded
  • commit (bool) – write to disk immediately
Returns:

nothing

load_json(filename='settings.json', section=None, identifier='@', encoding=None)[source]

Load config from JSON file

For instance:

# With ``identifier`` as '@',
'@counters': {
    'start': {
        'name': 'scrollers',
        'count': 15
    },
    'end': {
        'name': 'keepers',
        'count': 5
    }
}

# will result in a section
[counters]
start = {'name': 'scrollers', 'count': 15}
end = {'name': 'keepers', 'count': 5}
Parameters:
  • filename (str) – name of the JSON file
  • section (str) – config section name to save key and values by default
  • identifier (str) – the prefix that identifies a key as a section name
  • encoding (str) – encoding of the JSON file
Returns:

nothing

reload()[source]

Reload the configuration file into memory

remove_key(*args, **kwargs)[source]

Same as calling remove_option()

This is just in case one is used to the key-value term pair

remove_option(key, section=None, commit=False)[source]

Remove an option from the configuration file

Parameters:
  • key (str) – The key name
  • section (str) – The section name, defaults to main
  • commit (bool) – Also write changes to ini file on disk
Returns:

Nothing

Return type:

None

remove_section(section)[source]

Remove a section from the configuration file whilst leaving the others intact

Parameters:section (str) – The name of the section to remove
Returns:Nothing
Return type:None
save()[source]

Write to file on disk

Write the contents to a file on the disk.

This does not close the file. You have to explicitly call close() to do so.

Returns:Nothing
Return type:None
search(value, case_sensitive=True, exact_match=False, threshold=0.36)[source]

Returns a tuple containing the key, value and section of the best match found, else empty tuple

If exact_match is False, checks if there exists a value that matches above the threshold value. In this case, case_sensitive is ignored.

If exact_match is True then the value of case_sensitive matters.

The threshold value should be 0, 1 or any value between 0 and 1. The higher the value the better the accuracy.

Changed in version 0.5.0: Returns all the matches found

Parameters:
  • value (str) – The value to search for in the config file
  • case_sensitive (bool) – Match case during search or not
  • exact_match (bool) – Match exact value
  • threshold (float) – The value of matching at which a match can be considered as satisfactory
Returns:

A tuple of the key, value and section of the results, else None

Return type:

Union[tuple, None]

set(key, value, section=None, commit=False)[source]

Sets the value of key to the provided value

Section defaults to main if not provided. The section is created if it does not exist.

When commit is True, all changes up to the current one are written to disk.

Parameters:
  • key (str) – The key name
  • value (str) – The value to which the key is mapped
  • section (str) – The name of the section, defaults to main
  • commit (bool) – Also write changes to ini file on disk
Return type:

None

set_many(data, section=None, commit=False)[source]

Update multiple keys

This is a convenience method that is much faster to utilise than using set() for every key.

New in version 0.6.0.

Parameters:
  • data (dict) – Data to update in the configuration file
  • section (str) – The section to update with the data
  • commit (bool) – If True, write, instantly, all change to file. Defaults to False.
show(output=True)[source]

Prints out all the sections and returns a dictionary of the same

Parameters:output (bool) – Print to std.out a string representation of the file contents, defaults to True
Returns:A dictionary mapping of sections, options and values
Return type:dict
to_env(environment=None, prepend=True)[source]

Export contents to an environment

Exports by default to os.environ.

By default, the section and option would be capitalised and joined by an underscore to form the key - as an attempt at avoid collision with (any) environment variables.

Usage:
>>> reader = ConfigReader()
>>> reader.show(output=False)
OrderedDict([('main', OrderedDict([('reader', 'configreader')]))])
>>> reader.to_env()
>>> import os
>>> os.environ['MAIN_READER']
'configreader'
>>> reader.to_env(prepend=False)
>>> os.environ['READER']
'configreader'
>>> reader.close()
Parameters:
  • environment (os.environ) – An environment to export to
  • prepend (bool) – Prepend the section name to the key
Returns:

Nothing

Return type:

None

to_json(file_object=None)[source]

Export config to JSON

If a file_object is given, it is exported to it else returned as called

Usage:
>>> # Example
>>> reader = ConfigReader()
>>> with open('config.json', 'w') as f:
...     reader.to_json(f)
>>> # or
>>> from io import StringIO
>>> s_io = StringIO()
>>> reader.to_json(s_io)
>>> reader.close()
Parameters:file_object (io.TextIO) – A file-like object for the JSON content
Returns:A string or the dumped JSON contents or nothing if file_object is provided
Return type:str or None

Exceptions

exception pyconfigreader.exceptions.MissingOptionError(option, section)[source]

Raised when a key cannot be found

This could be because the key does not exist in the section or the section does not exist at all

exception pyconfigreader.exceptions.ModeError[source]

Raised when the opened file is not in mode w+

exception pyconfigreader.exceptions.SectionNameNotAllowed[source]

Raised when a section of default variant is attempted to be created.

exception pyconfigreader.exceptions.ThresholdError[source]

Raised when the search threshold is not a float >=0.0 or <=1.0