I'm using Python's ConfigParser to create a configuration file. I want to check if a section has a particular option defined and, if it does, get the value. If the option isn't defined, I just want to continue without any special behavior. There seem to be two ways of doing this.
if config.has_option('Options', 'myoption'):
OPTION = config.get('Options', 'myoption')
Or:
try:
OPTION = config.get('Options', 'myoption')
except ConfigParser.NoOptionError:
pass
Is one method preferred over the other? The if
involves less lines, but I've occasionally read that try
/except
is considered more pythonic in many cases.