Reputation: 2409
I am trying to write a try/except block that declares two variables that retrieve their values via ConfigParser
. The issue I am running into is that it is possible that one or both the values being declared may not be present under a particular section and should be set to None
in such a case. I am aware that I can simply add the values under to every config file, however, not all of the configs are consistent in section names which turns into a very tedious task.
Is there a better way to achieve the following try/except block without breaking them up into two separate ones?
try:
ports = getCfgStr(sectName, 'ports')
terminal = getCfgStr(sectName, 'terminals')
except KeyError:
# Need to set ports or terminal to None depending on which raised the KeyError
My workaround solution:
try:
ports = getCfgStr(sectName, 'ports')
except KeyError:
ports = None
try:
terminals = getCfgStr(sectName, 'terminals')
except KeyError:
terminals = None
Upvotes: 3
Views: 2323
Reputation: 6488
Interesting question!
How about this:
def lookup(param):
try:
return getCfgStr(sectName, param)
except KeyError:
return None
ports = lookup('ports')
terminal = lookup('terminals')
Upvotes: 4
Reputation: 15934
Maybe just make a function:
def get_or_default(name, default):
try:
result = getCfgStr(sectName, name)
return result
except KeyError:
return default
Call like this:
ports = get_or_default('ports', None)
However a better approach if you are using ConfigParser
would be to alter the getCfgStr
function to use the libraries way of doing this: https://docs.python.org/3.4/library/configparser.html#fallback-values
Upvotes: 0
Reputation: 134
Instead of using the anti-pattern of coding by exception, you could explicitly check if the option is present:
RawConfigParser.has_option(section, option)
If the given section exists, and contains the given option, return True; otherwise return False.
Upvotes: 0
Reputation: 5641
The best solution is to make your getCfgStr
function able to accept default values, which it will return if there is no such option in section. So your code will be like this:
ports = getCfgStr(sectName, 'ports', None)
terminal = getCfgStr(sectName, 'terminals', None)
If you have to use exceptions, your solution is OK.
Upvotes: 3