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

Class ConfigObj
source code

object --+        
         |        
      dict --+    
             |    
       Section --+
                 |
                ConfigObj

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

Instance Methods [hide private]
  __init__(self, infile=None, options=None, **kwargs)
Parse or create a config file object.
  __repr__(self)
repr(x)
  _handle_bom(self, infile)
Handle any BOM, and decode if necessary.
  _a_to_u(self, string)
Decode ascii strings to unicode if a self.encoding is specified.
  _decode(self, infile, encoding)
Decode infile to unicode.
  _decode_element(self, line)
Decode element to unicode if necessary.
  _str(self, value)
Used by stringify within validate, to turn non-string values into strings.
  _parse(self, infile)
Actually parse the config file.
  _match_depth(self, sect, depth)
Given a section and a depth level, walk back through the sections parents to see if the depth level matches a previous section.
  _handle_error(self, text, ErrorClass, infile, cur_index)
Handle an error according to the error settings.
  _unquote(self, value)
Return an unquoted version of a value
  _quote(self, value, multiline=True)
Return a safely quoted version of a value.
  _handle_value(self, value)
Given a value string, unquote, remove comment, handle lists.
  _multiline(self, value, infile, cur_index, maxline)
Extract the value, where we are in a multiline situation.
  _handle_configspec(self, configspec)
Parse the configspec.
  _set_configspec_value(self, configspec, section)
Used to recursively set configspec values.
  _handle_repeat(self, section, configspec)
Dynamically assign configspec for repeated section.
  _write_line(self, indent_string, entry, this_entry, comment)
Write an individual line, for the write method
  _write_marker(self, indent_string, depth, entry, comment)
Write a section marker line
  _handle_comment(self, comment)
Deal with a comment.
  _compute_indent_string(self, depth)
Compute the indent string, according to current indent_type and depth
  write(self, outfile=None, section=None)
Write the current ConfigObj as a file
  validate(self, validator, preserve_errors=False, copy=False, section=None)
Test the ConfigObj against a configspec.

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__

    Inherited from Section
  __delitem__(self, key)
Remove items from the sequence when deleting.
  __getitem__(self, key)
Fetch the item and do string interpolation.
  __iter__(self)
iter(x)
  __setitem__(self, key, value, unrepr=False)
Correctly set a value.
  __str__(self)
repr(x)
  _interpolate(self, value)
Nicked from ConfigParser.
  _interpolation_replace(self, match)
  as_bool(self, key)
Accepts a key as input.
  as_float(self, key)
A convenience method which coerces the specified value to a float.
  as_int(self, key)
A convenience method which coerces the specified value to an integer.
  clear(self)
A version of clear that also affects scalars/sections Also clears comments and configspec.
  decode(self, encoding)
Decode all strings and values to unicode, using the specified encoding.
  dict(self)
Return a deepcopy of self as a dictionary.
  encode(self, encoding)
Encode all strings and values from unicode, using the specified encoding.
  get(self, key, default=None)
A version of get that doesn't bypass string interpolation.
  istrue(self, key)
A deprecated version of as_bool.
  items(self)
  iteritems(self)
  iterkeys(self)
iter(x)
  itervalues(self)
  keys(self)
  merge(self, indict)
A recursive update - useful for merging config files.
  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)
  rename(self, oldkey, newkey)
Change a keyname to another, without changing position in sequence.
  setdefault(self, key, default=None)
A version of setdefault that sets sequence if appropriate.
  update(self, indict)
A version of update that uses our __setitem__.
  values(self)
  walk(self, function, raise_errors=True, call_on_sections=False, **keywargs)
Walk every member and call a function on the keyword and value.

Class Variables [hide private]
_keyword  
_sectionmarker  
_valueexp  
_listvalueexp  
_nolistvalue  
_single_line_single  
_single_line_double  
_multi_line_single  
_multi_line_double  
_triple_quote  
_bools  

Inherited from object: __class__

    Inherited from Section
_KEYCRE  

Method Details [hide private]

__init__(self, infile=None, options=None, **kwargs)
(Constructor)

source code 

Parse or create a config file object.

ConfigObj(infile=None, options=None, **kwargs)

Overrides: Section.__init__

__repr__(self)
(Representation operator)

source code 
repr(x)
Overrides: Section.__repr__

_handle_bom(self, infile)

source code 

Handle any BOM, and decode if necessary.

If an encoding is specified, that must be used - but the BOM should still be removed (and the BOM attribute set).

(If the encoding is wrongly specified, then a BOM for an alternative encoding won't be discovered or removed.)

If an encoding is not specified, UTF8 or UTF16 BOM will be detected and removed. The BOM attribute will be set. UTF16 will be decoded to unicode.

NOTE: This method must not be called with an empty infile.

Specifying the wrong encoding is likely to cause a UnicodeDecodeError.

infile must always be returned as a list of lines, but may be passed in as a single string.

_a_to_u(self, string)

source code 
Decode ascii strings to unicode if a self.encoding is specified.

_decode(self, infile, encoding)

source code 

Decode infile to unicode. Using the specified encoding.

if is a string, it also needs converting to a list.

_decode_element(self, line)

source code 
Decode element to unicode if necessary.

_str(self, value)

source code 
Used by stringify within validate, to turn non-string values into strings.

_parse(self, infile)

source code 
Actually parse the config file.

_match_depth(self, sect, depth)

source code 

Given a section and a depth level, walk back through the sections parents to see if the depth level matches a previous section.

Return a reference to the right section, or raise a SyntaxError.

_handle_error(self, text, ErrorClass, infile, cur_index)

source code 

Handle an error according to the error settings.

Either raise the error or store it. The error will have occured at cur_index

_unquote(self, value)

source code 
Return an unquoted version of a value

_quote(self, value, multiline=True)

source code 

Return a safely quoted version of a value.

Raise a ConfigObjError if the value cannot be safely quoted. If multiline is True (default) then use triple quotes if necessary.

Don't quote values that don't need it. Recursively quote members of a list and return a comma joined list. Multiline is False for lists. Obey list syntax for empty and single member lists.

If list_values=False then the value is only quoted if it contains a ``

`` (is multiline).

If write_empty_values is set, and the value is an empty string, it won't be quoted.

_handle_value(self, value)

source code 
Given a value string, unquote, remove comment, handle lists. (including empty and single member lists)

_multiline(self, value, infile, cur_index, maxline)

source code 
Extract the value, where we are in a multiline situation.

_handle_configspec(self, configspec)

source code 
Parse the configspec.

_set_configspec_value(self, configspec, section)

source code 
Used to recursively set configspec values.

_handle_repeat(self, section, configspec)

source code 
Dynamically assign configspec for repeated section.

_write_line(self, indent_string, entry, this_entry, comment)

source code 
Write an individual line, for the write method

_write_marker(self, indent_string, depth, entry, comment)

source code 
Write a section marker line

_handle_comment(self, comment)

source code 
Deal with a comment.

_compute_indent_string(self, depth)

source code 
Compute the indent string, according to current indent_type and depth

write(self, outfile=None, section=None)

source code 

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

validate(self, validator, preserve_errors=False, copy=False, section=None)

source code 

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.


Class Variable Details [hide private]

_keyword

Value:
^(\s*)((?:".*?")|(?:'.*?')|(?:[^'"=].*?))\s*=\s*(.*)$                  
      

_sectionmarker

Value:
^(\s*)((?:\[\s*)+)((?:"\s*\S.*?\s*")|(?:'\s*\S.*?\s*')|(?:[^'"\s].*?))\
((?:\s*\])+)\s*(#.*)?$                                                 
      

_valueexp

Value:
^(?:(?:((?:(?:(?:".*?")|(?:'.*?')|(?:[^'",#][^,#]*?))\s*,\s*)*)((?:".*\
?")|(?:'.*?')|(?:[^'",#\s][^,]*?)|(?:(?!,)))?)|(,))\s*(#.*)?$          
      

_listvalueexp

Value:
((?:".*?")|(?:'.*?')|(?:[^'",#].*?))\s*,\s*                            
      

_nolistvalue

Value:
^((?:".*?")|(?:'.*?')|(?:[^'"#].*?)|(?:))\s*(#.*)?$                    
      

_single_line_single

Value:
^'''(.*?)'''\s*(#.*)?$                                                 
      

_single_line_double

Value:
^"""(.*?)"""\s*(#.*)?$                                                 
      

_multi_line_single

Value:
^(.*?)'''\s*(#.*)?$                                                    
      

_multi_line_double

Value:
^(.*?)"""\s*(#.*)?$                                                    
      

_triple_quote

Value:
{'"""': (<_sre.SRE_Pattern object at 0x00B96410>,
         <_sre.SRE_Pattern object at 0x00D3E020>),
 "'''": (<_sre.SRE_Pattern object at 0x00B96368>,
         <_sre.SRE_Pattern object at 0x00B39D30>)}                     
      

_bools

Value:
{'0': False,
 '1': True,
 'false': False,
 'no': False,
 'off': False,
 'on': True,
 'true': True,
 'yes': True}