Back to index

enigmail  1.4.3
Public Member Functions | Public Attributes | Static Public Attributes | Private Member Functions | Static Private Attributes
configobj.ConfigObj Class Reference
Inheritance diagram for configobj.ConfigObj:
Inheritance graph
[legend]
Collaboration diagram for configobj.ConfigObj:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def write
def validate
def __getitem__
def __setitem__
def __delitem__
def get
def update
def pop
def popitem
def clear
def setdefault
def items
def keys
def values
def iteritems
def iterkeys
def itervalues
def __repr__
def dict
def merge
def rename
def walk
def decode
def encode
def istrue
def as_bool
def as_int
def as_float

Public Attributes

 indent_type
 interpolation
 parent
 main
 depth
 scalars
 sections
 name
 comments
 inline_comments
 configspec
 defaults

Static Public Attributes

 quot = noquot

Private Member Functions

def _handle_value
def _multiline
def _handle_configspec
def _set_configspec_value
def _handle_repeat
def _write_line
def _write_marker
def _handle_comment

Static Private Attributes

tuple _keyword
tuple _valueexp

Detailed Description

An object to read, create, and write config files.

Definition at line 1027 of file configobj.py.


Member Function Documentation

def configobj.Section.__delitem__ (   self,
  key 
) [inherited]
Remove items from the sequence when deleting.

Definition at line 595 of file configobj.py.

00595 
00596     def __delitem__(self, key):
00597         """Remove items from the sequence when deleting."""
00598         dict. __delitem__(self, key)
00599         if key in self.scalars:
00600             self.scalars.remove(key)
00601         else:
00602             self.sections.remove(key)
00603         del self.comments[key]
00604         del self.inline_comments[key]

def configobj.Section.__getitem__ (   self,
  key 
) [inherited]
Fetch the item and do string interpolation.

Definition at line 530 of file configobj.py.

00530 
00531     def __getitem__(self, key):
00532         """Fetch the item and do string interpolation."""
00533         val = dict.__getitem__(self, key)
00534         if self.main.interpolation and isinstance(val, StringTypes):
00535             return self._interpolate(key, val)
00536         return val

Here is the call graph for this function:

def configobj.Section.__repr__ (   self) [inherited]

Definition at line 693 of file configobj.py.

00693 
00694     def __repr__(self):
00695         return '{%s}' % ', '.join([('%s: %s' % (repr(key), repr(self[key])))
00696             for key in (self.scalars + self.sections)])

def configobj.Section.__setitem__ (   self,
  key,
  value,
  unrepr = False 
) [inherited]
Correctly set a value.

Making dictionary values Section instances.
(We have to special case 'Section' instances - which are also dicts)

Keys must be strings.
Values need only be strings (or lists of strings) if
``main.stringify`` is set.

