Created
August 20, 2018 18:20
-
-
Save tux-00/6093bfe1b5eef3049a7da493f312c77d to your computer and use it in GitHub Desktop.
Converts python config parser to dataclasses (easier access)
This file contains 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 | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment