Skip to content

Instantly share code, notes, and snippets.

@danila-schelkov
Last active December 17, 2022 13:09
Show Gist options
  • Save danila-schelkov/4a70f376d33567091a0a6a68ffc1aeb7 to your computer and use it in GitHub Desktop.
Save danila-schelkov/4a70f376d33567091a0a6a68ffc1aeb7 to your computer and use it in GitHub Desktop.
A simple config class, which is wrapping default configparser
# A simple config class, which is wrapping default configparser
# https://gist.github.com/Vorono4ka/4a70f376d33567091a0a6a68ffc1aeb7
import abc
import configparser
import typing
class Config(abc.ABC):
def __init__(self):
self._parser = configparser.ConfigParser()
self.filename: str or None = None
def load(self):
"""Loads properties from .ini file to class fields.
:return:
"""
try:
self._parser.read(self.filename)
self._sync_fields()
except configparser.NoOptionError:
self.save()
def save(self):
"""Saves class fields to .ini file.
:return:
"""
self._sync_properties()
self._parser.write(open(self.filename, 'w'))
@abc.abstractmethod
def _sync_fields(self) -> None:
"""Assigns properties to fields.
:return:
"""
@abc.abstractmethod
def _sync_properties(self) -> None:
"""Dumps fields to properties.
:return:
"""
def get_property(self,
section: str,
option: str,
default_value: typing.Any = None,
cast_type: typing.Type = None) -> typing.Any:
"""Returns property from the config.
:param section: name of config section (e.g. DEFAULT)
:param option: name of option in the section
:param default_value: value that is set if property is empty (by default is None)
:param cast_type: class for casting the value (e.g. int(value) if int)
:return:
"""
value = self._parser.get(section, option)
if value is None or value == '':
return default_value
if cast_type is not None:
return cast_type(value)
return value
def set_property(self, section: str, option: str, value: typing.Any) -> None:
"""Sets property in the config.
:param section: name of config section (e.g. DEFAULT)
:param option: name of option in the section
:param value: value to set in the property
:return:
"""
if not self._parser.has_section(section) and section != 'DEFAULT':
self._parser.add_section(section)
if value is None:
value = ''
self._parser.set(section, option, str(value))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment