32

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.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
user1272534
  • 991
  • 2
  • 11
  • 17

1 Answers1

28

The choice between try/except and if-condition is a fuzzy line.

  1. If you expect the exception to be quite rare, use try/except as it more closely models thinking
  2. Conversely, "expected" exceptions like a configuration item missing, are part of the normal flow of control and the code should reflect that.

There is no clearly superior choice, but it sounds like you've got a case of (2) so I'd opt for if/then. This completely ignores aspects of Easier to ask Forgiveness Than Permission and the relative efficiencies of the structures.

msw
  • 42,753
  • 9
  • 87
  • 112
  • That makes sense. I'll stick with the `if` method. I would be curious to know if one way is faster than the other. The `if` method calls the ConfigParser object twice, where the `try` method only does it once. I don't know if that might have an impact. – user1272534 Jul 17 '12 at 18:59