external.configobj — IPython 0.10.2 documentation

### Navigation

- index
- modules |
- next |
- previous |
- IPython 0.10.2 documentation »
- The IPython API »

# external.configobj

## Module: `external.configobj`

Inheritance diagram for `IPython.external.configobj`:

## Classes

### `Builder`

class `IPython.external.configobj.` `Builder`

  Bases: `object`

  `__init__`()

    x.__init__(...) initializes x; see x.__class__.__doc__ for signature

  `build`()
  `build_Add`()
  `build_Const`()
  `build_Dict`()
  `build_Getattr`()
  `build_List`()
  `build_Name`()
  `build_Tuple`()
  `build_UnaryAdd`()
  `build_UnarySub`()

### `ConfigObj`

class `IPython.external.configobj.` `ConfigObj`(infile=None, options=None, **kwargs)

  Bases: `IPython.external.configobj.Section`

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

  `__init__`()

    Parse a config file or create a config file object.

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

  `reload`()

    Reload a ConfigObj from file.

    This method raises a `ReloadError` if the ConfigObj doesn’t have a filename attribute pointing to a file.

  `reset`()

    Clear ConfigObj instance and restore to ‘freshly created’ state.

  `validate`()

    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` indicates 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.

  `write`()

    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

### `ConfigObjError`

class `IPython.external.configobj.` `ConfigObjError`(message='', line_number=None, line='')

  Bases: `exceptions.SyntaxError`

  This is the base class for all errors that ConfigObj raises. It is a subclass of SyntaxError.

  `__init__`()

### `ConfigParserInterpolation`

class `IPython.external.configobj.` `ConfigParserInterpolation`(section)

  Bases: `IPython.external.configobj.InterpolationEngine`

  Behaves like ConfigParser.

  `__init__`()

### `ConfigspecError`

class `IPython.external.configobj.` `ConfigspecError`(message='', line_number=None, line='')

  Bases: `IPython.external.configobj.ConfigObjError`

  An error occured whilst parsing a configspec.

  `__init__`()

### `DuplicateError`

class `IPython.external.configobj.` `DuplicateError`(message='', line_number=None, line='')

  Bases: `IPython.external.configobj.ConfigObjError`

  The keyword or section specified already exists.

  `__init__`()

### `InterpolationEngine`

class `IPython.external.configobj.` `InterpolationEngine`(section)

  Bases: `object`

  A helper class to help perform string interpolation.

  This class is an abstract base class; its descendants perform the actual work.

  `__init__`()
  `interpolate`()

### `InterpolationError`

class `IPython.external.configobj.` `InterpolationError`(message='', line_number=None, line='')

  Bases: `IPython.external.configobj.ConfigObjError`

  Base class for the two interpolation errors.

  `__init__`()

### `InterpolationLoopError`

class `IPython.external.configobj.` `InterpolationLoopError`(option)

  Bases: `IPython.external.configobj.InterpolationError`

  Maximum interpolation depth exceeded in string interpolation.

  `__init__`()

### `MissingInterpolationOption`

class `IPython.external.configobj.` `MissingInterpolationOption`(option)

  Bases: `IPython.external.configobj.InterpolationError`

  A value specified for interpolation was missing.

  `__init__`()

### `NestingError`

class `IPython.external.configobj.` `NestingError`(message='', line_number=None, line='')

  Bases: `IPython.external.configobj.ConfigObjError`

  This error indicates a level of nesting that doesn’t match.

  `__init__`()

### `ParseError`

class `IPython.external.configobj.` `ParseError`(message='', line_number=None, line='')

  Bases: `IPython.external.configobj.ConfigObjError`

  This error indicates that a line is badly written. It is neither a valid `key = value` line, nor a valid section marker line.

  `__init__`()

### `ReloadError`

class `IPython.external.configobj.` `ReloadError`

  Bases: `exceptions.IOError`

  A ‘reload’ operation failed. This exception is a subclass of `IOError`.

  `__init__`()

### `RepeatSectionError`

class `IPython.external.configobj.` `RepeatSectionError`(message='', line_number=None, line='')

  Bases: `IPython.external.configobj.ConfigObjError`

  This error indicates additional sections in a section with a `__many__` (repeated) section.

  `__init__`()

### `Section`

class `IPython.external.configobj.` `Section`(parent, depth, main, indict=None, name=None)

  Bases: `dict`

  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.

  `__init__`()
    - 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
  `as_bool`()

    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_float`()

    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

  `as_int`()

    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

  `clear`()

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

    Leaves other attributes alone :
      depth/main/parent are not affected
  `decode`()

    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

  `dict`()

    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

  `encode`()

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

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

  `get`()

    A version of `get` that doesn’t bypass string interpolation.

  `istrue`()

    A deprecated version of `as_bool`.

  `items`()
  `iteritems`()
  `iterkeys`()
  `itervalues`()
  `keys`()
  `merge`()

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

  `pop`()

    ‘D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised’

  `popitem`()

    Pops the first (key,val)

  `rename`()

    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.

  `restore_default`()

    Restore (and return) default value for the specified key.

    This method will only work for a ConfigObj that was created with a configspec and has been validated.

    If there is no default value for this key, `KeyError` is raised.

  `restore_defaults`()

    Recursively restore default values to all members that have them.

    This method will only work for a ConfigObj that was created with a configspec and has been validated.

    It doesn’t delete or modify entries without default values.

  `setdefault`()

    A version of setdefault that sets sequence if appropriate.

  `update`()

    A version of update that uses our `__setitem__`.

  `values`()
  `walk`()

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

