Created
July 25, 2019 13:14
-
-
Save yakreved/c05057cb3d33fbbf9a32805b5984b7a4 to your computer and use it in GitHub Desktop.
Convert .ini file to python3 config class.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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