Package pythonutils :: Module configobj :: Class Section
[hide private]
[frames] | no frames]

Class Section
source code

object --+    
         |    
      dict --+
             |
            Section
Known Subclasses:
ConfigObj

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

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

Interpolation is tried first from the 'DEFAULT' section of this object, next from the 'DEFAULT' section of the parent, lastly the main object.

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.



Instance Methods [hide private]
  __init__(self, parent, depth, main, indict=None, name=None)
parent is the section above
  _interpolate(self, value)
Nicked from ConfigParser.
  _interpolation_replace(self, match)
  __getitem__(self, key)
Fetch the item and do string interpolation.
  __setitem__(self, key, value, unrepr=False)
Correctly set a value.
  __delitem__(self, key)
Remove items from the sequence when deleting.
  get(self, key, default=None)
A version of get that doesn't bypass string interpolation.
  update(self, indict)
A version of update that uses our __setitem__.
  pop(self, key, *args)
If key is not found, d is returned if given, otherwise KeyError is raised
  popitem(self)
Pops the first (key,val)
  clear(self)
A version of clear that also affects scalars/sections Also clears comments and configspec.
  setdefault(self, key, default=None)
A version of setdefault that sets sequence if appropriate.
  items(self)
  keys(self)
  values(self)
  iteritems(self)
  iterkeys(self)
iter(x)
  __iter__(self)
iter(x)
  itervalues(self)
  __repr__(self)
repr(x)
  __str__(self)
repr(x)
  dict(self)
Return a deepcopy of self as a dictionary.
  merge(self, indict)
A recursive update - useful for merging config files.
  rename(self, oldkey, newkey)
Change a keyname to another, without changing position in sequence.
  walk(self, function, raise_errors=True, call_on_sections=False, **keywargs)
Walk every member and call a function on the keyword and value.
  decode(self, encoding)
Decode all strings and values to unicode, using the specified encoding.
  encode(self, encoding)
Encode all strings and values from unicode, using the specified encoding.
  istrue(self, key)
A deprecated version of as_bool.
  as_bool(self, key)
Accepts a key as input.
  as_int(self, key)
A convenience method which coerces the specified value to an integer.
  as_float(self, key)
A convenience method which coerces the specified value to a float.

Inherited from dict: __cmp__, __contains__, __eq__, __ge__, __getattribute__, __gt__, __hash__, __le__, __len__, __lt__, __ne__, __new__, copy, fromkeys, has_key

Inherited from object: __delattr__, __reduce__, __reduce_ex__, __setattr__


Class Variables [hide private]
_KEYCRE  

Inherited from object: __class__


Method Details [hide private]

__init__(self, parent, depth, main, indict=None, name=None)
(Constructor)

source code 
  • 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
Overrides: dict.__init__

_interpolate(self, value)

source code 
Nicked from ConfigParser.

_interpolation_replace(self, match)

source code 

__getitem__(self, key)
(Indexing operator)

source code 
Fetch the item and do string interpolation.
Overrides: dict.__getitem__

__setitem__(self, key, value, unrepr=False)
(Index assignment operator)

source code 

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.

Overrides: dict.__setitem__

__delitem__(self, key)
(Index deletion operator)

source code 
Remove items from the sequence when deleting.
Overrides: dict.__delitem__

get(self, key, default=None)

source code 
A version of get that doesn't bypass string interpolation.
Returns:
D[k] if k in D, else d

Overrides: dict.get

update(self, indict)

source code 
A version of update that uses our __setitem__.
Returns:
None

Overrides: dict.update

pop(self, key, *args)

source code 
Returns:
v, remove specified key and return the corresponding value

Overrides: dict.pop

popitem(self)

source code 
Pops the first (key,val)
Returns:
(k, v), remove and return some (key, value) pair as a

Overrides: dict.popitem

clear(self)

source code 

A version of clear that also affects scalars/sections Also clears comments and configspec.

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

Overrides: dict.clear

setdefault(self, key, default=None)

source code 
A version of setdefault that sets sequence if appropriate.
Returns:
D.get(k,d), also set D[k]=d if k not in D

Overrides: dict.setdefault

items(self)

source code 
Returns:
list of D's (key, value) pairs, as 2-tuples

Overrides: dict.items

keys(self)

source code 
Returns:
list of D's keys

Overrides: dict.keys

values(self)

source code 
Returns:
list of D's values

Overrides: dict.values

iteritems(self)

source code 
Returns:
an iterator over the (key, value) items of D

Overrides: dict.iteritems

iterkeys(self)

source code 
Returns:
an iterator over the keys of D

Overrides: dict.iterkeys

__iter__(self)

source code 
Returns:
an iterator over the keys of D

Overrides: dict.__iter__

itervalues(self)

source code 
Returns:
an iterator over the values of D

Overrides: dict.itervalues

__repr__(self)
(Representation operator)

source code 
repr(x)
Overrides: dict.__repr__
(inherited documentation)

__str__(self)
(Informal representation operator)

source code 
repr(x)
Overrides: object.__str__
(inherited documentation)

dict(self)

source code 

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

merge(self, indict)

source code 

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'}}}

rename(self, oldkey, newkey)

source code 

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.

walk(self, function, raise_errors=True, call_on_sections=False, **keywargs)

source code 

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 it's 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'}}

decode(self, encoding)

source code 

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

encode(self, encoding)

source code 

Encode all strings and values from unicode, using the specified encoding.

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

istrue(self, key)

source code 
A deprecated version of as_bool.

as_bool(self, key)

source code 

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

as_int(self, key)

source code 

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

as_float(self, key)

source code 

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

Class Variable Details [hide private]

_KEYCRE

Value:
%\(([^\)]*)\)s|.