`unrepr`` must be set when setting a value to a dictionary, without
creating a new sub-section.

Definition at line 537 of file configobj.py.

00537 
00538     def __setitem__(self, key, value, unrepr=False):
00539         """
00540         Correctly set a value.
00541         
00542         Making dictionary values Section instances.
00543         (We have to special case 'Section' instances - which are also dicts)
00544         
00545         Keys must be strings.
00546         Values need only be strings (or lists of strings) if
00547         ``main.stringify`` is set.
00548         
00549         `unrepr`` must be set when setting a value to a dictionary, without
00550         creating a new sub-section.
00551         """
00552         if not isinstance(key, StringTypes):
00553             raise ValueError, 'The key "%s" is not a string.' % key
00554         # add the comment
00555         if not self.comments.has_key(key):
00556             self.comments[key] = []
00557             self.inline_comments[key] = ''
00558         # remove the entry from defaults
00559         if key in self.defaults:
00560             self.defaults.remove(key)
00561         #
00562         if isinstance(value, Section):
00563             if not self.has_key(key):
00564                 self.sections.append(key)
00565             dict.__setitem__(self, key, value)
00566         elif isinstance(value, dict) and not unrepr:
00567             # First create the new depth level,
00568             # then create the section
00569             if not self.has_key(key):
00570                 self.sections.append(key)
00571             new_depth = self.depth + 1
00572             dict.__setitem__(
00573                 self,
00574                 key,
00575                 Section(
00576                     self,
00577                     new_depth,
00578                     self.main,
00579                     indict=value,
00580                     name=key))
00581         else:
00582             if not self.has_key(key):
00583                 self.scalars.append(key)
00584             if not self.main.stringify:
00585                 if isinstance(value, StringTypes):
00586                     pass
00587                 elif isinstance(value, (list, tuple)):
00588                     for entry in value:
00589                         if not isinstance(entry, StringTypes):
00590                             raise TypeError, (
00591                                 'Value is not a string "%s".' % entry)
00592                 else:
00593                     raise TypeError, 'Value is not a string "%s".' % value
00594             dict.__setitem__(self, key, value)

def configobj.ConfigObj._handle_comment (   self,
  comment 
) [private]
Deal with a comment.

Definition at line 1880 of file configobj.py.

01880 
01881     def _handle_comment(self, comment):
01882         """Deal with a comment."""
01883         if not comment:
01884             return ''
01885         start = self.indent_type
01886         if not comment.startswith('#'):
01887             start += self._a_to_u(' # ')
01888         return (start + comment)

def configobj.ConfigObj._handle_configspec (   self,
  configspec 
) [private]
Parse the configspec.

Definition at line 1777 of file configobj.py.

01777 
01778     def _handle_configspec(self, configspec):
01779         """Parse the configspec."""
01780         # FIXME: Should we check that the configspec was created with the 
01781         #   correct settings ? (i.e. ``list_values=False``)
01782         if not isinstance(configspec, ConfigObj):
01783             try:
01784                 configspec = ConfigObj(
01785                     configspec,
01786                     raise_errors=True,
01787                     file_error=True,
01788                     list_values=False)
01789             except ConfigObjError, e:
01790                 # FIXME: Should these errors have a reference
01791                 # to the already parsed ConfigObj ?
01792                 raise ConfigspecError('Parsing configspec failed: %s' % e)
01793             except IOError, e:
01794                 raise IOError('Reading configspec failed: %s' % e)
01795         self._set_configspec_value(configspec, self)

Here is the call graph for this function:

def configobj.ConfigObj._handle_repeat (   self,
  section,
  configspec 
) [private]
Dynamically assign configspec for repeated section.

Definition at line 1826 of file configobj.py.

01826 
01827     def _handle_repeat(self, section, configspec):
01828         """Dynamically assign configspec for repeated section."""
01829         try:
01830             section_keys = configspec.sections
01831             scalar_keys = configspec.scalars
01832         except AttributeError:
01833             section_keys = [entry for entry in configspec 
01834                                 if isinstance(configspec[entry], dict)]
01835             scalar_keys = [entry for entry in configspec 
01836                                 if not isinstance(configspec[entry], dict)]
01837         if '__many__' in section_keys and len(section_keys) > 1:
01838             # FIXME: can we supply any useful information here ?
01839             raise RepeatSectionError
01840         scalars = {}
01841         sections = {}
01842         for entry in scalar_keys:
01843             val = configspec[entry]
01844             scalars[entry] = val
01845         for entry in section_keys:
01846             val = configspec[entry]
01847             if entry == '__many__':
01848                 scalars[entry] = val
01849                 continue
01850             sections[entry] = val
01851         #
01852         section.configspec = scalars
01853         for entry in sections:
01854             if not section.has_key(entry):
01855                 section[entry] = {}
01856             self._handle_repeat(section[entry], sections[entry])

Here is the call graph for this function:

Here is the caller graph for this function:

def configobj.ConfigObj._handle_value (   self,
  value 
) [private]
Given a value string, unquote, remove comment,
handle lists. (including empty and single member lists)

Definition at line 1698 of file configobj.py.

01698 
01699     def _handle_value(self, value):
01700         """
01701         Given a value string, unquote, remove comment,
01702         handle lists. (including empty and single member lists)
01703         """
01704         # do we look for lists in values ?
01705         if not self.list_values:
01706             mat = self._nolistvalue.match(value)
01707             if mat is None:
01708                 raise SyntaxError
01709             # NOTE: we don't unquote here
01710             return mat.groups()
01711         #
01712         mat = self._valueexp.match(value)
01713         if mat is None:
01714             # the value is badly constructed, probably badly quoted,
01715             # or an invalid list
01716             raise SyntaxError
01717         (list_values, single, empty_list, comment) = mat.groups()
01718         if (list_values == '') and (single is None):
01719             # change this if you want to accept empty values
01720             raise SyntaxError
01721         # NOTE: note there is no error handling from here if the regex
01722         # is wrong: then incorrect values will slip through
01723         if empty_list is not None:
01724             # the single comma - meaning an empty list
01725             return ([], comment)
01726         if single is not None:
01727             # handle empty values
01728             if list_values and not single:
01729                 # FIXME: the '' is a workaround because our regex now matches
01730                 #   '' at the end of a list if it has a trailing comma
01731                 single = None
01732             else:
01733                 single = single or '""'
01734                 single = self._unquote(single)
01735         if list_values == '':
01736             # not a list value
01737             return (single, comment)
01738         the_list = self._listvalueexp.findall(list_values)
01739         the_list = [self._unquote(val) for val in the_list]
01740         if single is not None:
01741             the_list += [single]
01742         return (the_list, comment)

def configobj.ConfigObj._multiline (   self,
  value,
  infile,
  cur_index,
  maxline 
) [private]
Extract the value, where we are in a multiline situation.

Definition at line 1743 of file configobj.py.

01743 
01744     def _multiline(self, value, infile, cur_index, maxline):
01745         """Extract the value, where we are in a multiline situation."""
01746         quot = value[:3]
01747         newvalue = value[3:]
01748         single_line = self._triple_quote[quot][0]
01749         multi_line = self._triple_quote[quot][1]
01750         mat = single_line.match(value)
01751         if mat is not None:
01752             retval = list(mat.groups())
01753             retval.append(cur_index)
01754             return retval
01755         elif newvalue.find(quot) != -1:
01756             # somehow the triple quote is missing
01757             raise SyntaxError
01758         #
01759         while cur_index < maxline:
01760             cur_index += 1
01761             newvalue += '\n'
01762             line = infile[cur_index]
01763             if line.find(quot) == -1:
01764                 newvalue += line
01765             else:
01766                 # end of multiline, process it
01767                 break
01768         else:
01769             # we've got to the end of the config, oops...
01770             raise SyntaxError
01771         mat = multi_line.match(line)
01772         if mat is None:
01773             # a badly formed line
01774             raise SyntaxError
01775         (value, comment) = mat.groups()
01776         return (newvalue + value, comment, cur_index)

def configobj.ConfigObj._set_configspec_value (   self,
  configspec,
  section 
) [private]
Used to recursively set configspec values.

Definition at line 1796 of file configobj.py.

01796 
01797     def _set_configspec_value(self, configspec, section):
01798         """Used to recursively set configspec values."""
01799         if '__many__' in configspec.sections:
01800             section.configspec['__many__'] = configspec['__many__']
01801             if len(configspec.sections) > 1:
01802                 # FIXME: can we supply any useful information here ?
01803                 raise RepeatSectionError
01804         if hasattr(configspec, 'initial_comment'):
01805             section._configspec_initial_comment = configspec.initial_comment
01806             section._configspec_final_comment = configspec.final_comment
01807             section._configspec_encoding = configspec.encoding
01808             section._configspec_BOM = configspec.BOM
01809             section._configspec_newlines = configspec.newlines
01810             section._configspec_indent_type = configspec.indent_type
01811         for entry in configspec.scalars:
01812             section._configspec_comments[entry] = configspec.comments[entry]
01813             section._configspec_inline_comments[entry] = (
01814                 configspec.inline_comments[entry])
01815             section.configspec[entry] = configspec[entry]
01816             section._order.append(entry)
01817         for entry in configspec.sections:
01818             if entry == '__many__':
01819                 continue
01820             section._cs_section_comments[entry] = configspec.comments[entry]
01821             section._cs_section_inline_comments[entry] = (
01822                 configspec.inline_comments[entry])
01823             if not section.has_key(entry):
01824                 section[entry] = {}
01825             self._set_configspec_value(configspec[entry], section[entry])

Here is the call graph for this function:

Here is the caller graph for this function:

def configobj.ConfigObj._write_line (   self,
  indent_string,
  entry,
  this_entry,
  comment 
) [private]
Write an individual line, for the write method

Definition at line 1857 of file configobj.py.

01857 
01858     def _write_line(self, indent_string, entry, this_entry, comment):
01859         """Write an individual line, for the write method"""
01860         # NOTE: the calls to self._quote here handles non-StringType values.
01861         if not self.unrepr:
01862             val = self._decode_element(self._quote(this_entry))
01863         else:
01864             val = repr(this_entry)
01865         return '%s%s%s%s%s' % (
01866             indent_string,
01867             self._decode_element(self._quote(entry, multiline=False)),
01868             self._a_to_u(' = '),
01869             val,
01870             self._decode_element(comment))

def configobj.ConfigObj._write_marker (   self,
  indent_string,
  depth,
  entry,
  comment 
) [private]
Write a section marker line

Definition at line 1871 of file configobj.py.

01871 
01872     def _write_marker(self, indent_string, depth, entry, comment):
01873         """Write a section marker line"""
01874         return '%s%s%s%s%s' % (
01875             indent_string,
01876             self._a_to_u('[' * depth),
01877             self._quote(self._decode_element(entry), multiline=False),
01878             self._a_to_u(']' * depth),
01879             self._decode_element(comment))

def configobj.Section.as_bool (   self,
  key 
) [inherited]
Accepts a key as input. The corresponding value must be a string or
the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to
retain compatibility with Python 2.2.

If the string is one of  ``True``, ``On``, ``Yes``, or ``1`` it returns 
``True``.

If the string is one of  ``False``, ``Off``, ``No``, or ``0`` it returns 
``False``.

``as_bool`` is not case sensitive.

Any other input will raise a ``ValueError``.

>>> a = ConfigObj()
>>> a['a'] = 'fish'
>>> a.as_bool('a')
Traceback (most recent call last):
ValueError: Value "fish" is neither True nor False
>>> a['b'] = 'True'
>>> a.as_bool('b')
1
>>> a['b'] = 'off'
>>> a.as_bool('b')
0

Definition at line 941 of file configobj.py.

00941 
00942     def as_bool(self, key):
00943         """
00944         Accepts a key as input. The corresponding value must be a string or
00945         the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to
00946         retain compatibility with Python 2.2.
00947         
00948         If the string is one of  ``True``, ``On``, ``Yes``, or ``1`` it returns 
00949         ``True``.
00950         
00951         If the string is one of  ``False``, ``Off``, ``No``, or ``0`` it returns 
00952         ``False``.
00953         
00954         ``as_bool`` is not case sensitive.
00955         
00956         Any other input will raise a ``ValueError``.
00957         
00958         >>> a = ConfigObj()
00959         >>> a['a'] = 'fish'
00960         >>> a.as_bool('a')
00961         Traceback (most recent call last):
00962         ValueError: Value "fish" is neither True nor False
00963         >>> a['b'] = 'True'
00964         >>> a.as_bool('b')
00965         1
00966         >>> a['b'] = 'off'
00967         >>> a.as_bool('b')
00968         0
00969         """
00970         val = self[key]
00971         if val == True:
00972             return True
00973         elif val == False:
00974             return False
00975         else:
00976             try:
00977                 if not isinstance(val, StringTypes):
00978                     raise KeyError
00979                 else:
00980                     return self.main._bools[val.lower()]
00981             except KeyError:
00982                 raise ValueError('Value "%s" is neither True nor False' % val)

Here is the caller graph for this function:

def configobj.Section.as_float (   self,
  key 
) [inherited]
A convenience method which coerces the specified value to a float.

If the value is an invalid literal for ``float``, a ``ValueError`` will
be raised.

>>> a = ConfigObj()
>>> a['a'] = 'fish'
>>> a.as_float('a')
Traceback (most recent call last):
ValueError: invalid literal for float(): fish
>>> a['b'] = '1'
>>> a.as_float('b')
1.0
>>> a['b'] = '3.2'
>>> a.as_float('b')
3.2000000000000002

Definition at line 1005 of file configobj.py.

01005 
01006     def as_float(self, key):
01007         """
01008         A convenience method which coerces the specified value to a float.
01009         
01010         If the value is an invalid literal for ``float``, a ``ValueError`` will
01011         be raised.
01012         
01013         >>> a = ConfigObj()
01014         >>> a['a'] = 'fish'
01015         >>> a.as_float('a')
01016         Traceback (most recent call last):
01017         ValueError: invalid literal for float(): fish
01018         >>> a['b'] = '1'
01019         >>> a.as_float('b')
01020         1.0
01021         >>> a['b'] = '3.2'
01022         >>> a.as_float('b')
01023         3.2000000000000002
01024         """
01025         return float(self[key])
01026     

def configobj.Section.as_int (   self,
  key 
) [inherited]
A convenience method which coerces the specified value to an integer.

If the value is an invalid literal for ``int``, a ``ValueError`` will
be raised.

>>> a = ConfigObj()
>>> a['a'] = 'fish'
>>> a.as_int('a')
Traceback (most recent call last):
ValueError: invalid literal for int(): fish
>>> a['b'] = '1'
>>> a.as_int('b')
1
>>> a['b'] = '3.2'
>>> a.as_int('b')
Traceback (most recent call last):
ValueError: invalid literal for int(): 3.2

Definition at line 983 of file configobj.py.

00983 
00984     def as_int(self, key):
00985         """
00986         A convenience method which coerces the specified value to an integer.
00987         
00988         If the value is an invalid literal for ``int``, a ``ValueError`` will
00989         be raised.
00990         
00991         >>> a = ConfigObj()
00992         >>> a['a'] = 'fish'
00993         >>> a.as_int('a')
00994         Traceback (most recent call last):
00995         ValueError: invalid literal for int(): fish
00996         >>> a['b'] = '1'
00997         >>> a.as_int('b')
00998         1
00999         >>> a['b'] = '3.2'
01000         >>> a.as_int('b')
01001         Traceback (most recent call last):
01002         ValueError: invalid literal for int(): 3.2
01003         """
01004         return int(self[key])

def configobj.Section.clear (   self) [inherited]
A version of clear that also affects scalars/sections
Also clears comments and configspec.

Leaves other attributes alone :
    depth/main/parent are not affected

Definition at line 644 of file configobj.py.

00644 
00645     def clear(self):
00646         """
00647         A version of clear that also affects scalars/sections
00648         Also clears comments and configspec.
00649         
00650         Leaves other attributes alone :
00651             depth/main/parent are not affected
00652         """
00653         dict.clear(self)
00654         self.scalars = []
00655         self.sections = []
00656         self.comments = {}
00657         self.inline_comments = {}
00658         self.configspec = {}

def configobj.Section.decode (   self,
  encoding 
) [inherited]
Decode all strings and values to unicode, using the specified encoding.

Works with subsections and list values.

Uses the ``walk`` method.

Testing ``encode`` and ``decode``.
>>> m = ConfigObj(a)
>>> m.decode('ascii')
>>> def testuni(val):
...     for entry in val:
...         if not isinstance(entry, unicode):
...             print >> sys.stderr, type(entry)
...             raise AssertionError, 'decode failed.'
...         if isinstance(val[entry], dict):
...             testuni(val[entry])
...         elif not isinstance(val[entry], unicode):
...             raise AssertionError, 'decode failed.'
>>> testuni(m)
>>> m.encode('ascii')
>>> a == m
1

Definition at line 867 of file configobj.py.

00867 
00868     def decode(self, encoding):
00869         """
00870         Decode all strings and values to unicode, using the specified encoding.
00871         
00872         Works with subsections and list values.
00873         
00874         Uses the ``walk`` method.
00875         
00876         Testing ``encode`` and ``decode``.
00877         >>> m = ConfigObj(a)
00878         >>> m.decode('ascii')
00879         >>> def testuni(val):
00880         ...     for entry in val:
00881         ...         if not isinstance(entry, unicode):
00882         ...             print >> sys.stderr, type(entry)
00883         ...             raise AssertionError, 'decode failed.'
00884         ...         if isinstance(val[entry], dict):
00885         ...             testuni(val[entry])
00886         ...         elif not isinstance(val[entry], unicode):
00887         ...             raise AssertionError, 'decode failed.'
00888         >>> testuni(m)
00889         >>> m.encode('ascii')
00890         >>> a == m
00891         1
00892         """
00893         warn('use of ``decode`` is deprecated.', DeprecationWarning)
00894         def decode(section, key, encoding=encoding, warn=True):
00895             """ """
00896             val = section[key]
00897             if isinstance(val, (list, tuple)):
00898                 newval = []
00899                 for entry in val:
00900                     newval.append(entry.decode(encoding))
00901             elif isinstance(val, dict):
00902                 newval = val
00903             else:
00904                 newval = val.decode(encoding)
00905             newkey = key.decode(encoding)
00906             section.rename(key, newkey)
00907             section[newkey] = newval
00908         # using ``call_on_sections`` allows us to modify section names
00909         self.walk(decode, call_on_sections=True)

Here is the call graph for this function:

def configobj.Section.dict (   self) [inherited]
Return a deepcopy of self as a dictionary.

All members that are ``Section`` instances are recursively turned to
ordinary dictionaries - by calling their ``dict`` method.

>>> n = a.dict()
>>> n == a
1
>>> n is a
0

Definition at line 701 of file configobj.py.

00701 
00702     def dict(self):
00703         """
00704         Return a deepcopy of self as a dictionary.
00705         
00706         All members that are ``Section`` instances are recursively turned to
00707         ordinary dictionaries - by calling their ``dict`` method.
00708         
00709         >>> n = a.dict()
00710         >>> n == a
00711         1
00712         >>> n is a
00713         0
00714         """
00715         newdict = {}
00716         for entry in self:
00717             this_entry = self[entry]
00718             if isinstance(this_entry, Section):
00719                 this_entry = this_entry.dict()
00720             elif isinstance(this_entry, list):
00721                 # create a copy rather than a reference
00722                 this_entry = list(this_entry)
00723             elif isinstance(this_entry, tuple):
00724                 # create a copy rather than a reference
00725                 this_entry = tuple(this_entry)
00726             newdict[entry] = this_entry
00727         return newdict

def configobj.Section.encode (   self,
  encoding 
) [inherited]
Encode all strings and values from unicode,
using the specified encoding.

Works with subsections and list values.
Uses the ``walk`` method.

Definition at line 910 of file configobj.py.

00910 
00911     def encode(self, encoding):
00912         """
00913         Encode all strings and values from unicode,
00914         using the specified encoding.
00915         
00916         Works with subsections and list values.
00917         Uses the ``walk`` method.
00918         """
00919         warn('use of ``encode`` is deprecated.', DeprecationWarning)
00920         def encode(section, key, encoding=encoding):
00921             """ """
00922             val = section[key]
00923             if isinstance(val, (list, tuple)):
00924                 newval = []
00925                 for entry in val:
00926                     newval.append(entry.encode(encoding))
00927             elif isinstance(val, dict):
00928                 newval = val
00929             else:
00930                 newval = val.encode(encoding)
00931             newkey = key.encode(encoding)
00932             section.rename(key, newkey)
00933             section[newkey] = newval
00934         self.walk(encode, call_on_sections=True)

Here is the call graph for this function:

def configobj.Section.get (   self,
  key,
  default = None 
) [inherited]
A version of ``get`` that doesn't bypass string interpolation.

Definition at line 605 of file configobj.py.

00605 
00606     def get(self, key, default=None):
00607         """A version of ``get`` that doesn't bypass string interpolation."""
00608         try:
00609             return self[key]
00610         except KeyError:
00611             return default

Here is the caller graph for this function:

def configobj.Section.istrue (   self,
  key 
) [inherited]
A deprecated version of ``as_bool``.

Definition at line 935 of file configobj.py.

00935 
00936     def istrue(self, key):
00937         """A deprecated version of ``as_bool``."""
00938         warn('use of ``istrue`` is deprecated. Use ``as_bool`` method '
00939                 'instead.', DeprecationWarning)
00940         return self.as_bool(key)

Here is the call graph for this function:

def configobj.Section.items (   self) [inherited]

Definition at line 667 of file configobj.py.

00667 
00668     def items(self):
00669         """ """
00670         return zip((self.scalars + self.sections), self.values())

Here is the call graph for this function:

Here is the caller graph for this function:

def configobj.Section.iteritems (   self) [inherited]

Definition at line 679 of file configobj.py.

00679 
00680     def iteritems(self):
00681         """ """
00682         return iter(self.items())

Here is the call graph for this function:

def configobj.Section.iterkeys (   self) [inherited]

Definition at line 683 of file configobj.py.

00683 
00684     def iterkeys(self):
00685         """ """
00686         return iter((self.scalars + self.sections))

def configobj.Section.itervalues (   self) [inherited]

Definition at line 689 of file configobj.py.

00689 
00690     def itervalues(self):
00691         """ """
00692         return iter(self.values())

Here is the call graph for this function:

def configobj.Section.keys (   self) [inherited]

Definition at line 671 of file configobj.py.

00671 
00672     def keys(self):
00673         """ """
00674         return (self.scalars + self.sections)

def configobj.Section.merge (   self,
  indict 
) [inherited]
A recursive update - useful for merging config files.

>>> a = '''[section1]
...     option1 = True
...     [[subsection]]
...     more_options = False
...     # end of file'''.splitlines()
>>> b = '''# File is user.ini
...     [section1]
...     option1 = False
...     # end of file'''.splitlines()
>>> c1 = ConfigObj(b)
>>> c2 = ConfigObj(a)
>>> c2.merge(c1)
>>> c2
{'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}}

Definition at line 728 of file configobj.py.

00728 
00729     def merge(self, indict):
00730         """
00731         A recursive update - useful for merging config files.
00732         
00733         >>> a = '''[section1]
00734         ...     option1 = True
00735         ...     [[subsection]]
00736         ...     more_options = False
00737         ...     # end of file'''.splitlines()
00738         >>> b = '''# File is user.ini
00739         ...     [section1]
00740         ...     option1 = False
00741         ...     # end of file'''.splitlines()
00742         >>> c1 = ConfigObj(b)
00743         >>> c2 = ConfigObj(a)
00744         >>> c2.merge(c1)
00745         >>> c2
00746         {'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}}
00747         """
00748         for key, val in indict.items():
00749             if (key in self and isinstance(self[key], dict) and
00750                                 isinstance(val, dict)):
00751                 self[key].merge(val)
00752             else:   
00753                 self[key] = val

def configobj.Section.pop (   self,
  key,
  args 
) [inherited]

Definition at line 619 of file configobj.py.

00619 
00620     def pop(self, key, *args):
00621         """ """
00622         val = dict.pop(self, key, *args)
00623         if key in self.scalars:
00624             del self.comments[key]
00625             del self.inline_comments[key]
00626             self.scalars.remove(key)
00627         elif key in self.sections:
00628             del self.comments[key]
00629             del self.inline_comments[key]
00630             self.sections.remove(key)
00631         if self.main.interpolation and isinstance(val, StringTypes):
00632             return self._interpolate(key, val)
00633         return val

Here is the call graph for this function:

def configobj.Section.popitem (   self) [inherited]
Pops the first (key,val)

Definition at line 634 of file configobj.py.

00634 
00635     def popitem(self):
00636         """Pops the first (key,val)"""
00637         sequence = (self.scalars + self.sections)
00638         if not sequence:
00639             raise KeyError, ": 'popitem(): dictionary is empty'"
00640         key = sequence[0]
00641         val =  self[key]
00642         del self[key]
00643         return key, val

def configobj.Section.rename (   self,
  oldkey,
  newkey 
) [inherited]
Change a keyname to another, without changing position in sequence.

Implemented so that transformations can be made on keys,
as well as on values. (used by encode and decode)

Also renames comments.

Definition at line 754 of file configobj.py.

00754 
00755     def rename(self, oldkey, newkey):
00756         """
00757         Change a keyname to another, without changing position in sequence.
00758         
00759         Implemented so that transformations can be made on keys,
00760         as well as on values. (used by encode and decode)
00761         
00762         Also renames comments.
00763         """
00764         if oldkey in self.scalars:
00765             the_list = self.scalars
00766         elif oldkey in self.sections:
00767             the_list = self.sections
00768         else:
00769             raise KeyError, 'Key "%s" not found.' % oldkey
00770         pos = the_list.index(oldkey)
00771         #
00772         val = self[oldkey]
00773         dict.__delitem__(self, oldkey)
00774         dict.__setitem__(self, newkey, val)
00775         the_list.remove(oldkey)
00776         the_list.insert(pos, newkey)
00777         comm = self.comments[oldkey]
00778         inline_comment = self.inline_comments[oldkey]
00779         del self.comments[oldkey]
00780         del self.inline_comments[oldkey]
00781         self.comments[newkey] = comm
00782         self.inline_comments[newkey] = inline_comment

Here is the call graph for this function:

def configobj.Section.setdefault (   self,
  key,
  default = None 
) [inherited]
A version of setdefault that sets sequence if appropriate.

Definition at line 659 of file configobj.py.

00659 
00660     def setdefault(self, key, default=None):
00661         """A version of setdefault that sets sequence if appropriate."""
00662         try:
00663             return self[key]
00664         except KeyError:
00665             self[key] = default
00666             return self[key]

def configobj.Section.update (   self,
  indict 
) [inherited]
A version of update that uses our ``__setitem__``.

Definition at line 612 of file configobj.py.

00612 
00613     def update(self, indict):
00614         """
00615         A version of update that uses our ``__setitem__``.
00616         """
00617         for entry in indict:
00618             self[entry] = indict[entry]

def configobj.ConfigObj.validate (   self,
  validator,
  preserve_errors = False,
  copy = False,
  section = None 
)
Test the ConfigObj against a configspec.

It uses the ``validator`` object from *validate.py*.

To run ``validate`` on the current ConfigObj, call: ::

    test = config.validate(validator)

(Normally having previously passed in the configspec when the ConfigObj
was created - you can dynamically assign a dictionary of checks to the
``configspec`` attribute of a section though).

It returns ``True`` if everything passes, or a dictionary of
pass/fails (True/False). If every member of a subsection passes, it
will just have the value ``True``. (It also returns ``False`` if all
members fail).

In addition, it converts the values from strings to their native
types if their checks pass (and ``stringify`` is set).

If ``preserve_errors`` is ``True`` (``False`` is default) then instead
of a marking a fail with a ``False``, it will preserve the actual
exception object. This can contain info about the reason for failure.
For example the ``VdtValueTooSmallError`` indeicates that the value
supplied was too small. If a value (or section) is missing it will
still be marked as ``False``.

You must have the validate module to use ``preserve_errors=True``.

You can then use the ``flatten_errors`` function to turn your nested
results dictionary into a flattened list of failures - useful for
displaying meaningful error messages.

Definition at line 1993 of file configobj.py.

01993 
01994         section=None):
01995         """
01996         Test the ConfigObj against a configspec.
01997         
01998         It uses the ``validator`` object from *validate.py*.
01999         
02000         To run ``validate`` on the current ConfigObj, call: ::
02001         
02002             test = config.validate(validator)
02003         
02004         (Normally having previously passed in the configspec when the ConfigObj
02005         was created - you can dynamically assign a dictionary of checks to the
02006         ``configspec`` attribute of a section though).
02007         
02008         It returns ``True`` if everything passes, or a dictionary of
02009         pass/fails (True/False). If every member of a subsection passes, it
02010         will just have the value ``True``. (It also returns ``False`` if all
02011         members fail).
02012         
02013         In addition, it converts the values from strings to their native
02014         types if their checks pass (and ``stringify`` is set).
02015         
02016         If ``preserve_errors`` is ``True`` (``False`` is default) then instead
02017         of a marking a fail with a ``False``, it will preserve the actual
02018         exception object. This can contain info about the reason for failure.
02019         For example the ``VdtValueTooSmallError`` indeicates that the value
02020         supplied was too small. If a value (or section) is missing it will
02021         still be marked as ``False``.
02022         
02023         You must have the validate module to use ``preserve_errors=True``.
02024         
02025         You can then use the ``flatten_errors`` function to turn your nested
02026         results dictionary into a flattened list of failures - useful for
02027         displaying meaningful error messages.
02028         """
02029         if section is None:
02030             if self.configspec is None:
02031                 raise ValueError, 'No configspec supplied.'
02032             if preserve_errors:
02033                 if VdtMissingValue is None:
02034                     raise ImportError('Missing validate module.')
02035             section = self
02036         #
02037         spec_section = section.configspec
02038         if copy and hasattr(section, '_configspec_initial_comment'):
02039             section.initial_comment = section._configspec_initial_comment
02040             section.final_comment = section._configspec_final_comment
02041             section.encoding = section._configspec_encoding
02042             section.BOM = section._configspec_BOM
02043             section.newlines = section._configspec_newlines
02044             section.indent_type = section._configspec_indent_type
02045         if '__many__' in section.configspec:
02046             many = spec_section['__many__']
02047             # dynamically assign the configspecs
02048             # for the sections below
02049             for entry in section.sections:
02050                 self._handle_repeat(section[entry], many)
02051         #
02052         out = {}
02053         ret_true = True
02054         ret_false = True
02055         order = [k for k in section._order if k in spec_section]
02056         order += [k for k in spec_section if k not in order]
02057         for entry in order:
02058             if entry == '__many__':
02059                 continue
02060             if (not entry in section.scalars) or (entry in section.defaults):
02061                 # missing entries
02062                 # or entries from defaults
02063                 missing = True
02064                 val = None
02065                 if copy and not entry in section.scalars:
02066                     # copy comments
02067                     section.comments[entry] = (
02068                         section._configspec_comments.get(entry, []))
02069                     section.inline_comments[entry] = (
02070                         section._configspec_inline_comments.get(entry, ''))
02071                 #
02072             else:
02073                 missing = False
02074                 val = section[entry]
02075             try:
02076                 check = validator.check(spec_section[entry],
02077                                         val,
02078                                         missing=missing
02079                                         )
02080             except validator.baseErrorClass, e:
02081                 if not preserve_errors or isinstance(e, VdtMissingValue):
02082                     out[entry] = False
02083                 else:
02084                     # preserve the error
02085                     out[entry] = e
02086                     ret_false = False
02087                 ret_true = False
02088             else:
02089                 ret_false = False
02090                 out[entry] = True
02091                 if self.stringify or missing:
02092                     # if we are doing type conversion
02093                     # or the value is a supplied default
02094                     if not self.stringify:
02095                         if isinstance(check, (list, tuple)):
02096                             # preserve lists
02097                             check = [self._str(item) for item in check]
02098                         elif missing and check is None:
02099                             # convert the None from a default to a ''
02100                             check = ''
02101                         else:
02102                             check = self._str(check)
02103                     if (check != val) or missing:
02104                         section[entry] = check
02105                 if not copy and missing and entry not in section.defaults:
02106                     section.defaults.append(entry)
02107         #
02108         # Missing sections will have been created as empty ones when the
02109         # configspec was read.
02110         for entry in section.sections:
02111             # FIXME: this means DEFAULT is not copied in copy mode
02112             if section is self and entry == 'DEFAULT':
02113                 continue
02114             if copy:
02115                 section.comments[entry] = section._cs_section_comments[entry]
02116                 section.inline_comments[entry] = (
02117                     section._cs_section_inline_comments[entry])
02118             check = self.validate(validator, preserve_errors=preserve_errors,
02119                 copy=copy, section=section[entry])
02120             out[entry] = check
02121             if check == False:
02122                 ret_true = False
02123             elif check == True:
02124                 ret_false = False
02125             else:
02126                 ret_true = False
02127                 ret_false = False
02128         #
02129         if ret_true:
02130             return True
02131         elif ret_false:
02132             return False
02133         else:
02134             return out

