python-3.xinidecouplingpython-decouple

Parse .ini sections with python-decouple


Documentation has a paradigm where the only section is called settings This seems to be the default namespace for python-decouple thus if you have:

[settings]
DEBUG=True

you can parse the config with:

from decouple import config
DEBUG = config('DEBUG', default=False, cast=bool)  # no section argument

But what if we have custom sections like:

[sectionA]
DEBUG=True

[sectionB]
foo="bar"

?

I know that one can easily use ConfigParser to parse custom sections, like so:

config_parser.get('sectionA', 'DEBUG')   # the corresponding call in ConfigParser

but I was wondering how it's done through python-decouple since it also supports .ini files


Solution

  • section seems to be hardcoded as a class attribute in the code, thus I suppose that there isn't any clean, parameterized solution to this issue.

    class RepositoryIni(RepositoryEmpty):
        """
        Retrieves option keys from .ini files.
        """
        SECTION = 'settings'
    
        def __init__(self, source):
            self.parser = ConfigParser()
            with open(source) as file_:
                self.parser.readfp(file_)
    
        def __contains__(self, key):
            return (key in os.environ or
                    self.parser.has_option(self.SECTION, key))
    
        def __getitem__(self, key):
            return self.parser.get(self.SECTION, key)