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.
Read and parse one configuration file, given as a file object. Read configuration from a given string. Read configuration from a dictionary. Keys are section names, values are dictionaries with keys and values that should be present in the section.
configparser comes from Python 3 and as such it works well with Unicode.
The choice between try/except and if-condition is a fuzzy line.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With