[Python-checkins] python/dist/src/Lib ConfigParser.py,1.47,1.48
fdrake@users.sourceforge.net
fdrake@users.sourceforge.net
Fri, 25 Oct 2002 11:08:20 -0700
Update of /cvsroot/python/python/dist/src/Lib
In directory usw-pr-cvs1:/tmp/cvs-serv32549
Modified Files:
ConfigParser.py
Log Message:
Re-factor: Use a RawConfigParser base class and make ConfigParser a
derived class that adds the ugly string interpolation code. In the
process, changed all "__" methods and instance variables to "_".
Index: ConfigParser.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/ConfigParser.py,v
retrieving revision 1.47
retrieving revision 1.48
diff -C2 -d -r1.47 -r1.48
*** ConfigParser.py 27 Sep 2002 16:21:16 -0000 1.47
--- ConfigParser.py 25 Oct 2002 18:08:18 -0000 1.48
***************
*** 173,191 ****
! class ConfigParser:
def __init__(self, defaults=None):
! self.__sections = {}
if defaults is None:
! self.__defaults = {}
else:
! self.__defaults = defaults
def defaults(self):
! return self.__defaults
def sections(self):
"""Return a list of section names, excluding [DEFAULT]"""
! # self.__sections will never have [DEFAULT] in it
! return self.__sections.keys()
def add_section(self, section):
--- 173,191 ----
! class RawConfigParser:
def __init__(self, defaults=None):
! self._sections = {}
if defaults is None:
! self._defaults = {}
else:
! self._defaults = defaults
def defaults(self):
! return self._defaults
def sections(self):
"""Return a list of section names, excluding [DEFAULT]"""
! # self._sections will never have [DEFAULT] in it
! return self._sections.keys()
def add_section(self, section):
***************
*** 195,201 ****
already exists.
"""
! if section in self.__sections:
raise DuplicateSectionError(section)
! self.__sections[section] = {}
def has_section(self, section):
--- 195,201 ----
already exists.
"""
! if section in self._sections:
raise DuplicateSectionError(section)
! self._sections[section] = {}
def has_section(self, section):
***************
*** 204,216 ****
The DEFAULT section is not acknowledged.
"""
! return section in self.__sections
def options(self, section):
"""Return a list of option names for the given section name."""
try:
! opts = self.__sections[section].copy()
except KeyError:
raise NoSectionError(section)
! opts.update(self.__defaults)
if '__name__' in opts:
del opts['__name__']
--- 204,216 ----
The DEFAULT section is not acknowledged.
"""
! return section in self._sections
def options(self, section):
"""Return a list of option names for the given section name."""
try:
! opts = self._sections[section].copy()
except KeyError:
raise NoSectionError(section)
! opts.update(self._defaults)
if '__name__' in opts:
del opts['__name__']
***************
*** 234,238 ****
except IOError:
continue
! self.__read(fp, filename)
fp.close()
--- 234,238 ----
except IOError:
continue
! self._read(fp, filename)
fp.close()
***************
*** 251,340 ****
except AttributeError:
filename = '<???>'
! self.__read(fp, filename)
!
! def get(self, section, option, raw=0, vars=None):
! """Get an option value for a given section.
!
! All % interpolations are expanded in the return values, based on the
! defaults passed into the constructor, unless the optional argument
! `raw' is true. Additional substitutions may be provided using the
! `vars' argument, which must be a dictionary whose contents overrides
! any pre-existing defaults.
! The section DEFAULT is special.
! """
! d = self.__defaults.copy()
! try:
! d.update(self.__sections[section])
! except KeyError:
if section != DEFAULTSECT:
raise NoSectionError(section)
! # Update with the entry specific variables
! if vars is not None:
! d.update(vars)
! option = self.optionxform(option)
! try:
! value = d[option]
! except KeyError:
raise NoOptionError(option, section)
! if raw:
! return value
! return self._interpolate(section, option, value, d)
!
! def items(self, section, raw=0, vars=None):
! """Return a list of tuples with (name, value) for each option
! in the section.
!
! All % interpolations are expanded in the return values, based on the
! defaults passed into the constructor, unless the optional argument
! `raw' is true. Additional substitutions may be provided using the
! `vars' argument, which must be a dictionary whose contents overrides
! any pre-existing defaults.
!
! The section DEFAULT is special.
! """
! d = self.__defaults.copy()
try:
! d.update(self.__sections[section])
except KeyError:
if section != DEFAULTSECT:
raise NoSectionError(section)
! # Update with the entry specific variables
! if vars:
! d.update(vars)
! if raw:
! for option in self.options(section):
! yield (option, d[option])
! else:
! for option in self.options(section):
! yield (option,
! self._interpolate(section, option, d[option], d))
!
! def _interpolate(self, section, option, rawval, vars):
! # do the string interpolation
! value = rawval
! depth = MAX_INTERPOLATION_DEPTH
! while depth: # Loop through this until it's done
! depth -= 1
! if value.find("%(") != -1:
! try:
! value = value % vars
! except KeyError, key:
! raise InterpolationError(key, option, section, rawval)
! else:
! break
! if value.find("%(") != -1:
! raise InterpolationDepthError(option, section, rawval)
! return value
! def __get(self, section, conv, option):
return conv(self.get(section, option))
def getint(self, section, option):
! return self.__get(section, int, option)
def getfloat(self, section, option):
! return self.__get(section, float, option)
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
--- 251,290 ----
except AttributeError:
filename = '<???>'
! self._read(fp, filename)
! def get(self, section, option):
! opt = self.optionxform(option)
! if section not in self._sections:
if section != DEFAULTSECT:
raise NoSectionError(section)
! if opt in self._defaults:
! return self._defaults[opt]
! else:
! raise NoOptionError(option, section)
! elif opt in self._sections[section]:
! return self._sections[section][opt]
! elif opt in self._defaults:
! return self._defaults[opt]
! else:
raise NoOptionError(option, section)
! def items(self, section):
try:
! d2 = self._sections[section]
except KeyError:
if section != DEFAULTSECT:
raise NoSectionError(section)
! d = self._defaults.copy()
! d.update(d2)
! return d.items()
! def _get(self, section, conv, option):
return conv(self.get(section, option))
def getint(self, section, option):
! return self._get(section, int, option)
def getfloat(self, section, option):
! return self._get(section, float, option)
_boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
***************
*** 354,372 ****
if not section or section == DEFAULTSECT:
option = self.optionxform(option)
! return option in self.__defaults
! elif section not in self.__sections:
return 0
else:
option = self.optionxform(option)
! return (option in self.__sections[section]
! or option in self.__defaults)
def set(self, section, option, value):
"""Set an option."""
if not section or section == DEFAULTSECT:
! sectdict = self.__defaults
else:
try:
! sectdict = self.__sections[section]
except KeyError:
raise NoSectionError(section)
--- 304,322 ----
if not section or section == DEFAULTSECT:
option = self.optionxform(option)
! return option in self._defaults
! elif section not in self._sections:
return 0
else:
option = self.optionxform(option)
! return (option in self._sections[section]
! or option in self._defaults)
def set(self, section, option, value):
"""Set an option."""
if not section or section == DEFAULTSECT:
! sectdict = self._defaults
else:
try:
! sectdict = self._sections[section]
except KeyError:
raise NoSectionError(section)
***************
*** 375,386 ****
def write(self, fp):
"""Write an .ini-format representation of the configuration state."""
! if self.__defaults:
fp.write("[%s]\n" % DEFAULTSECT)
! for (key, value) in self.__defaults.items():
fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
fp.write("\n")
! for section in self.__sections:
fp.write("[%s]\n" % section)
! for (key, value) in self.__sections[section].items():
if key != "__name__":
fp.write("%s = %s\n" %
--- 325,336 ----
def write(self, fp):
"""Write an .ini-format representation of the configuration state."""
! if self._defaults:
fp.write("[%s]\n" % DEFAULTSECT)
! for (key, value) in self._defaults.items():
fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
fp.write("\n")
! for section in self._sections:
fp.write("[%s]\n" % section)
! for (key, value) in self._sections[section].items():
if key != "__name__":
fp.write("%s = %s\n" %
***************
*** 391,398 ****
"""Remove an option."""
if not section or section == DEFAULTSECT:
! sectdict = self.__defaults
else:
try:
! sectdict = self.__sections[section]
except KeyError:
raise NoSectionError(section)
--- 341,348 ----
"""Remove an option."""
if not section or section == DEFAULTSECT:
! sectdict = self._defaults
else:
try:
! sectdict = self._sections[section]
except KeyError:
raise NoSectionError(section)
***************
*** 405,411 ****
def remove_section(self, section):
"""Remove a file section."""
! existed = section in self.__sections
if existed:
! del self.__sections[section]
return existed
--- 355,361 ----
def remove_section(self, section):
"""Remove a file section."""
! existed = section in self._sections
if existed:
! del self._sections[section]
return existed
***************
*** 427,431 ****
)
! def __read(self, fp, fpname):
"""Parse a sectioned setup file.
--- 377,381 ----
)
! def _read(self, fp, fpname):
"""Parse a sectioned setup file.
***************
*** 463,473 ****
if mo:
sectname = mo.group('header')
! if sectname in self.__sections:
! cursect = self.__sections[sectname]
elif sectname == DEFAULTSECT:
! cursect = self.__defaults
else:
cursect = {'__name__': sectname}
! self.__sections[sectname] = cursect
# So sections can't start with a continuation line
optname = None
--- 413,423 ----
if mo:
sectname = mo.group('header')
! if sectname in self._sections:
! cursect = self._sections[sectname]
elif sectname == DEFAULTSECT:
! cursect = self._defaults
else:
cursect = {'__name__': sectname}
! self._sections[sectname] = cursect
# So sections can't start with a continuation line
optname = None
***************
*** 503,504 ****
--- 453,534 ----
if e:
raise e
+
+
+ class ConfigParser(RawConfigParser):
+
+ def get(self, section, option, raw=0, vars=None):
+ """Get an option value for a given section.
+
+ All % interpolations are expanded in the return values, based on the
+ defaults passed into the constructor, unless the optional argument
+ `raw' is true. Additional substitutions may be provided using the
+ `vars' argument, which must be a dictionary whose contents overrides
+ any pre-existing defaults.
+
+ The section DEFAULT is special.
+ """
+ d = self._defaults.copy()
+ try:
+ d.update(self._sections[section])
+ except KeyError:
+ if section != DEFAULTSECT:
+ raise NoSectionError(section)
+ # Update with the entry specific variables
+ if vars is not None:
+ d.update(vars)
+ option = self.optionxform(option)
+ try:
+ value = d[option]
+ except KeyError:
+ raise NoOptionError(option, section)
+
+ if raw:
+ return value
+ else:
+ return self._interpolate(section, option, value, d)
+
+ def items(self, section, raw=0, vars=None):
+ """Return a list of tuples with (name, value) for each option
+ in the section.
+
+ All % interpolations are expanded in the return values, based on the
+ defaults passed into the constructor, unless the optional argument
+ `raw' is true. Additional substitutions may be provided using the
+ `vars' argument, which must be a dictionary whose contents overrides
+ any pre-existing defaults.
+
+ The section DEFAULT is special.
+ """
+ d = self._defaults.copy()
+ try:
+ d.update(self._sections[section])
+ except KeyError:
+ if section != DEFAULTSECT:
+ raise NoSectionError(section)
+ # Update with the entry specific variables
+ if vars:
+ d.update(vars)
+ if raw:
+ for option in self.options(section):
+ yield (option, d[option])
+ else:
+ for option in self.options(section):
+ yield (option,
+ self._interpolate(section, option, d[option], d))
+
+ def _interpolate(self, section, option, rawval, vars):
+ # do the string interpolation
+ value = rawval
+ depth = MAX_INTERPOLATION_DEPTH
+ while depth: # Loop through this until it's done
+ depth -= 1
+ if value.find("%(") != -1:
+ try:
+ value = value % vars
+ except KeyError, key:
+ raise InterpolationError(key, option, section, rawval)
+ else:
+ break
+ if value.find("%(") != -1:
+ raise InterpolationDepthError(option, section, rawval)
+ return value