I am learning programing by developing a script to automate tasks in Python. I need to code something that reads multiple sections with multiple variables from a configuration file and create a nested dictionary. The nested dictionary is the input of a class and use it allows me to create one object per section. The variables in each section give the attributes of my objects. The configuration file can contain a variable number of section and specific number of variables in each section. Configuration file is like this :
[SECTION_01]
name = 'name_01'
zone = 'zone_01'
size = 'size_01'
specific_to_SECTION_01 = ''
[SECTION_02]
name = 'name_02'
zone = 'zone_02'
size = 'size_02'
specific_to_SECTION_02 = ''
...
etc.
I get the nested dictionary I want and define it as an input of a class thanks to setattr() method.
import configparser
config = configparser.ConfigParser()
config.read("ini_file.ini")
class MyClass():
def __init__(self, dictionary)
for section in dictionary:
for k, v in dictionary[section].items()
setattr(self, k, v)
my_dict = {}
for section in config.sections():
if section.startwith('SECTION'):
my_dict[section] = {}
for key, value in config.items(section):
my_dict[section][key] = value
But then i would like to define my objects from the sections and define the attributes with a for loop, it returns an error about iterating through the dictionary class. By the way, I am not sure to know how to define well the attributes while I can't have a good definition for my loop.
obj_dict = MyClass(my_dict)
for sect in obj_dict:
obj_01_name = MyClass(my_dict).name
obj_01_zone = MyClass(my_dict).zone
...
This returns MyClass object is not iterable. I find some topic about adding the __iter__() method but I get this TypeError: iter() returned non-iterator of type MyClass(). I have found other topics about adding __next__() but I don't see how to integrate it.
Otherwise, I can loop directly through my_dict but when I try to instance MyClass() in the for loop, it gives me only the last section.