Skip to content

Instantly share code, notes, and snippets.

@yakreved
Created July 25, 2019 13:15
Show Gist options
  • Save yakreved/4b5e0e24eb03482195a4cd69c8d82536 to your computer and use it in GitHub Desktop.
Save yakreved/4b5e0e24eb03482195a4cd69c8d82536 to your computer and use it in GitHub Desktop.
Convert .ini file to python3 config class. One of the answers to question: how to manage configs for python scripts.
import configparser
import os
import re
class Config:
MAX_THREADS = 5
MAX_FILE_SIZE = 2**30
#Other default options
@staticmethod
def load_from_ini(ini_file: str = 'config.ini'):
if not os.path.exists(ini_file):
ini_file = os.path.join(os.path.dirname(os.path.abspath(__file__)),ini_file)
if not os.path.exists(ini_file):
raise Exception("There is no file {}. Can not read configuration.".format(ini_file))
ini = configparser.ConfigParser(interpolation = configparser.ExtendedInterpolation())
ini.read_file(open(ini_file, 'r'))
print("Loading config from ini file: " + str(ini_file))
new_config = Config()
for section in ini.items():
for option in section[1]:
default_value = new_config.__getattribute__(option.upper())
if type(default_value) is int:
try:
new_config.__setattr__(option.upper(), ini.getint(section[0], option))
except:
new_value = eval(ini.get(section[0], option).split(';')[0])
new_config.__setattr__(option.upper(), new_value)
elif type(default_value) is float:
try:
new_config.__setattr__(option.upper(), ini.getfloat(section[0], option))
except:
new_value = eval(ini.get(section[0], option).split(';')[0])
new_config.__setattr__(option.upper(), new_value)
else:
new_config.__setattr__(option.upper(), ini.get(section[0], option))
new_config.validate()
return new_config
def validate(self):
#some validations
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment