Try / Except for a block declaring multiple values

I am trying to write a try / except block that declares two variables that retrieve their values ​​through ConfigParser

. The problem I'm running into is that it is possible that one or both of the declared values ​​may be missing in a particular section and should be set None

in that case. I know that I can just add values ​​under each config file, however not all configs are consistent in section names, which becomes a very tedious task.

Is there a better way to achieve the next try / except block without breaking them 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 decision:

try:
    ports = getCfgStr(sectName, 'ports')
except KeyError:
    ports = None

try:
    terminals = getCfgStr(sectName, 'terminals')
except KeyError:
    terminals = None

      

+3


source to share


4 answers


Interest Ask!

How about this:



def lookup(param):
    try:
        return getCfgStr(sectName, param)
    except KeyError:
        return None

ports = lookup('ports')
terminal = lookup('terminals')

      

+2


source


The best solution is for your function getCfgStr

to accept the default values ​​that it will return if there is no such option in this section. So your code will look like this:

ports = getCfgStr(sectName, 'ports', None)
terminal = getCfgStr(sectName, 'terminals', None)

      



If you need to use exceptions, your solution is fine.

+2


source


Maybe just execute the function:

def get_or_default(name, default):
    try:
        result = getCfgStr(sectName, name)
        return result
    except KeyError:
        return default

      

Call:

 ports = get_or_default('ports', None)

      

However, the best approach, if you are using ConfigParser

, is to change the function getCfgStr

to use the libraries way to do this: https://docs.python.org/3.4/library/configparser.html#fallback-values

0


source


Instead of using the anti- coding pattern by exception , you can explicitly check if this parameter is present:

RawConfigParser.has_option(section, option) 

      

If the given section exists and contains the given option, return True; otherwise return False.

0


source







All Articles