Here is the call graph for this function:

Here is the caller graph for this function:

def configobj.Section.values (   self) [inherited]

Definition at line 675 of file configobj.py.

00675 
00676     def values(self):
00677         """ """
00678         return [self[key] for key in (self.scalars + self.sections)]

Here is the caller graph for this function:

def configobj.Section.walk (   self,
  function,
  raise_errors = True,
  call_on_sections = False,
  keywargs 
) [inherited]
Walk every member and call a function on the keyword and value.

Return a dictionary of the return values

If the function raises an exception, raise the errror
unless ``raise_errors=False``, in which case set the return value to
``False``.

Any unrecognised keyword arguments you pass to walk, will be pased on
to the function you pass in.

Note: if ``call_on_sections`` is ``True`` then - on encountering a
subsection, *first* the function is called for the *whole* subsection,
and then recurses into its members. This means your function must be
able to handle strings, dictionaries and lists. This allows you
to change the key of subsections as well as for ordinary members. The
return value when called on the whole subsection has to be discarded.

See  the encode and decode methods for examples, including functions.

.. caution::

    You can use ``walk`` to transform the names of members of a section
    but you mustn't add or delete members.

>>> config = '''[XXXXsection]
... XXXXkey = XXXXvalue'''.splitlines()
>>> cfg = ConfigObj(config)
>>> cfg
{'XXXXsection': {'XXXXkey': 'XXXXvalue'}}
>>> def transform(section, key):
...     val = section[key]
...     newkey = key.replace('XXXX', 'CLIENT1')
...     section.rename(key, newkey)
...     if isinstance(val, (tuple, list, dict)):
...         pass
...     else:
...         val = val.replace('XXXX', 'CLIENT1')
...         section[newkey] = val
>>> cfg.walk(transform, call_on_sections=True)
{'CLIENT1section': {'CLIENT1key': None}}
>>> cfg
{'CLIENT1section': {'CLIENT1key': 'CLIENT1value'}}

