Skip to content

Instantly share code, notes, and snippets.

@tux-00
Created August 20, 2018 18:20
Show Gist options
  • Save tux-00/6093bfe1b5eef3049a7da493f312c77d to your computer and use it in GitHub Desktop.
Save tux-00/6093bfe1b5eef3049a7da493f312c77d to your computer and use it in GitHub Desktop.

Revisions

  1. tux-00 created this gist Aug 20, 2018.
    33 changes: 33 additions & 0 deletions configparser_to_dataclasses.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    import configparser
    from dataclasses import dataclass


    @dataclass
    class Sections:
    raw_sections: dict

    def __post_init__(self):
    for section_key, section_value in self.raw_sections.items():
    setattr(self, section_key, SectionContent(section_value.items()))

    @dataclass
    class SectionContent:
    raw_section_content: dict

    def __post_init__(self):
    for section_content_k, section_content_v in self.raw_section_content:
    setattr(self, section_content_k, section_content_v)

    class Config(Sections):
    def __init__(self, raw_config_parser):
    Sections.__init__(self, raw_config_parser)


    conf = configparser.ConfigParser()
    conf.read('some_config_file.conf')

    new_config = Config(conf)

    # [mysection]
    # mykey = 1
    print(new_config.mysection.mykey) # output: 1