Home > Software design >  ConfigParser read Booleans / String / Integer at the same time with Python
ConfigParser read Booleans / String / Integer at the same time with Python

Time:02-22

Here is my config.ini:

[LOADER]
text = example text
size = 17
settings = None
run = False

But when I print it, using:

config = ConfigParser()
config.read('config.ini')
print(config._sections['LOADER'])

I get this:

{'text': 'example text', 'size': '17', 'settings': 'None', 'run': 'False'}

But I want this:

{'text': 'example text', 'size': 17, 'settings': None, 'run': False}

I tried several methods with ConfigParser, I tried to edit the list to replace the strings in boolean, but I really can't do it, thanks.

CodePudding user response:

A recursive function could be good for this:

def load_it(obj):
    if isinstance(obj, dict):
        return {k: load_it(v) for k, v in obj.items()}
    if isinstance(obj, list):
        return [load_it(elem) for elem in obj]
    if isinstance(obj, str):
        if obj == 'None':
            return None
        if obj.isnumeric():
            return int(obj)
        if obj.replace('.', '', 1).isnumeric():
            return float(obj)
        if obj.upper() in ('TRUE', 'FALSE', 'T', 'F'):
            return obj.upper() in ('TRUE', 'T')

    return obj


data = load_it({'text': 'example text', 'size': '17', 'settings': 'None', 'run': 'False'})
print(data)

Output:

{'text': 'example text', 'size': 17, 'settings': None, 'run': False}
  • Related