### `SimpleVal`

class `IPython.external.configobj.` `SimpleVal`

  Bases: `object`

  A simple validator. Can be used to check that all members expected are present.

  To use it, provide a configspec with all your members in (the value given will be ignored). Pass an instance of `SimpleVal` to the `validate` method of your `ConfigObj`. `validate` will return `True` if all members are present, or a dictionary with True/False meaning present/missing. (Whole missing sections will be replaced with `False`)

  `__init__`()
  `check`()

    A dummy check method, always returns the value unchanged.

### `TemplateInterpolation`

class `IPython.external.configobj.` `TemplateInterpolation`(section)

  Bases: `IPython.external.configobj.InterpolationEngine`

  Behaves like string.Template.

  `__init__`()

### `UnknownType`

class `IPython.external.configobj.` `UnknownType`

  Bases: `exceptions.Exception`

  `__init__`()

    x.__init__(...) initializes x; see x.__class__.__doc__ for signature

### `UnreprError`

class `IPython.external.configobj.` `UnreprError`(message='', line_number=None, line='')

  Bases: `IPython.external.configobj.ConfigObjError`

  An error parsing in unrepr mode.

  `__init__`()

## Functions

`IPython.external.configobj.` `flatten_errors`()

  An example function that will turn a nested dictionary of results (as returned by `ConfigObj.validate`) into a flat list.

  `cfg` is the ConfigObj instance being checked, `res` is the results dictionary returned by `validate`.

  (This is a recursive function, so you shouldn’t use the `levels` or `results` arguments - they are used by the function.

  Returns a list of keys that failed. Each member of the list is a tuple :

      ([list of sections...], key, result)

  If `validate` was called with `preserve_errors=False` (the default) then `result` will always be `False`.

  list of sections is a flattened list of sections that the key was found in.

  If the section was missing then key will be `None`.

  If the value (or section) was missing then `result` will be `False`.

  If `validate` was called with `preserve_errors=True` and a value was present, but failed the check, then `result` will be the exception object returned. You can use this as a string that describes the failure.

  For example The value “3” is of the wrong type.

      >>> import validate
      >>> vtor = validate.Validator()
      >>> my_ini = '''
      ...     option1 = True
      ...     [section1]
      ...     option1 = True
      ...     [section2]
      ...     another_option = Probably
      ...     [section3]
      ...     another_option = True
      ...     [[section3b]]
      ...     value = 3
      ...     value2 = a
      ...     value3 = 11
      ...     '''
      >>> my_cfg = '''
      ...     option1 = boolean()
      ...     option2 = boolean()
      ...     option3 = boolean(default=Bad_value)
      ...     [section1]
      ...     option1 = boolean()
      ...     option2 = boolean()
      ...     option3 = boolean(default=Bad_value)
      ...     [section2]
      ...     another_option = boolean()
      ...     [section3]
      ...     another_option = boolean()
      ...     [[section3b]]
      ...     value = integer
      ...     value2 = integer
      ...     value3 = integer(0, 10)
      ...         [[[section3b-sub]]]
      ...         value = string
      ...     [section4]
      ...     another_option = boolean()
      ...     '''
      >>> cs = my_cfg.split('\n')
      >>> ini = my_ini.split('\n')
      >>> cfg = ConfigObj(ini, configspec=cs)
      >>> res = cfg.validate(vtor, preserve_errors=True)
      >>> errors = []
      >>> for entry in flatten_errors(cfg, res):
      ...     section_list, key, error = entry
      ...     section_list.insert(0, '[root]')
      ...     if key is not None:
      ...        section_list.append(key)
      ...     else:
      ...         section_list.append('[missing]')
      ...     section_string = ', '.join(section_list)
      ...     errors.append((section_string, ' = ', error))
      >>> errors.sort()
      >>> for entry in errors:
      ...     print entry[0], entry[1], (entry[2] or 0)
      [root], option2  =  0
      [root], option3  =  the value "Bad_value" is of the wrong type.
      [root], section1, option2  =  0
      [root], section1, option3  =  the value "Bad_value" is of the wrong type.
      [root], section2, another_option  =  the value "Probably" is of the wrong type.
      [root], section3, section3b, section3b-sub, [missing]  =  0
      [root], section3, section3b, value2  =  the value "a" is of the wrong type.
      [root], section3, section3b, value3  =  the value "11" is too big.
      [root], section4, [missing]  =  0

`IPython.external.configobj.` `getObj`()

`IPython.external.configobj.` `match_utf8`()

`IPython.external.configobj.` `unrepr`()

### Navigation

- index
- modules |
- next |
- previous |
- IPython 0.10.2 documentation »
- The IPython API »