Definition at line 784 of file configobj.py.

00784 
00785             call_on_sections=False, **keywargs):
00786         """
00787         Walk every member and call a function on the keyword and value.
00788         
00789         Return a dictionary of the return values
00790         
00791         If the function raises an exception, raise the errror
00792         unless ``raise_errors=False``, in which case set the return value to
00793         ``False``.
00794         
00795         Any unrecognised keyword arguments you pass to walk, will be pased on
00796         to the function you pass in.
00797         
00798         Note: if ``call_on_sections`` is ``True`` then - on encountering a
00799         subsection, *first* the function is called for the *whole* subsection,
00800         and then recurses into its members. This means your function must be
00801         able to handle strings, dictionaries and lists. This allows you
00802         to change the key of subsections as well as for ordinary members. The
00803         return value when called on the whole subsection has to be discarded.
00804         
00805         See  the encode and decode methods for examples, including functions.
00806         
00807         .. caution::
00808         
00809             You can use ``walk`` to transform the names of members of a section
00810             but you mustn't add or delete members.
00811         
00812         >>> config = '''[XXXXsection]
00813         ... XXXXkey = XXXXvalue'''.splitlines()
00814         >>> cfg = ConfigObj(config)
00815         >>> cfg
00816         {'XXXXsection': {'XXXXkey': 'XXXXvalue'}}
00817         >>> def transform(section, key):
00818         ...     val = section[key]
00819         ...     newkey = key.replace('XXXX', 'CLIENT1')
00820         ...     section.rename(key, newkey)
00821         ...     if isinstance(val, (tuple, list, dict)):
00822         ...         pass
00823         ...     else:
00824         ...         val = val.replace('XXXX', 'CLIENT1')
00825         ...         section[newkey] = val
00826         >>> cfg.walk(transform, call_on_sections=True)
00827         {'CLIENT1section': {'CLIENT1key': None}}
00828         >>> cfg
00829         {'CLIENT1section': {'CLIENT1key': 'CLIENT1value'}}
00830         """
00831         out = {}
00832         # scalars first
00833         for i in range(len(self.scalars)):
00834             entry = self.scalars[i]
00835             try:
00836                 val = function(self, entry, **keywargs)
00837                 # bound again in case name has changed
00838                 entry = self.scalars[i]
00839                 out[entry] = val
00840             except Exception:
00841                 if raise_errors:
00842                     raise
00843                 else:
00844                     entry = self.scalars[i]
00845                     out[entry] = False
00846         # then sections
00847         for i in range(len(self.sections)):
00848             entry = self.sections[i]
00849             if call_on_sections:
00850                 try:
00851                     function(self, entry, **keywargs)
00852                 except Exception:
00853                     if raise_errors:
00854                         raise
00855                     else:
00856                         entry = self.sections[i]
00857                         out[entry] = False
00858                 # bound again in case name has changed
00859                 entry = self.sections[i]
00860             # previous result is discarded
00861             out[entry] = self[entry].walk(
00862                 function,
00863                 raise_errors=raise_errors,
00864                 call_on_sections=call_on_sections,
00865                 **keywargs)
00866         return out

