| |
- __builtin__.object
-
- SimpleVal
- Section(__builtin__.dict)
-
- ConfigObj
- exceptions.Exception
-
- UnknownType
- exceptions.SyntaxError(exceptions.StandardError)
-
- ConfigObjError
-
- ConfigspecError
- DuplicateError
- InterpolationError
-
- InterpolationDepthError
- MissingInterpolationOption
- NestingError
- ParseError
- RepeatSectionError
- UnreprError
class ConfigObj(Section) |
|
An object to read, create, and write config files. |
|
- Method resolution order:
- ConfigObj
- Section
- __builtin__.dict
- __builtin__.object
Methods defined here:
- __init__(self, infile=None, options=None, **kwargs)
- Parse or create a config file object.
``ConfigObj(infile=None, options=None, **kwargs)``
- __repr__(self)
- save(self)
- 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.
- write(self, outfile=None, section=None)
- Write the current ConfigObj as a file
tekNico: FIXME-IGNORED: 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
Methods inherited from Section:
- __delitem__(self, key)
- Remove items from the sequence when deleting.
- __getitem__(self, key)
- Fetch the item and do string interpolation.
- __iter__ = iterkeys(self)
- __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.
- __str__ = __repr__(self)
- 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
- 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
- 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
- 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
- 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
- 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
- encode(self, encoding)
- Encode all strings and values from unicode,
using the specified encoding.
Works with subsections and list values.
Uses the ``walk`` method.
- 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)
- itervalues(self)
- keys(self)
- 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'}}}
- pop(self, key, *args)
- popitem(self)
- Pops the first (key,val)
- 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.
- 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.
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'}}
Data and other attributes inherited from Section:
- __dict__ = <dictproxy object>
- dictionary for instance variables (if defined)
- __weakref__ = <attribute '__weakref__' of 'Section' objects>
- list of weak references to the object (if defined)
Methods inherited from __builtin__.dict:
- __cmp__(...)
- x.__cmp__(y) <==> cmp(x,y)
- __contains__(...)
- D.__contains__(k) -> True if D has a key k, else False
- __eq__(...)
- x.__eq__(y) <==> x==y
- __ge__(...)
- x.__ge__(y) <==> x>=y
- __getattribute__(...)
- x.__getattribute__('name') <==> x.name
- __gt__(...)
- x.__gt__(y) <==> x>y
- __hash__(...)
- x.__hash__() <==> hash(x)
- __le__(...)
- x.__le__(y) <==> x<=y
- __len__(...)
- x.__len__() <==> len(x)
- __lt__(...)
- x.__lt__(y) <==> x<y
- __ne__(...)
- x.__ne__(y) <==> x!=y
- copy(...)
- D.copy() -> a shallow copy of D
- has_key(...)
- D.has_key(k) -> True if D has a key k, else False
Data and other attributes inherited from __builtin__.dict:
- __new__ = <built-in method __new__ of type object>
- T.__new__(S, ...) -> a new object with type S, a subtype of T
- fromkeys = <built-in method fromkeys of type object>
- dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
v defaults to None.
|
class SimpleVal(__builtin__.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``) |
|
Methods defined here:
- __init__(self)
- check(self, check, member, missing=False)
- A dummy check method, always returns the value unchanged.
Data and other attributes defined here:
- __dict__ = <dictproxy object>
- dictionary for instance variables (if defined)
- __weakref__ = <attribute '__weakref__' of 'SimpleVal' objects>
- list of weak references to the object (if defined)
|
|