Tuesday, May 12, 2009

Unexpected behavior of python's ConfigParser

While working on some python code today I ran into some scoping issues that involved ConfigParser. The issue that made the process of finding and fixing the issue in the code harder is an unexpected behavior (on my end at least).

The situation is like this. My script relies on a configuration file that resides in the same directory as my script. For example sake let's call this file example.conf. During the execution of my script however, the directory scope of my script is no longer at my script main directory, so when it tries to find example.conf again it fails. This however is the part that put me off. The part that put me off is the fact that the error coming from ConfigParser is not really descriptive.

Take this example for example:

">>> config_file = 'does_not_exist_stuff.conf'
>>> config_parser = SafeConfigParser()
>>> config_parser.read(config_file)
[] <------------- shouldn't this part shot up some error messages?
>>> config_parser.get('config1','test_config')
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib64/python2.6/ConfigParser.py", line 531, in get
raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'config1'"

The thing I am trying to say here is when I try to feed SafeConfigParser a config file that does not exist should it complain? I understand that the onus should be on my code to check whether or not the config file exists but then an error saying "No section:" does not really help too much in finding the error fast. I am writing this post just hoping some one would chip in and show me if the way I am using ConfigParser is wrong or something if not I am considering writing a patch for ConfigParser.

On the other hand I found another Python configuration parser:http://pyfig.alecwh.com/. Going to look at this later on.
Post a Comment