Here is the caller graph for this function:

def configobj.ConfigObj.write (   self,
  outfile = None,
  section = None 
)
Write the current ConfigObj as a file

tekNico: FIXME: use StringIO instead of real files

>>> filename = a.filename
>>> a.filename = 'test.ini'
>>> a.write()
>>> a.filename = filename
>>> a == ConfigObj('test.ini', raise_errors=True)
1

Definition at line 1891 of file configobj.py.

01891 
01892     def write(self, outfile=None, section=None):
01893         """
01894         Write the current ConfigObj as a file
01895         
01896         tekNico: FIXME: use StringIO instead of real files
01897         
01898         >>> filename = a.filename
01899         >>> a.filename = 'test.ini'
01900         >>> a.write()
01901         >>> a.filename = filename
01902         >>> a == ConfigObj('test.ini', raise_errors=True)
01903         1
01904         """
01905         if self.indent_type is None:
01906             # this can be true if initialised from a dictionary
01907             self.indent_type = DEFAULT_INDENT_TYPE
01908         #
01909         out = []
01910         cs = self._a_to_u('#')
01911         csp = self._a_to_u('# ')
01912         if section is None:
01913             int_val = self.interpolation
01914             self.interpolation = False
01915             section = self
01916             for line in self.initial_comment:
01917                 line = self._decode_element(line)
01918                 stripped_line = line.strip()
01919                 if stripped_line and not stripped_line.startswith(cs):
01920                     line = csp + line
01921                 out.append(line)
01922         #
01923         indent_string = self.indent_type * section.depth
01924         for entry in (section.scalars + section.sections):
01925             if entry in section.defaults:
01926                 # don't write out default values
01927                 continue
01928             for comment_line in section.comments[entry]:
01929                 comment_line = self._decode_element(comment_line.lstrip())
01930                 if comment_line and not comment_line.startswith(cs):
01931                     comment_line = csp + comment_line
01932                 out.append(indent_string + comment_line)
01933             this_entry = section[entry]
01934             comment = self._handle_comment(section.inline_comments[entry])
01935             #
01936             if isinstance(this_entry, dict):
01937                 # a section
01938                 out.append(self._write_marker(
01939                     indent_string,
01940                     this_entry.depth,
01941                     entry,
01942                     comment))
01943                 out.extend(self.write(section=this_entry))
01944             else:
01945                 out.append(self._write_line(
01946                     indent_string,
01947                     entry,
01948                     this_entry,
01949                     comment))
01950         #
01951         if section is self:
01952             for line in self.final_comment:
01953                 line = self._decode_element(line)
01954                 stripped_line = line.strip()
01955                 if stripped_line and not stripped_line.startswith(cs):
01956                     line = csp + line
01957                 out.append(line)
01958             self.interpolation = int_val
01959         #
01960         if section is not self:
01961             return out
01962         #
01963         if (self.filename is None) and (outfile is None):
01964             # output a list of lines
01965             # might need to encode
01966             # NOTE: This will *screw* UTF16, each line will start with the BOM
01967             if self.encoding:
01968                 out = [l.encode(self.encoding) for l in out]
01969             if (self.BOM and ((self.encoding is None) or
01970                 (BOM_LIST.get(self.encoding.lower()) == 'utf_8'))):
01971                 # Add the UTF8 BOM
01972                 if not out:
01973                     out.append('')
01974                 out[0] = BOM_UTF8 + out[0]
01975             return out
01976         #
01977         # Turn the list to a string, joined with correct newlines
01978         output = (self._a_to_u(self.newlines or os.linesep)
01979             ).join(out)
01980         if self.encoding:
01981             output = output.encode(self.encoding)
01982         if (self.BOM and ((self.encoding is None) or
01983             (BOM_LIST.get(self.encoding.lower()) == 'utf_8'))):
01984             # Add the UTF8 BOM
01985             output = BOM_UTF8 + output
01986         if outfile is not None:
01987             outfile.write(output)
01988         else:
01989             h = open(self.filename, 'wb')
01990             h.write(output)
01991             h.close()

