2.3.2 Option type

The type string argument of the add_option() method is used to specify the convert the option setting obtained from a configuration file into the desired type. If the configuration option setting cannot be converted to the desired type appropriate help text will be made available (either an exception is raised or sys.exit() is called dependent on exception argument when instantiating ConfigParser). The following table shows the legal values:

value result
None no conversion (default)*
'choice' verifies option setting is a valid choice**
'complex' converts to complex number
'float' converts to floating point number
'int' converts to an integer
'long' converts to a long integer
'string' converts to a string


* When parsed, ini style configuration files automatically return strings as the option setting and no conversion is necessary. Python based configuration files return objects. Omitting the type argument (or setting type to None) allows the option setting object to remain as is.

** When type is set to 'choice', the choices argument must also be present and must be a list of strings of valid choices.

For example:

# file: type.ini
int_option = 10
float_option = 1.5
choice_option = APPLE

And script:

# file: type.py
import cfgparse
c = cfgparse.ConfigParser()
c.add_option('int_option', type='int')
c.add_option('float_option', type='float')
c.add_option('choice_option', type='choice', choices=['APPLE','ORANGE'])
opts = c.parse()
print opts.int_option*2
print opts.float_option*3
print opts.choice_option

Results in:

$ python type.py