Search code examples
pythonpython-moduleconfigparser

Python ConfigParser - usage across modules


I'm trying to understand the best way to implement Python's ConfigParser so that elements are accessible to multiple program modules. I'm using:-

import ConfigParser
import os.path

config = ConfigParser.RawConfigParser()

config.add_section('paths')
homedir = os.path.expanduser('~')
config.set('paths', 'user', os.path.join(homedir, 'users'))
[snip]
config.read(configfile)

In the last line the configfile variable is referenced. This has to be passed to the Config module so the user can override a default config file. How should I implement this in a module/class in such a manner that other modules can use config.get(spam, eggs)?


Solution

  • Let's say the code you have written in your question is inside a module configmodule.py. Then other modules get access to it in the following way:

    from configmodule import config
    config.get(spam, eggs)