Back to index

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

List of all members.

Public Member Functions

def __init__
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

 parent
 main
 depth
 scalars
 sections
 name
 comments
 inline_comments
 configspec
 defaults

Private Member Functions

def _interpolate

Private Attributes

 _order
 _configspec_comments
 _configspec_inline_comments
 _cs_section_comments
 _cs_section_inline_comments
 _interpolation_engine

Static Private Attributes

 __iter__ = iterkeys
 __str__ = __repr__

Detailed Description

A dictionary-like object that represents a section in a config file.

It does string interpolation if the 'interpolation' attribute
of the 'main' object is set to True.

Interpolation is tried first from this object, then from the 'DEFAULT'
section of this object, next from the parent and its 'DEFAULT' section,
and so on until the main object is reached.

A Section will behave like an ordered dictionary - following the
order of the ``scalars`` and ``sections`` attributes.
You can use this to change the order of members.

Iteration follows the order: scalars, then sections.

Definition at line 450 of file configobj.py.


Constructor & Destructor Documentation

def configobj.Section.__init__ (   self,
  parent,
  depth,
  main,
  indict = None,
  name = None 
)
* parent is the section above
* depth is the depth level of this section
* main is the main ConfigObj
* indict is a dictionary to initialise the section with

Definition at line 468 of file configobj.py.

00468 
00469     def __init__(self, parent, depth, main, indict=None, name=None):
00470         """
00471         * parent is the section above
00472         * depth is the depth level of this section
00473         * main is the main ConfigObj
00474         * indict is a dictionary to initialise the section with
00475         """
00476         if indict is None:
00477             indict = {}
00478         dict.__init__(self)
00479         # used for nesting level *and* interpolation
00480         self.parent = parent
00481         # used for the interpolation attribute
00482         self.main = main
00483         # level of nesting depth of this Section
00484         self.depth = depth
00485         # the sequence of scalar values in this Section
00486         self.scalars = []
00487         # the sequence of sections in this Section
00488         self.sections = []
00489         # purely for information
00490         self.name = name
00491         # for comments :-)
00492         self.comments = {}
00493         self.inline_comments = {}
00494         # for the configspec
00495         self.configspec = {}
00496         self._order = []
00497         self._configspec_comments = {}
00498         self._configspec_inline_comments = {}
00499         self._cs_section_comments = {}
00500         self._cs_section_inline_comments = {}
00501         # for defaults
00502         self.defaults = []
00503         #
00504         # we do this explicitly so that __setitem__ is used properly
00505         # (rather than just passing to ``dict.__init__``)
00506         for entry in indict:
00507             self[entry] = indict[entry]


Member Function Documentation

def configobj.Section.__delitem__ (   self,
  key 
)
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 
)
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:

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 
)
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.Section._interpolate (   self,
  key,
  value 
) [private]

Definition at line 508 of file configobj.py.

00508 
00509     def _interpolate(self, key, value):
00510         try:
00511             # do we already have an interpolation engine?
00512             engine = self._interpolation_engine
00513         except AttributeError:
00514             # not yet: first time running _interpolate(), so pick the engine
00515             name = self.main.interpolation
00516             if name == True:  # note that "if name:" would be incorrect here
00517                 # backwards-compatibility: interpolation=True means use default
00518                 name = DEFAULT_INTERPOLATION
00519             name = name.lower()  # so that "Template", "template", etc. all work
00520             class_ = interpolation_engines.get(name, None)
00521             if class_ is None:
00522                 # invalid value for self.main.interpolation
00523                 self.main.interpolation = False
00524                 return value
00525             else:
00526                 # save reference to engine so we don't have to do this again
00527                 engine = self._interpolation_engine = class_(self)
00528         # let the engine do the actual work
00529         return engine.interpolate(key, value)

Here is the caller graph for this function:

def configobj.Section.as_bool (   self,
  key 
)
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 
)
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 
)
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)
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 
)
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)
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 
)
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 
)
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 
)
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)

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:

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:

Definition at line 683 of file configobj.py.

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

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)

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 
)
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 
)

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)
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 
)
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 
)
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 
)
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.Section.values (   self)

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 
)
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:


Member Data Documentation

configobj.Section.__iter__ = iterkeys [static, private]

Definition at line 687 of file configobj.py.

configobj.Section.__str__ = __repr__ [static, private]

Definition at line 697 of file configobj.py.

Definition at line 496 of file configobj.py.

Definition at line 497 of file configobj.py.

Definition at line 498 of file configobj.py.

Definition at line 499 of file configobj.py.

Definition at line 526 of file configobj.py.

Definition at line 495 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 492 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.

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: