This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: configparser - add 'getDict' function
Type: enhancement Stage:
Components: Library (Lib) Versions: Python 3.3
process
Status: closed Resolution: works for me
Dependencies: Superseder:
Assigned To: lukasz.langa Nosy List: Michael.Müller, lukasz.langa, r.david.murray
Priority: normal Keywords:

Created on 2014-03-16 12:19 by Michael.Müller, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (3)
msg213721 - (view) Author: Michael Müller (Michael.Müller) Date: 2014-03-16 12:19
It would be nice to have a 'getDict' function in the configparser lib.

Adding that function would be simply

def getDict(self, *args):
        return dict([entry for entry in self.items(*args)])

inside the RawConfigParser class next to the other get* functions.
msg213723 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2014-03-16 13:24
How is this different from myconfig['section']?
msg213785 - (view) Author: Łukasz Langa (lukasz.langa) * (Python committer) Date: 2014-03-17 01:15
Michael, what you wish is already a part of configparser. Let's use this as an example:

>>> p = configparser.ConfigParser()
>>> p.read_string("""
... [one]
... opt=val
... [two]
... num=1
... str=bzz
... bool=true
... """)

When asking for a specific section, you get a SectionProxy object. It has a dict-like API but is not a dict:

>>> p['two']
<Section: two>
>>> isinstance(p['two'], dict)
False

The reason for that is two-fold: firstly this enables us to make changes made on a section object persistent within the main parser. Secondly, this enables us to add configparsser-specific functionality (like dynamic interpolation, type conversions, etc.):

>>> p['two']['num']
'1'
>>> p['two'].getint('num')
1
>>> p['two']['str'] = 'bool is %(bool)s'
>>> p['two']['str']
'bool is true'
>>> p['two']['bool'] = 'false'
>>> p['two']['str']
'bool is false'

Because the section proxy object follows the dict API very closely, it's trivial to convert a section to a dict:

>>> dict(p['two'])
{'str': 'bool is false', 'bool': 'false', 'num': '1'}

Note, however, that this sets in stone interpolations and doesn't provide built-in type conversions.
History
Date User Action Args
2022-04-11 14:58:00adminsetgithub: 65142
2014-03-17 01:15:49lukasz.langasetstatus: open -> closed
assignee: lukasz.langa
resolution: works for me
messages: + msg213785
2014-03-16 13:24:57r.david.murraysetnosy: + r.david.murray
messages: + msg213723
2014-03-16 12:19:11Michael.Müllercreate