5

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)?

Steve Crook
  • 1,013
  • 2
  • 13
  • 22

1 Answers1

4

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)
silvado
  • 17,202
  • 2
  • 30
  • 46
  • Thanks. Using this solution, is there any way to pass the configfile variable to the config parser? – Steve Crook Jan 06 '12 at 13:04
  • You would usually use optparse or argparse to let the user choose a config file. If the option and argument parsing is also done in the config module, this should be straightforward (but feel free to extend your question if you encounter problems). Otherwise it depends very much on your specific program structure. – silvado Jan 06 '12 at 14:00
  • That solved it, thanks! The trick was to put optparse and ConfigParser in the same module. – Steve Crook Jan 06 '12 at 14:45