What are the differences between ConfigParser
and SafeConfigParser
? And why, exactly, is the latter is safer? What's 'unsafe' about ConfigParser
? I know that SafeConfigParser
inherited the ConfigParser
, what did it do different?
The SafeConfigParser implements a different set(section, option, value)
method which will raise a NoSectionError if the section does not exists, and a TypeError
if value
is not a string.
This allows more control over the behaviour of the parser, an example from documentation:
try:
config.set(section2, option, config.get(section1, option, 1))
except ConfigParser.NoSectionError:
# Create non-existent section
config.add_section(section2)
opt_move(config, section1, section2, option)
else:
config.remove_option(section1, option)
From documentation: It also support interpolation. This means values can contain format strings which refer to other values in the same section, or values in a special DEFAULT section. Additional defaults can be provided on initialization.
Update
I just checked the source code of the SafeConfigParser
, and even if it is true that ConfigParser
also allows interpolation, SafeConfigParser
provides an updated version of it that documentation describes as a more-sane and more predictable variant of the magical interpolation feature.
For example, it will raise an InterpolationSyntaxError
in the event of a bad reference or a syntax error after a '%' character.
Update 2
That could be useful to precise that the SafeConfigParser
class has been renamed to ConfigParser in Python 3.2. If you wonder which of the SafeConfigParser
or the ConfigParser
you should use in python 2.7, use the first (unless you have a very specific reason to use the second)
You could also make easier your future transition to python 3+, (which should happen soon) by doing:
from ConfigParser import SafeConfigParser as ConfigParser