Search code examples
pythonconfigparser

Ignore non existing attributes in config file parser python


I have a function returning 1 list at a time, like below

['7:49', 'Section1', '181', '1578', '634', '4055']
['7:49', 'Section2', '181', '1578', '634', '4055']

These values are time,section,count,avg,min,max (I know this will always be the sequence) My aim is to alert if any of the values breaches limits defined in a config file.

So I create a config like below

[Section1]
Count:10
Min:20
Max:100
Avg:50
[Section2]
Count:10
Min:20
Max:100
Avg:50

My function to check max and min limits

def checklimit(line):
    print "Inside CheckLimit", line[1],line[4],line[5]
    if line[4] < ConfigSectionMap(line[1])['min'] or line[5] > ConfigSectionMap(line[1])['max']:
        sendAlert(line)

This works fine but this could be improved and has some corner cases. Suppose someone leaves config as below

[Section1]
Count:10
Min:
Max:
Avg:50
[Section2]
Count:10
Avg:50

Meaning the user only wants to check for Count and Avg. How should these cases be handled in my code so as to check only required parameters given in config file. I have used Config Parser from here

Suggestions for question title improvement are welcome. It was hard to put one. Thanks


Solution

  • There's a many ways to approach this. With key lookups, in dictionaries you can use the dict.get() method and provide a fallback value.

    so instead of

    ConfigSectionMap(line[1])['min']
    

    You can use something like this, which will return 0 if the key does not exist.

    ConfigSectionMap(line[1]).get('min', 0)