Here is the caller graph for this function:


Member Data Documentation

tuple configobj.ConfigObj._keyword [static, private]
Initial value:
re.compile(r'''^ # line start
    (\s*)                   # indentation
    (                       # keyword
        (?:".*?")|          # double quotes
        (?:'.*?')|          # single quotes
        (?:[^'"=].*?)       # no quotes    )    \s*=\s*                 # divider    (.*)                    # value (including list values and comments)    $   # line end    ''',        re.VERBOSE)    _sectionmarker = re.compile(r'''^    (\s*)                     # 1: indentation    ((?:\[\s*)+)              # 2: section marker open    (                         # 3: section name open        (?:"\s*\S.*?\s*")|    # at least one non-space with double quotes        (?:'\s*\S.*?\s*')|    # at least one non-space with single quotes        (?:[^'"\s].*?)        # at least one non-space unquoted
    )                         # section name close
    ((?:\s*\])+)              # 4: section marker close
    \s*(\#.*)?                # 5: optional comment
    $''',
        re.VERBOSE)

Definition at line 1030 of file configobj.py.

tuple configobj.ConfigObj._valueexp [static, private]

Definition at line 1060 of file configobj.py.

Definition at line 491 of file configobj.py.

Definition at line 494 of file configobj.py.

Definition at line 501 of file configobj.py.

Definition at line 483 of file configobj.py.

Definition at line 1906 of file configobj.py.

Definition at line 492 of file configobj.py.

Definition at line 1913 of file configobj.py.

Definition at line 481 of file configobj.py.

Definition at line 489 of file configobj.py.

Definition at line 479 of file configobj.py.

configobj.ConfigObj.quot = noquot [static]

Definition at line 1669 of file configobj.py.

Definition at line 485 of file configobj.py.

Definition at line 487 of file configobj.py.


The documentation for this class was generated from the following file: