2.3.3 Option check

The check argument of the add_option() method is used to provide a function to check the option setting. In addition the function may also do any further conversions, but it is recommended that the type argument be used when possible. The check function must accept a single argument, the option setting. The function must return a tuple containing the option setting and an error message. If no error, the error message should be set to None.

For example:

# file: check.ini
timeout  = 10  # seconds
timeout2 = 101 # invalid

And script:

# file: check.py

def in_range(value):
    error = None
    if (value <= 0) or (value >= 100):
        error = "'%d' not valid.  Must be between 0 and 100 seconds." % value        
    value = value * 1000 # convert to milliseconds
    return value,error
import cfgparse
c = cfgparse.ConfigParser()
c.add_option('timeout', type='int', check=in_range)
opts = c.parse()
print "Valid timeout:",opts.timeout

c.add_option('timeout2', type='int', check=in_range)
opts = c.parse()

Results in:

$ python check.py
Valid timeout: 10000
ERROR: Configuration File Parser

Option: timeout2
File: [CWD]/check.ini
Section: [DEFAULT]
Line: 3
'101' not valid.  Must be between 0 and 100 seconds.