Tim provided a correct-looking answer, albeit somewhat
complex, as it doesn't reuse the logic in the ConfigParser.

It didn't start out very complex, but it was so easy to make it a bit more robust with such a scant few lines of code that I went ahead. The original just looked like

  options = {}
  for line in file("simple.ini"):
    line = line.rstrip("\r\n")
    if '=' in line:
      key, value = line.split('=', 1)
      options[key] = value

which is about as simple as it gets. However, this doesn't handle commented lines nicely (OP didn't mention whether there were comments), the keys are case-sensitive (often not a desired behavior), and leading/trailing whitespace for both the key & value are preserved (also rarely desired), and in the event of a malformed line (with no '='), it fails indistinguishably from a blank line and silently.

The big advantages given by the ConfigParser hack (tacking on a fake section-header)

- it provides the convenience methods for pulling out an int/float/bool in addition to a string

- possibly handles continued lines (I saw something in the source referring to this)

- it handles merging config files from multiple sources (such as /etc/foo_rc then merged with ~/.foo_rc)

- encourages use-of and learning-about a standard library module

- and it handles string substitution if you want it.


It also provides for defaults, but the standard dict has the get() method to allow for defaults, and the library offers the default-dict.

<ramble>
As a personal aside, it does bug me that the ConfigParser .get*() methods don't afford an optional default value like dict.get() in the event you want a value that may be present in the config file but isn't in the [DEFAULT] section when present raising a NoSectionError or NoOptionError. I.e. I'd like to be able to call

  cp.get('some_section', 'some_key', '42')

on an empty config.ini file and get back the "42" as if it existed in "some_section" rather than throwing an exception/error (and why the heck do these "exceptions" descend from Error rather than Exception? These aren't errors...they're exceptions)

</ramble>

-tkc




--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to