Search code examples
pythonwith-statementconfigparser

ConfigParser - get entire section as dict and set values


What I'd like to do (ideally) is use with with a dictionary to set an entire section of parameters at once. After some experimenting I came up with the following code, which raises AttributeError:

import configparser
import os

CONFIG_PATH = os.path.abspath(os.path.dirname(__file__)) + '/config.ini'
config = configparser.ConfigParser()
assert open(CONFIG_PATH)
config.read(CONFIG_PATH)

with dict(config.items('Settings')) as c:
    c['username'] = input('Enter username: ')

config.ini file:

[Settings]
username = ''

The traceback:

Traceback (most recent call last):
  File "test.py", line 9, in <module>
    with dict(config.items('Settings')) as c:
AttributeError: __enter__

I feel like I'm using configparser wrong here, but I'd like to write some beautiful code to set config.ini parameters.


Solution

  • You can't use a dictionary with with because a dict is not a context manager.

    with dict() as d:
        print d
    

    output:

    Traceback (most recent call last):
      File "Main.py", line 6, in <module>
        with dict() as d:
    AttributeError: __exit__
    

    https://paiza.io/projects/aPGRmOEmydbJL2ZeRtF-3A?language=python

    An object must define __enter__ and __exit__ in order to be used as a context manager.

    documentation: http://book.pythontips.com/en/latest/context_managers.html