~ubuntu-branches/debian/stretch/configobj/stretch

« back to all changes in this revision

Viewing changes to docs/configobj.txt

  • Committer: Package Import Robot
  • Author(s): Benjamin Drung
  • Date: 2014-08-28 18:42:29 UTC
  • mfrom: (1.3.4)
  • Revision ID: package-import@ubuntu.com-20140828184229-yisw15o0j2r334jx
Tags: 5.0.6-1
* Team upload.
* Update watch file to point to GitHub releases.
* Bump Standards-Version to 3.9.5
* Use the pybuild buildsystem.
* Release a package for Python 3. (Closes: #660172)
* Refresh eggify.diff
* Drop report-doctest-failure.diff and py27-test.diff (fixed upstream).
* Disable triplequotes.diff (fail to apply).
* Fix deprecation warning test case.
* Adjust autopkgtests to run pytest for Python 2.x and 3.x.
* Move documentation into separate package and build Sphinx documentation.
* Update debian/copyright

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
==================================
2
 
 Reading and Writing Config Files
3
 
==================================
4
 
----------------------------------------
5
 
 ConfigObj 4 Introduction and Reference
6
 
----------------------------------------
7
 
 
8
 
:Authors: Michael Foord, Nicola Larosa
9
 
:Version: ConfigObj 4.7.2
10
 
:Date: 2010/02/27
11
 
:Homepage: `ConfigObj Homepage`_
12
 
:PyPI Entry: `ConfigObj on PyPI <http://pypi.python.org/pypi/configobj/>`_
13
 
:Development: `Google Code Homepage`_
14
 
:License: `BSD License`_
15
 
:Support: `Mailing List`_
16
 
 
17
 
.. _Mailing List: http://lists.sourceforge.net/lists/listinfo/configobj-develop
18
 
.. _Google Code Homepage: http://code.google.com/p/configobj/
19
 
 
20
 
.. meta::
21
 
   :description: ConfigObj - a Python module for easy reading and writing of 
22
 
                 config files.
23
 
   :keywords: python, script, module, config, configuration, data, persistence,
24
 
              developer, configparser
25
 
 
26
 
 
27
 
.. contents:: ConfigObj Manual
28
 
.. sectnum::
29
 
 
30
 
.. note::
31
 
 
32
 
    The best introduction to working with ConfigObj, including the powerful configuration validation system,
33
 
    is the article:
34
 
    
35
 
    * `An Introduction to ConfigObj <http://www.voidspace.org.uk/python/articles/configobj.shtml>`_
36
 
 
37
 
 
38
 
Introduction
39
 
============
40
 
 
41
 
**ConfigObj** is a simple but powerful config file reader and writer: an *ini
42
 
file round tripper*. Its main feature is that it is very easy to use, with a
43
 
straightforward programmer's interface and a simple syntax for config files.
44
 
It has lots of other features though :
45
 
    
46
 
* Nested sections (subsections), to any level
47
 
* List values
48
 
* Multiple line values
49
 
* String interpolation (substitution)
50
 
* Integrated with a powerful validation system
51
 
 
52
 
    - including automatic type checking/conversion
53
 
    - repeated sections
54
 
    - and allowing default values
55
 
 
56
 
* When writing out config files, ConfigObj preserves all comments and the order of members and sections
57
 
* Many useful methods and options for working with configuration files (like the 'reload' method)
58
 
* Full Unicode support
59
 
 
60
 
 
61
 
For support and bug reports please use the ConfigObj `Mailing List`_ or the issue tracker on the 
62
 
`Google Code Homepage`_.
63
 
 
64
 
 
65
 
Downloading
66
 
===========
67
 
 
68
 
The current version is **4.7.2**, dated 27th February 2010. ConfigObj 4 is
69
 
stable and mature. We still expect to pick up a few bugs along the way though [#]_.
70
 
 
71
 
You can get ConfigObj in the following ways :
72
 
 
73
 
* configobj.py_ from Voidspace
74
 
 
75
 
    ConfigObj has no external dependencies. This file is sufficient to access
76
 
    all the functionality except Validation_.
77
 
 
78
 
* configobj.zip_ from Voidspace
79
 
 
80
 
    This also contains validate.py_  and `this document`_.
81
 
 
82
 
* validate.py_ from Voidspace
83
 
 
84
 
 
85
 
Installing
86
 
----------
87
 
 
88
 
ConfigObj has a source distribution `on PyPI <http://pypi.python.org/pypi/configobj/>`_. If you unzip
89
 
the archive you can install it with::
90
 
 
91
 
    setup.py install
92
 
    
93
 
Alternatively, you can install with easy install or pip::
94
 
 
95
 
    easy_install configobj
96
 
 
97
 
 
98
 
Documentation
99
 
-------------
100
 
 
101
 
*configobj.zip* also contains `this document`_.
102
 
 
103
 
* You can view `this document`_ online at the `ConfigObj Homepage`_.
104
 
 
105
 
 
106
 
Development Version
107
 
-------------------
108
 
 
109
 
It is sometimes possible to get the latest *development version* of ConfigObj
110
 
from the Subversion Repository maintained on the `Google Code Homepage`_.
111
 
 
112
 
.. _configobj.py: http://www.voidspace.org.uk/downloads/configobj.py
113
 
.. _configobj.zip: http://www.voidspace.org.uk/downloads/configobj-4.7.2.zip
114
 
.. _validate.py: http://www.voidspace.org.uk/downloads/validate.py
115
 
.. _this document:
116
 
.. _configobj homepage: http://www.voidspace.org.uk/python/configobj.html
117
 
 
118
 
 
119
 
 
120
 
ConfigObj in the Real World
121
 
===========================
122
 
    
123
 
**ConfigObj** is widely used. Projects using it include:
124
 
 
125
 
* `Bazaar <http://bazaar-ng.org>`_.
126
 
 
127
 
    Bazaar is a Python distributed {acro;VCS;Version Control System}.
128
 
    ConfigObj is used to read ``bazaar.conf`` and ``branches.conf``.
129
 
 
130
 
* `Chandler <http://chandler.osafoundation.org/>`_
131
 
 
132
 
   A Python and `wxPython <http://www.wxpython.org>`_ 
133
 
   Personal Information Manager, being developed by the 
134
 
   `OSAFoundation <http://www.osafoundation.org/>`_.
135
 
 
136
 
* `matplotlib <http://matplotlib.sourceforge.net/>`_
137
 
 
138
 
    A 2D plotting library.
139
 
 
140
 
* `IPython <http://ipython.scipy.org/moin/>`_
141
 
 
142
 
    IPython is an enhanced interactive Python shell. IPython uses ConfigObj in a module called 'TConfig' that combines it with enthought `Traits <http://code.enthought.com/traits/>`_: `tconfig <http://ipython.scipy.org/ipython/ipython/browser/ipython/branches/saw/sandbox/tconfig>`_.
143
 
    
144
 
* `Elisa - the Fluendo Mediacenter <http://elisa.fluendo.com/>`_    
145
 
    
146
 
    Elisa is an open source cross-platform media center solution designed to be simple for people not particularly familiar with computers.
147
 
 
148
 
 
149
 
Getting Started
150
 
===============
151
 
 
152
 
The outstanding feature of using ConfigObj is simplicity. Most functions can be
153
 
performed with single line commands.
154
 
 
155
 
 
156
 
Reading a Config File
157
 
---------------------
158
 
 
159
 
The normal way to read a config file, is to give ConfigObj the filename :
160
 
 
161
 
.. code-block:: python
162
 
 
163
 
    from configobj import ConfigObj
164
 
    config = ConfigObj(filename)
165
 
 
166
 
You can also pass the config file in as a list of lines, or a ``StringIO``
167
 
instance, so it doesn't matter where your config data comes from.
168
 
 
169
 
You can then access members of your config file as a dictionary. Subsections
170
 
will also be dictionaries.
171
 
 
172
 
.. code-block:: python
173
 
 
174
 
    from configobj import ConfigObj
175
 
    config = ConfigObj(filename)
176
 
    #
177
 
    value1 = config['keyword1']
178
 
    value2 = config['keyword2']
179
 
    #
180
 
    section1 = config['section1']
181
 
    value3 = section1['keyword3']
182
 
    value4 = section1['keyword4']
183
 
    #
184
 
    # you could also write
185
 
    value3 = config['section1']['keyword3']
186
 
    value4 = config['section1']['keyword4']
187
 
 
188
 
 
189
 
Writing a Config File
190
 
---------------------
191
 
 
192
 
Creating a new config file is just as easy as reading one. You can specify a
193
 
filename when you create the ConfigObj, or do it later [#]_.
194
 
 
195
 
If you *don't* set a filename, then the ``write`` method will return a list of
196
 
lines instead of writing to file. See the write_ method for more details.
197
 
 
198
 
Here we show creating an empty ConfigObj, setting a filename and some values,
199
 
and then writing to file :
200
 
 
201
 
 
202
 
.. code-block:: python
203
 
 
204
 
    from configobj import ConfigObj
205
 
    config = ConfigObj()
206
 
    config.filename = filename
207
 
    #
208
 
    config['keyword1'] = value1
209
 
    config['keyword2'] = value2
210
 
    #
211
 
    config['section1'] = {}
212
 
    config['section1']['keyword3'] = value3
213
 
    config['section1']['keyword4'] = value4
214
 
    #
215
 
    section2 = {
216
 
        'keyword5': value5,
217
 
        'keyword6': value6,
218
 
        'sub-section': {
219
 
            'keyword7': value7
220
 
            }
221
 
    }
222
 
    config['section2'] = section2
223
 
    #
224
 
    config['section3'] = {}
225
 
    config['section3']['keyword 8'] = [value8, value9, value10]
226
 
    config['section3']['keyword 9'] = [value11, value12, value13]
227
 
    #
228
 
    config.write()
229
 
 
230
 
    
231
 
.. caution::
232
 
 
233
 
    Keywords and section names can only be strings [#]_. Attempting to set
234
 
    anything else will raise a ``ValueError``.
235
 
    
236
 
    See `String Interpolation and List Values`_ for an important note on
237
 
    using lists in combination with `String Interpolation`_.
238
 
 
239
 
 
240
 
Config Files
241
 
------------
242
 
 
243
 
The config files that ConfigObj will read and write are based on the 'INI'
244
 
format. This means it will read and write files created for ``ConfigParser``
245
 
[#]_.
246
 
 
247
 
Keywords and values are separated by an ``'='``, and section markers are
248
 
between square brackets. Keywords, values, and section names can be surrounded
249
 
by single or double quotes. Indentation is not significant, but can be
250
 
preserved.
251
 
 
252
 
Subsections are indicated by repeating the square brackets in the section
253
 
marker. You nest levels by using more brackets.
254
 
 
255
 
You can have list values by separating items with a comma, and values spanning
256
 
multiple lines by using triple quotes (single or double).
257
 
 
258
 
For full details on all these see `the config file format`_. Here's an example
259
 
to illustrate::
260
 
 
261
 
    # This is the 'initial_comment'
262
 
    # Which may be several lines
263
 
    keyword1 = value1
264
 
    'keyword 2' = 'value 2'
265
 
 
266
 
    [ "section 1" ]
267
 
    # This comment goes with keyword 3
268
 
    keyword 3 = value 3
269
 
    'keyword 4' = value4, value 5, 'value 6'
270
 
 
271
 
        [[ sub-section ]]    # an inline comment
272
 
        # sub-section is inside "section 1"
273
 
        'keyword 5' = 'value 7'
274
 
        'keyword 6' = '''A multiline value,
275
 
    that spans more than one line :-)
276
 
    The line breaks are included in the value.'''
277
 
 
278
 
            [[[ sub-sub-section ]]]
279
 
            # sub-sub-section is *in* 'sub-section'
280
 
            # which is in 'section 1'
281
 
            'keyword 7' = 'value 8'
282
 
 
283
 
    [section 2]    # an inline comment
284
 
    keyword8 = "value 9"
285
 
    keyword9 = value10     # an inline comment
286
 
    # The 'final_comment'
287
 
    # Which also may be several lines
288
 
 
289
 
 
290
 
ConfigObj specifications
291
 
========================
292
 
 
293
 
.. code-block:: python
294
 
 
295
 
    config = ConfigObj(infile=None, options=None, configspec=None, encoding=None,
296
 
                       interpolation=True, raise_errors=False, list_values=True,
297
 
                       create_empty=False, file_error=False, stringify=True,
298
 
                       indent_type=None, default_encoding=None, unrepr=False,
299
 
                       write_empty_values=False, _inspec=False)
300
 
 
301
 
Many of the keyword arguments are available as attributes after the config file has been
302
 
parsed.
303
 
 
304
 
.. note::
305
 
 
306
 
    New in ConfigObj 4.7.0: Instantiating ConfigObj with
307
 
    an ``options`` dictionary is now deprecated. To modify code that used to 
308
 
    do this simply unpack the dictionary in the constructor call:
309
 
    
310
 
    .. code-block:: python
311
 
    
312
 
        config = ConfigObj(filename, **options)
313
 
 
314
 
ConfigObj takes the following arguments (with the default values shown) :
315
 
 
316
 
* infile: ``None``
317
 
 
318
 
    You don't need to specify an infile. If you omit it, an empty ConfigObj will be
319
 
    created. ``infile`` *can* be :
320
 
 
321
 
    * Nothing. In which case the ``filename`` attribute of your ConfigObj will be
322
 
      ``None``. You can set a filename at any time.
323
 
 
324
 
    * A filename. What happens if the file doesn't already exist is determined by
325
 
      the options ``file_error`` and ``create_empty``. The filename will be
326
 
      preserved as the ``filename`` attribute. This can be changed at any time.
327
 
 
328
 
    * A list of lines. Any trailing newlines will be removed from the lines. The
329
 
      ``filename`` attribute of your ConfigObj will be ``None``.
330
 
 
331
 
    * A ``StringIO`` instance or file object, or any object with a ``read`` method.
332
 
      The ``filename`` attribute of your ConfigObj will be ``None`` [#]_.
333
 
 
334
 
    * A dictionary. You can initialise a ConfigObj from a dictionary [#]_. The
335
 
      ``filename`` attribute of your ConfigObj will be ``None``. All keys must be
336
 
      strings. In this case, the order of values and sections is arbitrary.
337
 
 
338
 
* 'raise_errors': ``False``
339
 
 
340
 
    When parsing, it is possible that the config file will be badly formed. The
341
 
    default is to parse the whole file and raise a single error at the end. You
342
 
    can set ``raise_errors = True`` to have errors raised immediately. See the
343
 
    exceptions_ section for more details.
344
 
 
345
 
    Altering this value after initial parsing has no effect.
346
 
 
347
 
* 'list_values': ``True``
348
 
 
349
 
    If ``True`` (the default) then list values are possible. If ``False``, the
350
 
    values are not parsed for lists.
351
 
 
352
 
    If ``list_values = False`` then single line values are not quoted or
353
 
    unquoted when reading and writing.
354
 
 
355
 
    Changing this value affects whether single line values will be quoted or 
356
 
    not when writing.
357
 
 
358
 
* 'create_empty': ``False``
359
 
 
360
 
    If this value is ``True`` and the file specified by ``infile`` doesn't
361
 
    exist, ConfigObj will create an empty file. This can be a useful test that
362
 
    the filename makes sense: an impossible filename will cause an error.
363
 
 
364
 
    Altering this value after initial parsing has no effect.
365
 
 
366
 
* 'file_error': ``False``
367
 
 
368
 
    If this value is ``True`` and the file specified by ``infile`` doesn't
369
 
    exist, ConfigObj will raise an ``IOError``.
370
 
 
371
 
    Altering this value after initial parsing has no effect.
372
 
 
373
 
* 'interpolation': ``True``
374
 
 
375
 
    Whether string interpolation is switched on or not. It is on (``True``) by
376
 
    default.
377
 
 
378
 
    You can set this attribute to change whether string interpolation is done
379
 
    when values are fetched. See the `String Interpolation`_ section for more details.
380
 
    
381
 
    New in ConfigObj 4.7.0: Interpolation will also be done in list values.
382
 
 
383
 
* 'configspec': ``None``
384
 
 
385
 
    If you want to use the validation system, you supply a configspec. This is
386
 
    effectively a type of config file that specifies a check for each member.
387
 
    This check can be used to do type conversion as well as check that the
388
 
    value is within your required parameters.
389
 
 
390
 
    You provide a configspec in the same way as you do the initial file: a
391
 
    filename, or list of lines, etc. See the validation_ section for full
392
 
    details on how to use the system.
393
 
 
394
 
    When parsed, every section has a ``configspec`` with a dictionary of
395
 
    configspec checks for *that section*.
396
 
 
397
 
* 'stringify': ``True``
398
 
 
399
 
    If you use the validation scheme, it can do type checking *and* conversion
400
 
    for you. This means you may want to set members to integers, or other
401
 
    non-string values.
402
 
 
403
 
    If 'stringify' is set to ``True`` (default) then non-string values will
404
 
    be converted to strings when you write the config file. The validation_
405
 
    process converts values from strings to the required type.
406
 
 
407
 
    If 'stringify' is set to ``False``, attempting to set a member to a
408
 
    non-string value [#]_ will raise a ``TypeError`` (no type conversion is
409
 
    done by validation).
410
 
 
411
 
* 'indent_type': ``'    '``
412
 
 
413
 
    Indentation is not significant; it can however be present in the input and
414
 
    output config. Any combination of tabs and spaces may be used: the string
415
 
    will be repeated for each level of indentation. Typical values are: ``''``
416
 
    (no indentation), ``'    '`` (indentation with four spaces, the default),
417
 
    ``'\t'`` (indentation with one tab).
418
 
 
419
 
    If this option is not specified, and the ConfigObj is initialised with a
420
 
    dictionary, the indentation used in the output is the default one, that is,
421
 
    four spaces.
422
 
 
423
 
    If this option is not specified, and the ConfigObj is initialised with a
424
 
    list of lines or a file, the indentation used in the first indented line is
425
 
    selected and used in all output lines. If no input line is indented, no
426
 
    output line will be either.
427
 
 
428
 
    If this option *is* specified, the option value is used in the output
429
 
    config, overriding the type of indentation in the input config (if any).
430
 
 
431
 
* 'encoding': ``None``
432
 
 
433
 
    By default **ConfigObj** does not decode the file/strings you pass it into
434
 
    Unicode [#]_. If you want your config file as Unicode (keys and members)
435
 
    you need to provide an encoding to decode the file with. This encoding will
436
 
    also be used to encode the config file when writing.
437
 
    
438
 
    You can change the encoding attribute at any time.
439
 
    
440
 
    Any characters in your strings that can't be encoded with the specified
441
 
    encoding will raise a ``UnicodeEncodeError``.
442
 
    
443
 
    .. note::
444
 
    
445
 
        ``UTF16`` encoded files will automatically be detected and decoded,
446
 
        even if ``encoding`` is ``None``.
447
 
        
448
 
        This is because it is a 16-bit encoding, and ConfigObj will mangle it
449
 
        (split characters on byte boundaries) if it parses it without decoding.
450
 
 
451
 
* 'default_encoding': ``None``
452
 
 
453
 
    When using the ``write`` method, **ConfigObj** uses the ``encoding``
454
 
    attribute to encode the Unicode strings. If any members (or keys) have
455
 
    been set as byte strings instead of Unicode, these must first be decoded
456
 
    to Unicode before outputting in the specified encoding.
457
 
 
458
 
    ``default_encoding``, if specified, is the encoding used to decode byte
459
 
    strings in the **ConfigObj** before writing. If this is ``None``, then
460
 
    the Python default encoding (``sys.defaultencoding`` - usually ASCII) is
461
 
    used.
462
 
    
463
 
    For most Western European users, a value of ``latin-1`` is sensible.
464
 
    
465
 
    ``default_encoding`` is *only* used if an ``encoding`` is specified.
466
 
    
467
 
    Any characters in byte-strings that can't be decoded using the
468
 
    ``default_encoding`` will raise a ``UnicodeDecodeError``.
469
 
 
470
 
* 'unrepr': ``False``
471
 
 
472
 
    The ``unrepr`` option reads and writes files in a different mode. This
473
 
    allows you to store and retrieve the basic Python data-types using config
474
 
    files.
475
 
    
476
 
    This uses Python syntax for lists and quoting. See `unrepr mode`_ for the
477
 
    full details.
478
 
 
479
 
* 'write_empty_values': ``False`` 
480
 
 
481
 
    If ``write_empty_values`` is ``True``, empty strings are written as
482
 
    empty values. See `Empty Values`_ for more details.
483
 
 
484
 
* '_inspec': ``False``
485
 
 
486
 
    Used internally by ConfigObj when parsing configspec files. If you are
487
 
    creating a ConfigObj instance from a configspec file you must pass True
488
 
    for this argument as well as ``list_values=False``.
489
 
 
490
 
 
491
 
Methods
492
 
-------
493
 
 
494
 
The ConfigObj is a subclass of an object called ``Section``, which is itself a
495
 
subclass of ``dict``, the builtin dictionary type. This means it also has
496
 
**all** the normal dictionary methods.
497
 
 
498
 
In addition, the following `Section Methods`_ may be useful :
499
 
 
500
 
* 'restore_default'
501
 
* 'restore_defaults'
502
 
* 'walk'
503
 
* 'merge'
504
 
* 'dict'
505
 
* 'as_bool'
506
 
* 'as_float'
507
 
* 'as_int'
508
 
* 'as_list'
509
 
 
510
 
Read about Sections_ for details of all the methods.
511
 
 
512
 
.. hint::
513
 
 
514
 
    The *merge* method of sections is a recursive update.
515
 
    
516
 
    You can use this to merge sections, or even whole ConfigObjs, into each
517
 
    other.
518
 
    
519
 
    You would typically use this to create a default ConfigObj and then merge
520
 
    in user settings. This way users only need to specify values that are
521
 
    different from the default. You can use configspecs and validation to
522
 
    achieve the same thing of course.
523
 
    
524
 
 
525
 
The public methods available on ConfigObj are :
526
 
 
527
 
* 'write'
528
 
* 'validate'
529
 
* 'reset'
530
 
* 'reload'
531
 
 
532
 
 
533
 
write
534
 
~~~~~
535
 
 
536
 
.. code-block:: python
537
 
 
538
 
    write(file_object=None)
539
 
 
540
 
This method writes the current ConfigObj and takes a single, optional argument
541
 
[#]_.
542
 
 
543
 
If you pass in a file like object to the ``write`` method, the config file will
544
 
be written to this. (The only method of this object that is used is its
545
 
``write`` method, so a ``StringIO`` instance, or any other file like object
546
 
will work.)
547
 
 
548
 
Otherwise, the behaviour of this method depends on the ``filename`` attribute
549
 
of the ConfigObj.
550
 
 
551
 
``filename``
552
 
    ConfigObj will write the configuration to the file specified.
553
 
 
554
 
``None``
555
 
    ``write`` returns a list of lines. (Not ``'\n'`` terminated)
556
 
 
557
 
First the 'initial_comment' is written, then the config file, followed by the
558
 
'final_comment'. Comment lines and inline comments are written with each
559
 
key/value.
560
 
 
561
 
 
562
 
validate
563
 
~~~~~~~~
564
 
 
565
 
 
566
 
.. code-block:: python
567
 
 
568
 
    validate(validator, preserve_errors=False, copy=False)
569
 
 
570
 
.. code-block:: python
571
 
 
572
 
    # filename is the config file
573
 
    # filename2 is the configspec
574
 
    # (which could also be hardcoded into your program)
575
 
    config = ConfigObj(filename, configspec=filename2)
576
 
    #
577
 
    from validate import Validator
578
 
    val = Validator()
579
 
    test = config.validate(val)
580
 
    if test == True:
581
 
        print 'Succeeded.'
582
 
 
583
 
The validate method uses the `validate 
584
 
<http://www.voidspace.org.uk/python/validate.html>`__ module to do the
585
 
validation.
586
 
    
587
 
This method validates the ConfigObj against the configspec. By doing type
588
 
conversion as well it can abstract away the config file altogether and present
589
 
the config *data* to your application (in the types it expects it to be).
590
 
 
591
 
If the ``configspec`` attribute of the ConfigObj is ``None``, it raises a
592
 
``ValueError``.
593
 
 
594
 
If the stringify_ attribute is set, this process will convert values to the
595
 
type defined in the configspec.
596
 
 
597
 
The validate method uses checks specified in the configspec and defined in the
598
 
``Validator`` object. It is very easy to extend.
599
 
 
600
 
The configspec looks like the config file, but instead of the value, you
601
 
specify the check (and any default value). See the validation_ section for
602
 
details.
603
 
 
604
 
.. hint::
605
 
 
606
 
    The system of configspecs can seem confusing at first, but is actually
607
 
    quite simple and powerful. The best guide to them is this article on
608
 
    ConfigObj:
609
 
    
610
 
    * `An Introduction to ConfigObj`_
611
 
 
612
 
The ``copy`` parameter fills in missing values from the configspec (default
613
 
values), *without* marking the values as defaults. It also causes comments to
614
 
be copied from the configspec into the config file. This allows you to use a
615
 
configspec to create default config files. (Normally default values aren't
616
 
written out by the ``write`` method.)
617
 
 
618
 
As of ConfigObj 4.3.0 you can also pass in a ConfigObj instance as your
619
 
configspec. This is especially useful if you need to specify the encoding of
620
 
your configspec file. When you read your configspec file, you *must* specify
621
 
``list_values=False``. If you need to support hashes inside the configspec
622
 
values then you must also pass in ``_inspec=True``. This is because configspec
623
 
files actually use a different syntax to config files and inline comment support
624
 
must be switched off to correctly read configspec files with hashes in the values.
625
 
 
626
 
 
627
 
.. code-block:: python
628
 
 
629
 
    from configobj import ConfigObj
630
 
    configspec = ConfigObj(configspecfilename, encoding='UTF8',
631
 
                           list_values=False, _inspec=True)
632
 
    config = ConfigObj(filename, configspec=configspec)
633
 
 
634
 
 
635
 
Return Value
636
 
############
637
 
 
638
 
By default, the validate method either returns ``True`` (everything passed) 
639
 
or a dictionary of ``True`` / ``False`` representing pass/fail. The dictionary 
640
 
follows the structure of the ConfigObj.
641
 
 
642
 
If a whole section passes then it is replaced with the value ``True``. If a 
643
 
whole section fails, then it is replaced with the value ``False``.
644
 
 
645
 
If a value is missing, and there is no default in the check, then the check 
646
 
automatically fails.
647
 
 
648
 
The ``validate`` method takes an optional keyword argument ``preserve_errors``.
649
 
If you set this to ``True``, instead of getting ``False`` for failed checks you
650
 
get the actual error object from the **validate** module. This usually contains
651
 
useful information about why the check failed.
652
 
 
653
 
See the `flatten_errors`_ function for how to turn your results dictionary into
654
 
a useful list of error messages.
655
 
 
656
 
Even if ``preserve_errors`` is ``True``, missing keys or sections will still be
657
 
represented by a ``False`` in the results dictionary.
658
 
 
659
 
 
660
 
Mentioning Default Values
661
 
#########################
662
 
 
663
 
In the check in your configspec, you can specify a default to be used - by 
664
 
using the ``default`` keyword. E.g. ::
665
 
 
666
 
    key1 = integer(0, 30, default=15)
667
 
    key2 = integer(default=15)
668
 
    key3 = boolean(default=True)
669
 
    key4 = option('Hello', 'Goodbye', 'Not Today', default='Not Today')
670
 
 
671
 
If the configspec check supplies a default and the value is missing in the
672
 
config, then the default will be set in your ConfigObj. (It is still passed to
673
 
the ``Validator`` so that type conversion can be done: this means the default
674
 
value must still pass the check.)
675
 
 
676
 
ConfigObj keeps a record of which values come from defaults, using the
677
 
``defaults`` attribute of sections_. Any key in this list isn't written out by
678
 
the ``write`` method. If a key is set from outside (even to the same value)
679
 
then it is removed from the ``defaults`` list.
680
 
 
681
 
.. note:
682
 
 
683
 
    Even if all the keys in a section are in the defaults list, the section
684
 
    marker is still written out.
685
 
 
686
 
There is additionally a special case default value of ``None``. If you set the
687
 
default value to ``None`` and the value is missing, the value will always be
688
 
set to ``None``. As the other checks don't return ``None`` (unless you
689
 
implement your own that do), you can tell that this value came from a default
690
 
value (and was missing from the config file). It allows an easy way of
691
 
implementing optional values. Simply check (and ignore) members that are set
692
 
to ``None``.
693
 
 
694
 
.. note::
695
 
 
696
 
    If stringify_ is ``False`` then ``default=None`` returns ``''`` instead of
697
 
    ``None``. This is because setting a value to a non-string raises an error
698
 
    if stringify is unset.
699
 
 
700
 
The default value can be a list. See `List Values`_ for the way to do this.
701
 
 
702
 
Writing invalid default values is a *guaranteed* way of confusing your users.
703
 
Default values **must** pass the check.
704
 
 
705
 
 
706
 
Mentioning Repeated Sections and Values
707
 
#######################################
708
 
 
709
 
In the configspec it is possible to cause *every* sub-section in a section to
710
 
be validated using the same configspec. You do this with a section in the
711
 
configspec  called ``__many__``. Every sub-section in that section has the
712
 
``__many__`` configspec applied to it (without you having to explicitly name
713
 
them in advance).
714
 
 
715
 
Your ``__many__`` section can have nested subsections, which can also include
716
 
``__many__`` type sections.
717
 
 
718
 
You can also specify that all values should be validated using the same configspec,
719
 
by having a member with the name ``__many__``. If you want to use repeated values
720
 
along with repeated sections then you can call one of them ``___many___`` (triple
721
 
underscores).
722
 
 
723
 
Sections with repeated sections or values can also have specifically named sub-sections
724
 
or values. The ``__many__`` configspec will only be used to validate entries that don't 
725
 
have an explicit configspec.
726
 
 
727
 
See `Repeated Sections`_ for examples.
728
 
 
729
 
 
730
 
Mentioning SimpleVal
731
 
####################
732
 
 
733
 
If you just want to check if all members are present, then you can use the
734
 
``SimpleVal`` object that comes with ConfigObj. It only fails members if they
735
 
are missing.
736
 
 
737
 
Write a configspec that has all the members you want to check for, but set
738
 
every section to ``''``.
739
 
 
740
 
.. code-block:: python
741
 
 
742
 
    val = SimpleVal()
743
 
    test = config.validate(val)
744
 
    if test is True:
745
 
        print 'Succeeded.'
746
 
 
747
 
 
748
 
Mentioning copy Mode
749
 
####################
750
 
 
751
 
As discussed in `Mentioning Default Values`_, you can use a configspec to
752
 
supply default values. These are marked in the ConfigObj instance as defaults,
753
 
and *not* written out by the ``write`` mode. This means that your users only
754
 
need to supply values that are different from the defaults.
755
 
 
756
 
This can be inconvenient if you *do* want to write out the default values,
757
 
for example to write out a default config file.
758
 
 
759
 
If you set ``copy=True`` when you call validate, then no values are marked as
760
 
defaults. In addition, all comments from the configspec are copied into
761
 
your ConfigObj instance. You can then call ``write`` to create your config
762
 
file.
763
 
    
764
 
There is a limitation with this. In order to allow `String Interpolation`_ to work
765
 
within configspecs, ``DEFAULT`` sections are not processed by
766
 
validation; even in copy mode.
767
 
 
768
 
 
769
 
reload
770
 
~~~~~~
771
 
 
772
 
If a ConfigObj instance was loaded from the filesystem, then this method will reload it. It
773
 
will also reuse any configspec you supplied at instantiation (including reloading it from
774
 
the filesystem if you passed it in as a filename).
775
 
 
776
 
If the ConfigObj does not have a filename attribute pointing to a file, then a ``ReloadError`` 
777
 
will be raised.
778
 
 
779
 
 
780
 
reset
781
 
~~~~~
782
 
 
783
 
This method takes no arguments and doesn't return anything. It restores a ConfigObj
784
 
instance to a freshly created state.
785
 
 
786
 
 
787
 
Attributes
788
 
----------
789
 
 
790
 
A ConfigObj has the following attributes :
791
 
 
792
 
* indent_type
793
 
* interpolation
794
 
* stringify
795
 
* BOM
796
 
* initial_comment
797
 
* final_comment
798
 
* list_values
799
 
* encoding
800
 
* default_encoding
801
 
* unrepr
802
 
* write_empty_values
803
 
* newlines
804
 
 
805
 
.. note::
806
 
 
807
 
    This doesn't include *comments*, *inline_comments*, *defaults*, or
808
 
    *configspec*. These are actually attributes of Sections_.
809
 
 
810
 
It also has the following attributes as a result of parsing. They correspond to
811
 
options when the ConfigObj was created, but changing them has no effect.
812
 
 
813
 
* raise_errors
814
 
* create_empty
815
 
* file_error
816
 
 
817
 
 
818
 
interpolation
819
 
~~~~~~~~~~~~~
820
 
 
821
 
ConfigObj can perform string interpolation in a *similar* way to
822
 
``ConfigParser``. See the `String Interpolation`_ section for full details.
823
 
 
824
 
If ``interpolation`` is set to ``False``, then interpolation is *not* done when
825
 
you fetch values.
826
 
 
827
 
 
828
 
stringify
829
 
~~~~~~~~~
830
 
 
831
 
If this attribute is set (``True``) then the validate_ method changes the
832
 
values in the ConfigObj. These are turned back into strings when write_ is
833
 
called.
834
 
 
835
 
If stringify is unset (``False``) then attempting to set a value to a non
836
 
string (or a list of strings) will raise a ``TypeError``.
837
 
 
838
 
 
839
 
BOM
840
 
~~~
841
 
 
842
 
If the initial config file *started* with the UTF8 Unicode signature (known
843
 
slightly incorrectly as the BOM - Byte Order Mark), or the UTF16 BOM, then
844
 
this attribute is set to ``True``. Otherwise it is ``False``.
845
 
 
846
 
If it is set to ``True`` when ``write`` is called then, if ``encoding`` is set
847
 
to ``None`` *or* to ``utf_8`` (and variants) a UTF BOM will be written.
848
 
 
849
 
For UTF16 encodings, a BOM is *always* written.
850
 
 
851
 
 
852
 
initial_comment
853
 
~~~~~~~~~~~~~~~
854
 
 
855
 
This is a list of lines. If the ConfigObj is created from an existing file, it
856
 
will contain any lines of comments before the start of the members.
857
 
 
858
 
If you create a new ConfigObj, this will be an empty list.
859
 
 
860
 
The write method puts these lines before it starts writing out the members.
861
 
 
862
 
 
863
 
final_comment
864
 
~~~~~~~~~~~~~
865
 
 
866
 
This is a list of lines. If the ConfigObj is created from an existing file, it
867
 
will contain any lines of comments after the last member.
868
 
 
869
 
If you create a new ConfigObj, this will be an empty list.
870
 
 
871
 
The ``write`` method puts these lines after it finishes writing out the
872
 
members.
873
 
 
874
 
 
875
 
list_values
876
 
~~~~~~~~~~~
877
 
 
878
 
This attribute is ``True`` or ``False``. If set to ``False`` then values are
879
 
not parsed for list values. In addition single line values are not unquoted.
880
 
 
881
 
This allows you to do your own parsing of values. It exists primarily to
882
 
support the reading of the configspec_ - but has other use cases.
883
 
 
884
 
For example you could use the ``LineParser`` from the
885
 
`listquote module <http://www.voidspace.org.uk/python/listquote.html#lineparser>`_ 
886
 
to read values for nested lists.
887
 
 
888
 
Single line values aren't quoted when writing - but multiline values are
889
 
handled as normal.
890
 
 
891
 
.. caution::
892
 
 
893
 
    Because values aren't quoted, leading or trailing whitespace can be lost. This behaviour was changed in version 4.0.1. Prior to this, single line values might have been quoted; even with ``list_values=False``. This means that files written by earlier versions of ConfigObj *could* now be incompatible and need the quotes removing by hand.
894
 
 
895
 
 
896
 
encoding
897
 
~~~~~~~~
898
 
 
899
 
This is the encoding used to encode the output, when you call ``write``. It
900
 
must be a valid encoding `recognised by Python <http://docs.python.org/lib/standard-encodings.html>`_.
901
 
 
902
 
If this value is ``None`` then no encoding is done when ``write`` is called.
903
 
 
904
 
 
905
 
default_encoding
906
 
~~~~~~~~~~~~~~~~
907
 
 
908
 
If encoding is set, any byte-strings in your ConfigObj instance (keys or
909
 
members) will first be decoded to Unicode using the encoding specified by the
910
 
``default_encoding`` attribute. This ensures that the output is in the encoding
911
 
specified.
912
 
 
913
 
If this value is ``None`` then ``sys.defaultencoding`` is used instead.
914
 
 
915
 
 
916
 
unrepr
917
 
~~~~~~
918
 
 
919
 
Another boolean value. If this is set, then ``repr(value)`` is used to write
920
 
values. This writes values in a slightly different way to the normal ConfigObj
921
 
file syntax.
922
 
 
923
 
This preserves basic Python data-types when read back in. See `unrepr mode`_
924
 
for more details.
925
 
 
926
 
 
927
 
write_empty_values
928
 
~~~~~~~~~~~~~~~~~~
929
 
 
930
 
Also boolean. If set, values that are an empty string (``''``) are written as
931
 
empty values. See `Empty Values`_ for more details.
932
 
 
933
 
 
934
 
newlines
935
 
~~~~~~~~
936
 
 
937
 
When a config file is read, ConfigObj records the type of newline separators in the
938
 
file and uses this separator when writing. It defaults to ``None``, and ConfigObj
939
 
uses the system default (``os.sep``) if write is called without newlines having
940
 
been set.
941
 
 
942
 
 
943
 
The Config File Format
944
 
======================
945
 
 
946
 
You saw an example config file in the `Config Files`_ section. Here is a fuller
947
 
specification of the config files used and created by ConfigObj.
948
 
 
949
 
The basic pattern for keywords is::
950
 
 
951
 
    # comment line
952
 
    # comment line
953
 
    keyword = value # inline comment
954
 
 
955
 
Both keyword and value can optionally be surrounded in quotes. The equals sign
956
 
is the only valid divider.
957
 
 
958
 
Values can have comments on the lines above them, and an inline comment after
959
 
them. This, of course, is optional. See the comments_ section for details.
960
 
 
961
 
If a keyword or value starts or ends with whitespace, or contains a quote mark
962
 
or comma, then it should be surrounded by quotes. Quotes are not necessary if
963
 
whitespace is surrounded by non-whitespace.
964
 
 
965
 
Values can also be lists. Lists are comma separated. You indicate a single
966
 
member list by a trailing comma. An empty list is shown by a single comma::
967
 
 
968
 
    keyword1 = value1, value2, value3
969
 
    keyword2 = value1, # a single member list
970
 
    keyword3 = , # an empty list
971
 
 
972
 
Values that contain line breaks (multi-line values) can be surrounded by triple
973
 
quotes. These can also be used if a value contains both types of quotes. List
974
 
members cannot be surrounded by triple quotes::
975
 
 
976
 
    keyword1 = ''' A multi line value
977
 
    on several
978
 
    lines'''     # with a comment
979
 
    keyword2 = '''I won't be "afraid".'''
980
 
    #
981
 
    keyword3 = """ A multi line value
982
 
    on several
983
 
    lines"""     # with a comment
984
 
    keyword4 = """I won't be "afraid"."""
985
 
 
986
 
.. warning::
987
 
 
988
 
    There is no way of safely quoting values that contain both types of triple
989
 
    quotes.
990
 
 
991
 
A line that starts with a '#', possibly preceded by whitespace, is a comment.
992
 
 
993
 
New sections are indicated by a section marker line. That is the section name
994
 
in square brackets. Whitespace around the section name is ignored. The name can
995
 
be quoted with single or double quotes. The marker can have comments before it
996
 
and an inline comment after it::
997
 
 
998
 
    # The First Section
999
 
    [ section name 1 ] # first section
1000
 
    keyword1 = value1
1001
 
 
1002
 
    # The Second Section
1003
 
    [ "section name 2" ] # second section
1004
 
    keyword2 = value2
1005
 
 
1006
 
Any subsections (sections that are *inside* the current section) are
1007
 
designated by repeating the square brackets before and after the section name.
1008
 
The number of square brackets represents the nesting level of the sub-section.
1009
 
Square brackets may be separated by whitespace; such whitespace, however, will
1010
 
not be present in the output config written by the ``write`` method.
1011
 
 
1012
 
Indentation is not significant, but can be preserved. See the description of
1013
 
the ``indent_type`` option, in the `ConfigObj specifications`_ chapter, for the
1014
 
details.
1015
 
 
1016
 
A *NestingError* will be raised if the number of the opening and the closing
1017
 
brackets in a section marker is not the same, or if a sub-section's nesting
1018
 
level is greater than the nesting level of it parent plus one.
1019
 
 
1020
 
In the outer section, single values can only appear before any sub-section.
1021
 
Otherwise they will belong to the sub-section immediately before them::
1022
 
 
1023
 
    # initial comment
1024
 
    keyword1 = value1
1025
 
    keyword2 = value2
1026
 
 
1027
 
    [section 1]
1028
 
    keyword1 = value1
1029
 
    keyword2 = value2
1030
 
 
1031
 
        [[sub-section]]
1032
 
        # this is in section 1
1033
 
        keyword1 = value1
1034
 
        keyword2 = value2
1035
 
 
1036
 
            [[[nested section]]]
1037
 
            # this is in sub section
1038
 
            keyword1 = value1
1039
 
            keyword2 = value2
1040
 
 
1041
 
        [[sub-section2]]
1042
 
        # this is in section 1 again
1043
 
        keyword1 = value1
1044
 
        keyword2 = value2
1045
 
 
1046
 
    [[sub-section3]]
1047
 
    # this is also in section 1, indentation is misleading here
1048
 
    keyword1 = value1
1049
 
    keyword2 = value2
1050
 
 
1051
 
    # final comment
1052
 
 
1053
 
When parsed, the above config file produces the following data structure:
1054
 
 
1055
 
 
1056
 
.. code-block:: python
1057
 
 
1058
 
    ConfigObj({
1059
 
        'keyword1': 'value1',
1060
 
        'keyword2': 'value2',
1061
 
        'section 1': {
1062
 
            'keyword1': 'value1',
1063
 
            'keyword2': 'value2',
1064
 
            'sub-section': {
1065
 
                'keyword1': 'value1',
1066
 
                'keyword2': 'value2',
1067
 
                'nested section': {
1068
 
                    'keyword1': 'value1',
1069
 
                    'keyword2': 'value2',
1070
 
                },
1071
 
            },
1072
 
            'sub-section2': {
1073
 
                'keyword1': 'value1',
1074
 
                'keyword2': 'value2',
1075
 
            },
1076
 
            'sub-section3': {
1077
 
                'keyword1': 'value1',
1078
 
                'keyword2': 'value2',
1079
 
            },
1080
 
        },
1081
 
    })
1082
 
 
1083
 
    
1084
 
Sections are ordered: note how the structure of the resulting ConfigObj is in
1085
 
the same order as the original file.
1086
 
 
1087
 
.. note::
1088
 
 
1089
 
    In ConfigObj 4.3.0 *empty values* became valid syntax. They are read as the
1090
 
    empty string. There is also an option/attribute (``write_empty_values``) to
1091
 
    allow the writing of these.
1092
 
    
1093
 
    This is mainly to support 'legacy' config files, written from other
1094
 
    applications. This is documented under `Empty Values`_.
1095
 
    
1096
 
    `unrepr mode`_ introduces *another* syntax variation, used for storing
1097
 
    basic Python datatypes in config files.
1098
 
 
1099
 
 
1100
 
Sections
1101
 
========
1102
 
 
1103
 
Every section in a ConfigObj has certain properties. The ConfigObj itself also
1104
 
has these properties, because it too is a section (sometimes called the *root
1105
 
section*).
1106
 
 
1107
 
``Section`` is a subclass of the standard new-class dictionary, therefore it
1108
 
has **all** the methods of a normal dictionary. This means you can ``update``
1109
 
and ``clear`` sections.
1110
 
 
1111
 
.. note::
1112
 
 
1113
 
    You create a new section by assigning a member to be a dictionary.
1114
 
    
1115
 
    The new ``Section`` is created *from* the dictionary, but isn't the same
1116
 
    thing as the dictionary. (So references to the dictionary you use to create
1117
 
    the section *aren't* references to the new section).
1118
 
    
1119
 
    Note the following.
1120
 
 
1121
 
    .. code-block:: python
1122
 
 
1123
 
        config = ConfigObj()
1124
 
        vals = {'key1': 'value 1', 
1125
 
                'key2': 'value 2'
1126
 
               }
1127
 
        config['vals'] = vals
1128
 
        config['vals'] == vals
1129
 
        True
1130
 
        config['vals'] is vals
1131
 
        False
1132
 
     
1133
 
    If you now change ``vals``, the changes won't be reflected in ``config['vals']``.
1134
 
 
1135
 
A section is ordered, following its ``scalars`` and ``sections``
1136
 
attributes documented below. This means that the following dictionary
1137
 
attributes return their results in order.
1138
 
 
1139
 
* '__iter__'
1140
 
 
1141
 
    More commonly known as ``for member in section:``.
1142
 
 
1143
 
* '__repr__' and '__str__'
1144
 
 
1145
 
    Any time you print or display the ConfigObj.
1146
 
 
1147
 
* 'items'
1148
 
 
1149
 
* 'iteritems'
1150
 
 
1151
 
* 'iterkeys'
1152
 
 
1153
 
* 'itervalues'
1154
 
 
1155
 
* 'keys'
1156
 
 
1157
 
* 'popitem'
1158
 
 
1159
 
* 'values'
1160
 
 
1161
 
 
1162
 
Section Attributes
1163
 
------------------
1164
 
 
1165
 
* main
1166
 
 
1167
 
    A reference to the main ConfigObj.
1168
 
 
1169
 
* parent
1170
 
 
1171
 
    A reference to the 'parent' section, the section that this section is a
1172
 
    member of.
1173
 
 
1174
 
    On the ConfigObj this attribute is a reference to itself. You can use this
1175
 
    to walk up the sections, stopping when ``section.parent is section``.
1176
 
 
1177
 
* depth
1178
 
 
1179
 
    The nesting level of the current section.
1180
 
 
1181
 
    If you create a new ConfigObj and add sections, 1 will be added to the
1182
 
    depth level between sections.
1183
 
 
1184
 
* defaults
1185
 
 
1186
 
    This attribute is a list of scalars that came from default values. Values
1187
 
    that came from defaults aren't written out by the ``write`` method.
1188
 
    Setting any of these values in the section removes them from the defaults
1189
 
    list.
1190
 
 
1191
 
* default_values
1192
 
 
1193
 
    This attribute is a dictionary mapping keys to the default values for the
1194
 
    keys. By default it is an empty dictionary and is populated when you
1195
 
    validate the ConfigObj.
1196
 
 
1197
 
* scalars, sections
1198
 
 
1199
 
    These attributes are normal lists, representing the order that members,
1200
 
    single values and subsections appear in the section. The order will either
1201
 
    be the order of the original config file, *or* the order that you added
1202
 
    members.
1203
 
 
1204
 
    The order of members in this lists is the order that ``write`` creates in
1205
 
    the config file. The ``scalars`` list is output before the ``sections``
1206
 
    list.
1207
 
 
1208
 
    Adding or removing members also alters these lists. You can manipulate the
1209
 
    lists directly to alter the order of members.
1210
 
 
1211
 
    .. warning::
1212
 
 
1213
 
        If you alter the ``scalars``, ``sections``, or ``defaults`` attributes
1214
 
        so that they no longer reflect the contents of the section, you will
1215
 
        break your ConfigObj.
1216
 
 
1217
 
    See also the ``rename`` method.
1218
 
 
1219
 
* comments
1220
 
 
1221
 
    This is a dictionary of comments associated with each member. Each entry is
1222
 
    a list of lines. These lines are written out before the member.
1223
 
 
1224
 
* inline_comments
1225
 
 
1226
 
    This is *another* dictionary of comments associated with each member. Each
1227
 
    entry is a string that is put inline with the member.
1228
 
 
1229
 
* configspec
1230
 
 
1231
 
    The configspec attribute is a dictionary mapping scalars to *checks*. A
1232
 
    check defines the expected type and possibly the allowed values for a
1233
 
    member.
1234
 
 
1235
 
    The configspec has the same format as a config file, but instead of values
1236
 
    it has a specification for the value (which may include a default value).
1237
 
    The validate_ method uses it to check the config file makes sense. If a
1238
 
    configspec is passed in when the ConfigObj is created, then it is parsed
1239
 
    and broken up to become the ``configspec`` attribute of each section.
1240
 
 
1241
 
    If you didn't pass in a configspec, this attribute will be ``None`` on the
1242
 
    root section (the main ConfigObj).
1243
 
 
1244
 
    You can set the configspec attribute directly on a section.
1245
 
 
1246
 
    See the validation_ section for full details of how to write configspecs.
1247
 
 
1248
 
* extra_values
1249
 
 
1250
 
    By default an empty list. After validation_ this is populated with any members
1251
 
    of the section that don't appear in the configspec (i.e. they are additional
1252
 
    values). Rather than accessing this directly it may be more convenient to get
1253
 
    all the extra values in a config file using the get_extra_values_ function.
1254
 
    
1255
 
    New in ConfigObj 4.7.0.
1256
 
    
1257
 
 
1258
 
Section Methods
1259
 
---------------
1260
 
 
1261
 
* **dict**
1262
 
 
1263
 
    This method takes no arguments. It returns a deep copy of the section as a
1264
 
    dictionary. All subsections will also be dictionaries, and list values will
1265
 
    be copies, rather than references to the original [#]_.
1266
 
 
1267
 
* **rename**
1268
 
 
1269
 
    ``rename(oldkey, newkey)``
1270
 
 
1271
 
    This method renames a key, without affecting its position in the sequence.
1272
 
 
1273
 
* **merge**
1274
 
 
1275
 
    ``merge(indict)``
1276
 
    
1277
 
    This method is a *recursive update* method. It allows you to merge two
1278
 
    config files together.
1279
 
    
1280
 
    You would typically use this to create a default ConfigObj and then merge
1281
 
    in user settings. This way users only need to specify values that are
1282
 
    different from the default.
1283
 
    
1284
 
    For example :
1285
 
    
1286
 
    .. code-block:: python
1287
 
 
1288
 
        # def_cfg contains your default config settings
1289
 
        # user_cfg contains the user settings
1290
 
        cfg = ConfigObj(def_cfg)
1291
 
        usr = ConfigObj(user_cfg)
1292
 
        #
1293
 
        cfg.merge(usr)
1294
 
        
1295
 
        """
1296
 
        cfg now contains a combination of the default settings and the user
1297
 
        settings.
1298
 
        
1299
 
        The user settings will have overwritten any of the default ones.
1300
 
        """
1301
 
    
1302
 
* **walk**
1303
 
 
1304
 
    This method can be used to transform values and names. See `walking a
1305
 
    section`_ for examples and explanation.
1306
 
 
1307
 
* **as_bool**
1308
 
 
1309
 
    ``as_bool(key)``
1310
 
    
1311
 
    Returns ``True`` if the key contains a string that represents ``True``, or
1312
 
    is the ``True`` object.
1313
 
    
1314
 
    Returns ``False`` if the key contains a string that represents ``False``, 
1315
 
    or is the ``False`` object. 
1316
 
 
1317
 
    Raises a ``ValueError`` if the key contains anything else.
1318
 
    
1319
 
    Strings that represent ``True`` are (not case sensitive)::
1320
 
    
1321
 
        true, yes, on, 1
1322
 
        
1323
 
    Strings that represent ``False`` are::
1324
 
    
1325
 
        false, no, off, 0
1326
 
    
1327
 
        
1328
 
* **as_int**
1329
 
 
1330
 
    ``as_int(key)``
1331
 
    
1332
 
    This returns the value contained in the specified key as an integer.
1333
 
    
1334
 
    It raises a ``ValueError`` if the conversion can't be done.
1335
 
 
1336
 
    
1337
 
* **as_float**
1338
 
 
1339
 
    ``as_float(key)``
1340
 
    
1341
 
    This returns the value contained in the specified key as a float.
1342
 
    
1343
 
    It raises a ``ValueError`` if the conversion can't be done.
1344
 
    
1345
 
    
1346
 
* **as_list**
1347
 
 
1348
 
    ``as_list(key)``
1349
 
    
1350
 
    This returns the value contained in the specified key as a list.
1351
 
    
1352
 
    If it isn't a list it will be wrapped as a list so that you can 
1353
 
    guarantee the returned value will be a list.
1354
 
    
1355
 
 
1356
 
* **restore_default**
1357
 
 
1358
 
    ``restore_default(key)``
1359
 
    
1360
 
    Restore (and return) the default value for the specified key.
1361
 
    
1362
 
    This method will only work for a ConfigObj that was created
1363
 
    with a configspec and has been validated.
1364
 
    
1365
 
    If there is no default value for this key, ``KeyError`` is raised.
1366
 
 
1367
 
* **restore_defaults**
1368
 
    
1369
 
    ``restore_defaults()``
1370
 
 
1371
 
    Recursively restore default values to all members
1372
 
    that have them.
1373
 
    
1374
 
    This method will only work for a ConfigObj that was created
1375
 
    with a configspec and has been validated.
1376
 
    
1377
 
    It doesn't delete or modify entries without default values.
1378
 
 
1379
 
 
1380
 
Walking a Section
1381
 
-----------------
1382
 
 
1383
 
.. note::
1384
 
 
1385
 
    The walk method allows you to call a function on every member/name.
1386
 
 
1387
 
.. code-block:: python
1388
 
 
1389
 
    walk(function, raise_errors=True,
1390
 
         call_on_sections=False, **keywargs)
1391
 
 
1392
 
 
1393
 
``walk`` is a method of the ``Section`` object. This means it is also a method
1394
 
of ConfigObj.
1395
 
 
1396
 
It walks through every member and calls a function on the keyword and value. It
1397
 
walks recursively through subsections.
1398
 
 
1399
 
It returns a dictionary of all the computed values.
1400
 
 
1401
 
If the function raises an exception, the default is to propagate the error, and
1402
 
stop. If ``raise_errors=False`` then it sets the return value for that keyword
1403
 
to ``False`` instead, and continues. This is similar to the way validation_
1404
 
works.
1405
 
 
1406
 
Your function receives the arguments ``(section, key)``. The current value is
1407
 
then ``section[key]`` [#]_. Any unrecognised keyword arguments you pass to
1408
 
walk, are passed on to the function.
1409
 
 
1410
 
Normally ``walk`` just recurses into subsections. If you are transforming (or
1411
 
checking) names as well as values, then you want to be able to change the names
1412
 
of sections. In this case set ``call_on_sections`` to ``True``. Now, on
1413
 
encountering a sub-section, *first* the function is called for the *whole*
1414
 
sub-section, and *then* it recurses into it's members. This means your function
1415
 
must be able to handle receiving dictionaries as well as strings and lists.
1416
 
 
1417
 
If you are using the return value from ``walk`` *and* ``call_on_sections``,
1418
 
note that walk discards the return value when it calls your function.
1419
 
 
1420
 
.. caution::
1421
 
 
1422
 
    You can use ``walk`` to transform the names of members of a section
1423
 
    but you mustn't add or delete members.
1424
 
 
1425
 
 
1426
 
Examples
1427
 
--------
1428
 
 
1429
 
You can use this for transforming all values in your ConfigObj. For example
1430
 
you might like the nested lists from ConfigObj 3. This was provided by the
1431
 
listquote_ module. You could switch off the parsing for list values
1432
 
(``list_values=False``) and use listquote to parse every value.
1433
 
 
1434
 
Another thing you might want to do is use the Python escape codes in your
1435
 
values. You might be *used* to using ``\n`` for line feed and ``\t`` for tab.
1436
 
Obviously we'd need to decode strings that come from the config file (using the
1437
 
escape codes). Before writing out we'll need to put the escape codes back in
1438
 
encode.
1439
 
 
1440
 
As an example we'll write a function to use with walk, that encodes or decodes
1441
 
values using the ``string-escape`` codec.
1442
 
 
1443
 
The function has to take each value and set the new value. As a bonus we'll
1444
 
create one function that will do decode *or* encode depending on a keyword
1445
 
argument.
1446
 
 
1447
 
We don't want to work with section names, we're only transforming values, so
1448
 
we can leave ``call_on_sections`` as ``False``. This means the two datatypes we
1449
 
have to handle are strings and lists, we can ignore everything else. (We'll
1450
 
treat tuples as lists as well).
1451
 
 
1452
 
We're not using the return values, so it doesn't need to return anything, just
1453
 
change the values if appropriate.
1454
 
 
1455
 
 
1456
 
.. code-block:: python
1457
 
 
1458
 
    def string_escape(section, key, encode=False):
1459
 
        """
1460
 
        A function to encode or decode using the 'string-escape' codec.
1461
 
        To be passed to the walk method of a ConfigObj.
1462
 
        By default it decodes.
1463
 
        To encode, pass in the keyword argument ``encode=True``.
1464
 
        """
1465
 
        val = section[key]
1466
 
        # is it a type we can work with
1467
 
        # NOTE: for platforms where Python > 2.2
1468
 
        # you can use basestring instead of (str, unicode)
1469
 
        if not isinstance(val, (str, unicode, list, tuple)):
1470
 
            # no !
1471
 
            return
1472
 
        elif isinstance(val, (str, unicode)):
1473
 
            # it's a string !
1474
 
            if not encode:
1475
 
                section[key] = val.decode('string-escape')
1476
 
            else:
1477
 
                section[key] = val.encode('string-escape')
1478
 
        else:
1479
 
            # it must be a list or tuple!
1480
 
            # we'll be lazy and create a new list
1481
 
            newval = []
1482
 
            # we'll check every member of the list
1483
 
            for entry in val:
1484
 
                if isinstance(entry, (str, unicode)):
1485
 
                    if not encode:
1486
 
                        newval.append(entry.decode('string-escape'))
1487
 
                    else:
1488
 
                       newval.append(entry.encode('string-escape'))
1489
 
                else:
1490
 
                    newval.append(entry)
1491
 
            # done !
1492
 
            section[key] =  newval
1493
 
 
1494
 
    # assume we have a ConfigObj called ``config``
1495
 
    #
1496
 
    # To decode
1497
 
    config.walk(string_escape)
1498
 
    #
1499
 
    # To encode.
1500
 
    # Because ``walk`` doesn't recognise the ``encode`` argument
1501
 
    # it passes it to our function.
1502
 
    config.walk(string_escape, encode=True)
1503
 
 
1504
 
 
1505
 
Here's a simple example of using ``walk`` to transform names and values. One
1506
 
usecase of this would be to create a *standard* config file with placeholders
1507
 
for section and keynames. You can then use walk to create new config files
1508
 
and change values and member names :
1509
 
 
1510
 
.. code-block:: python
1511
 
 
1512
 
    # We use 'XXXX' as a placeholder
1513
 
    config = '''
1514
 
    XXXXkey1 = XXXXvalue1
1515
 
    XXXXkey2 = XXXXvalue2
1516
 
    XXXXkey3 = XXXXvalue3
1517
 
    [XXXXsection1]
1518
 
    XXXXkey1 = XXXXvalue1
1519
 
    XXXXkey2 = XXXXvalue2
1520
 
    XXXXkey3 = XXXXvalue3
1521
 
    [XXXXsection2]
1522
 
    XXXXkey1 = XXXXvalue1
1523
 
    XXXXkey2 = XXXXvalue2
1524
 
    XXXXkey3 = XXXXvalue3
1525
 
        [[XXXXsection1]]
1526
 
        XXXXkey1 = XXXXvalue1
1527
 
        XXXXkey2 = XXXXvalue2
1528
 
        XXXXkey3 = XXXXvalue3
1529
 
    '''.splitlines()
1530
 
    cfg = ConfigObj(config)
1531
 
    #
1532
 
    def transform(section, key):
1533
 
        val = section[key]
1534
 
        newkey = key.replace('XXXX', 'CLIENT1')
1535
 
        section.rename(key, newkey)
1536
 
        if isinstance(val, (tuple, list, dict)):
1537
 
            pass
1538
 
        else:
1539
 
            val = val.replace('XXXX', 'CLIENT1')
1540
 
            section[newkey] = val
1541
 
    #
1542
 
    cfg.walk(transform, call_on_sections=True)
1543
 
    print cfg
1544
 
    ConfigObj({'CLIENT1key1': 'CLIENT1value1', 'CLIENT1key2': 'CLIENT1value2', 
1545
 
    'CLIENT1key3': 'CLIENT1value3', 
1546
 
    'CLIENT1section1': {'CLIENT1key1': 'CLIENT1value1', 
1547
 
        'CLIENT1key2': 'CLIENT1value2', 'CLIENT1key3': 'CLIENT1value3'}, 
1548
 
    'CLIENT1section2': {'CLIENT1key1': 'CLIENT1value1', 
1549
 
        'CLIENT1key2': 'CLIENT1value2', 'CLIENT1key3': 'CLIENT1value3', 
1550
 
        'CLIENT1section1': {'CLIENT1key1': 'CLIENT1value1', 
1551
 
            'CLIENT1key2': 'CLIENT1value2', 'CLIENT1key3': 'CLIENT1value3'}}})
1552
 
 
1553
 
 
1554
 
Exceptions
1555
 
==========
1556
 
 
1557
 
There are several places where ConfigObj may raise exceptions (other than
1558
 
because of bugs).
1559
 
 
1560
 
1) If a configspec filename you pass in doesn't exist, or a config file
1561
 
    filename doesn't exist *and* ``file_error=True``, an ``IOError`` will be
1562
 
    raised.
1563
 
 
1564
 
2) If you try to set a non-string key, or a non string value when
1565
 
    ``stringify=False``, a ``TypeError`` will be raised.
1566
 
 
1567
 
3) A badly built config file will cause parsing errors.
1568
 
 
1569
 
4) A parsing error can also occur when reading a configspec.
1570
 
 
1571
 
5) In string interpolation you can specify a value that doesn't exist, or
1572
 
    create circular references (recursion).
1573
 
 
1574
 
Number 5 (which is actually two different types of exceptions) is documented
1575
 
in `String Interpolation`_.
1576
 
 
1577
 
*This* section is about errors raised during parsing.
1578
 
 
1579
 
The base error class is ``ConfigObjError``. This is a subclass of
1580
 
``SyntaxError``, so you can trap for ``SyntaxError`` without needing to
1581
 
directly import any of the ConfigObj exceptions.
1582
 
 
1583
 
The following other exceptions are defined (all deriving from
1584
 
``ConfigObjError``) :
1585
 
 
1586
 
* ``NestingError``
1587
 
 
1588
 
    This error indicates either a mismatch in the brackets in a section marker,
1589
 
    or an excessive level of nesting.
1590
 
 
1591
 
* ``ParseError``
1592
 
 
1593
 
    This error indicates that a line is badly written. It is neither a valid
1594
 
    ``key = value`` line, nor a valid section marker line, nor a comment line.
1595
 
 
1596
 
* ``DuplicateError``
1597
 
 
1598
 
    The keyword or section specified already exists.
1599
 
 
1600
 
* ``ConfigspecError``
1601
 
 
1602
 
    An error occurred whilst parsing a configspec.
1603
 
 
1604
 
* ``UnreprError``
1605
 
 
1606
 
    An error occurred when parsing a value in `unrepr mode`_.
1607
 
    
1608
 
* ``ReloadError``
1609
 
 
1610
 
    ``reload`` was called on a ConfigObj instance that doesn't have a valid 
1611
 
    filename attribute.
1612
 
 
1613
 
When parsing a configspec, ConfigObj will stop on the first error it
1614
 
encounters.  It will raise a ``ConfigspecError``. This will have an ``error``
1615
 
attribute, which is the actual error that was raised.
1616
 
 
1617
 
Behaviour when parsing a config file depends on the option ``raise_errors``.
1618
 
If ConfigObj encounters an error while parsing a config file:
1619
 
 
1620
 
    If ``raise_errors=True`` then ConfigObj will raise the appropriate error
1621
 
    and parsing will stop.
1622
 
 
1623
 
    If ``raise_errors=False`` (the default) then parsing will continue to the
1624
 
    end and *all* errors will be collected.
1625
 
 
1626
 
If ``raise_errors`` is False and multiple errors are found a ``ConfigObjError``
1627
 
is raised. The error raised has a ``config`` attribute, which is the parts of
1628
 
the ConfigObj that parsed successfully. It also has an attribute ``errors``,
1629
 
which is a list of *all* the errors raised. Each entry in the list is an
1630
 
instance of the appropriate error type. Each one has the following attributes
1631
 
(useful for delivering a sensible error message to your user) :
1632
 
 
1633
 
* ``line``: the original line that caused the error.
1634
 
 
1635
 
* ``line_number``: its number in the config file.
1636
 
 
1637
 
* ``message``: the error message that accompanied the error.
1638
 
 
1639
 
If only one error is found, then that error is re-raised. The error still has
1640
 
the ``config`` and ``errors`` attributes. This means that your error handling
1641
 
code can be the same whether one error is raised in parsing , or several.
1642
 
 
1643
 
It also means that in the most common case (a single error) a useful error
1644
 
message will be raised.
1645
 
 
1646
 
.. note::
1647
 
 
1648
 
    One wrongly written line could break the basic structure of your config
1649
 
    file. This could cause every line after it to flag an error, so having a
1650
 
    list of all the lines that caused errors may not be as useful as it sounds.
1651
 
 
1652
 
 
1653
 
Validation
1654
 
==========
1655
 
 
1656
 
.. hint::
1657
 
 
1658
 
    The system of configspecs can seem confusing at first, but is actually
1659
 
    quite simple and powerful. The best reference is my article on ConfigObj:
1660
 
    
1661
 
    * `An Introduction to ConfigObj`_
1662
 
    
1663
 
    
1664
 
Validation is done through a combination of the configspec_ and a ``Validator``
1665
 
object. For this you need *validate.py* [#]_. See downloading_ if you don't
1666
 
have a copy.
1667
 
 
1668
 
Validation can perform two different operations :
1669
 
 
1670
 
1) Check that a value meets a specification. For example, check that a value
1671
 
    is an integer between one and six, or is a choice from a specific set of
1672
 
    options.
1673
 
 
1674
 
2) It can convert the value into the type required. For example, if one of
1675
 
    your values is a port number, validation will turn it into an integer for
1676
 
    you.
1677
 
 
1678
 
So validation can act as a transparent layer between the datatypes of your
1679
 
application configuration (boolean, integers, floats, etc) and the text format
1680
 
of your config file.
1681
 
 
1682
 
 
1683
 
configspec
1684
 
----------
1685
 
 
1686
 
The ``validate`` method checks members against an entry in the configspec. Your
1687
 
configspec therefore resembles your config file, with a check for every member.
1688
 
 
1689
 
In order to perform validation you need a ``Validator`` object. This has
1690
 
several useful built-in check functions. You can also create your own custom
1691
 
functions and register them with your Validator object.
1692
 
 
1693
 
Each check is the name of one of these functions, including any parameters and
1694
 
keyword arguments. The configspecs look like function calls, and they map to
1695
 
function calls.
1696
 
 
1697
 
The basic datatypes that an un-extended Validator can test for are :
1698
 
 
1699
 
* boolean values (True and False)
1700
 
* integers (including minimum and maximum values)
1701
 
* floats (including min and max)
1702
 
* strings (including min and max length)
1703
 
* IP addresses (v4 only)
1704
 
 
1705
 
It can also handle lists of these types and restrict a value to being one from
1706
 
a set of options.
1707
 
 
1708
 
An example configspec is going to look something like::
1709
 
 
1710
 
    port = integer(0, 100)
1711
 
    user = string(max=25)
1712
 
    mode = option('quiet', 'loud', 'silent')
1713
 
 
1714
 
You can specify default values, and also have the same configspec applied to
1715
 
several sections. This is called `repeated sections`_.
1716
 
 
1717
 
For full details on writing configspecs, please refer to the `validate.py
1718
 
documentation`_.
1719
 
 
1720
 
.. important::
1721
 
 
1722
 
    Your configspec is read by ConfigObj in the same way as a config file.
1723
 
    
1724
 
    That means you can do interpolation *within* your configspec.
1725
 
    
1726
 
    In order to allow this, checks in the 'DEFAULT' section (of the root level
1727
 
    of your configspec) are *not* used.
1728
 
    
1729
 
    If you want to use a configspec *without* interpolation being done in it
1730
 
    you can create your configspec manually and switch off interpolation:
1731
 
    
1732
 
    .. code-block:: python
1733
 
    
1734
 
        from configobj import ConfigObj
1735
 
        
1736
 
        configspec = ConfigObj(spec_filename, interpolation=False, list_values=False,
1737
 
                               _inspec=True)
1738
 
        conf = ConfigObj(config_filename, configspec=configspec)
1739
 
 
1740
 
If you need to specify the encoding of your configspec, then you can pass in a
1741
 
ConfigObj instance as your configspec. When you read your configspec file, you
1742
 
*must* specify ``list_values=False``. If you need to support hashes in
1743
 
configspec values then you must also pass in ``_inspec=True``.
1744
 
 
1745
 
.. code-block:: python
1746
 
 
1747
 
    from configobj import ConfigObj
1748
 
    configspec = ConfigObj(configspecfilename, encoding='UTF8',
1749
 
                           list_values=False, _inspec=True)
1750
 
    config = ConfigObj(filename, configspec=configspec)
1751
 
 
1752
 
.. _validate.py documentation: http://www.voidspace.org.uk/python/validate.html
1753
 
 
1754
 
 
1755
 
Type Conversion
1756
 
---------------
1757
 
 
1758
 
By default, validation does type conversion. This means that if you specify
1759
 
``integer`` as the check, then calling validate_ will actually change the value
1760
 
to an integer (so long as the check succeeds).
1761
 
 
1762
 
It also means that when you call the write_ method, the value will be converted
1763
 
back into a string using the ``str`` function.
1764
 
 
1765
 
To switch this off, and leave values as strings after validation, you need to
1766
 
set the stringify_ attribute to ``False``. If this is the case, attempting to
1767
 
set a value to a non-string will raise an error.
1768
 
 
1769
 
 
1770
 
Default Values
1771
 
--------------
1772
 
 
1773
 
You can set a default value in your check. If the value is missing from the
1774
 
config file then this value will be used instead. This means that your user
1775
 
only has to supply values that differ from the defaults.
1776
 
 
1777
 
If you *don't* supply a default then for a value to be missing is an error,
1778
 
and this will show in the `return value`_ from validate.
1779
 
 
1780
 
Additionally you can set the default to be ``None``. This means the value will
1781
 
be set to ``None`` (the object) *whichever check is used*. (It will be set to
1782
 
``''`` rather than ``None`` if stringify_ is ``False``). You can use this
1783
 
to easily implement optional values in your config files. ::
1784
 
 
1785
 
    port = integer(0, 100, default=80)
1786
 
    user = string(max=25, default=0)
1787
 
    mode = option('quiet', 'loud', 'silent', default='loud')
1788
 
    nick = string(default=None)
1789
 
 
1790
 
.. note::
1791
 
 
1792
 
    Because the default goes through type conversion, it also has to pass the
1793
 
    check.
1794
 
 
1795
 
    Note that ``default=None`` is case sensitive.
1796
 
 
1797
 
 
1798
 
List Values
1799
 
~~~~~~~~~~~
1800
 
 
1801
 
It's possible that you will want to specify a list as a default value. To avoid
1802
 
confusing syntax with commas and quotes you use a list constructor to specify 
1803
 
that keyword arguments are lists. This includes the ``default`` value. This 
1804
 
makes checks look something like::
1805
 
 
1806
 
    checkname(default=list('val1', 'val2', 'val3'))
1807
 
 
1808
 
This works with all keyword arguments, but is most useful for default values.
1809
 
 
1810
 
 
1811
 
Repeated Sections
1812
 
-----------------
1813
 
 
1814
 
Repeated sections are a way of specifying a configspec for a section that
1815
 
should be applied to all unspecified subsections in the same section.
1816
 
 
1817
 
The easiest way of explaining this is to give an example. Suppose you have a
1818
 
config file that describes a dog. That dog has various attributes, but it can
1819
 
also have many fleas. You don't know in advance how many fleas there will be,
1820
 
or what they will be called, but you want each flea validated against the same
1821
 
configspec.
1822
 
 
1823
 
We can define a section called *fleas*. We want every flea in that section
1824
 
(every sub-section) to have the same configspec applied to it. We do this by
1825
 
defining a single section called ``__many__``. ::
1826
 
 
1827
 
    [dog]
1828
 
    name = string(default=Rover)
1829
 
    age = float(0, 99, default=0)
1830
 
 
1831
 
        [[fleas]]
1832
 
 
1833
 
            [[[__many__]]]
1834
 
            bloodsucker = boolean(default=True)
1835
 
            children = integer(default=10000)
1836
 
            size = option(small, tiny, micro, default=tiny)
1837
 
 
1838
 
Every flea on our dog will now be validated using the ``__many__`` configspec.
1839
 
 
1840
 
``__many__`` sections can have sub-sections, including their own ``__many__``
1841
 
sub-sections. Defaults work in the normal way in repeated sections.
1842
 
 
1843
 
 
1844
 
Repeated Values
1845
 
---------------
1846
 
 
1847
 
As well as using ``__many__`` to validate unspecified sections you can use it to validate values. For
1848
 
example, to specify that all values in a section should be integers::
1849
 
 
1850
 
    [section]
1851
 
        __many__ = integer
1852
 
        
1853
 
If you want to use repeated values alongside repeated sections you can call one ``__many__`` and the
1854
 
other ``___many___`` (with three underscores).
1855
 
 
1856
 
 
1857
 
Copy Mode
1858
 
---------
1859
 
 
1860
 
Because you can specify default values in your configspec, you can use
1861
 
ConfigObj to write out default config files for your application.
1862
 
 
1863
 
However, normally values supplied from a default in a configspec are *not*
1864
 
written out by the ``write`` method.
1865
 
 
1866
 
To do this, you need to specify ``copy=True`` when you call validate. As well
1867
 
as not marking values as default, all the comments in the configspec file
1868
 
will be copied into your ConfigObj instance.
1869
 
 
1870
 
 
1871
 
.. code-block:: python
1872
 
 
1873
 
    from configobj import ConfigObj
1874
 
    from validate import Validator
1875
 
    vdt = Validator()
1876
 
    config = ConfigObj(configspec='default.ini')
1877
 
    config.filename = 'new_default.ini'
1878
 
    config.validate(vdt, copy=True)
1879
 
    config.write()
1880
 
    
1881
 
If you need to support hashes in the configspec values then you must create
1882
 
it with ``_inspec=True``. This has the side effect of switching off the parsing
1883
 
of inline comments, meaning that they won't be copied into the new config file.
1884
 
(ConfigObj syntax is slightly different from configspec syntax and the parser
1885
 
can't support both inline comments and hashes in configspec values.)
1886
 
 
1887
 
 
1888
 
Validation and Interpolation
1889
 
----------------------------
1890
 
 
1891
 
String interpolation and validation don't play well together. When validation
1892
 
changes type it sets the value. If the value uses interpolation, then the 
1893
 
interpolation reference would normally be overwritten. Calling ``write`` would
1894
 
then use the absolute value and the interpolation reference would be lost.
1895
 
 
1896
 
As a compromise - if the value is unchanged by validation then it is not reset.
1897
 
This means strings that pass through validation unmodified will not be 
1898
 
overwritten. If validation changes type - the value has to be overwritten, and
1899
 
any interpolation references are lost.
1900
 
 
1901
 
 
1902
 
Extra Values
1903
 
------------
1904
 
 
1905
 
After validation the ``extra_values`` member of every section that is listed in
1906
 
the configspec will be populated with the names of members that are in the
1907
 
config file but not in the configspec.
1908
 
 
1909
 
If you are reporting configuration errors to your user this information can be
1910
 
useful, for example some missing entries may be due to misspelt entries that
1911
 
appear as extra values.
1912
 
 
1913
 
See the get_extra_values_ function
1914
 
 
1915
 
New in ConfigObj 4.7.0.
1916
 
 
1917
 
 
1918
 
 
1919
 
SimpleVal
1920
 
---------
1921
 
 
1922
 
You may not need a full validation process, but still want to check if all the
1923
 
expected values are present.
1924
 
 
1925
 
Provided as part of the ConfigObj module is the ``SimpleVal`` object. This has
1926
 
a dummy ``test`` method that always passes.
1927
 
 
1928
 
The only reason a test will fail is if the value is missing. The return value
1929
 
from ``validate`` will either be ``True``, meaning all present, or a dictionary
1930
 
with ``False`` for all missing values/sections.
1931
 
 
1932
 
To use it, you still need to pass in a valid configspec when you create the
1933
 
ConfigObj, but just set all the values to ``''``. Then create an instance of
1934
 
``SimpleVal`` and pass it to the ``validate`` method.
1935
 
 
1936
 
As a trivial example if you had the following config file::
1937
 
 
1938
 
    # config file for an application
1939
 
    port = 80
1940
 
    protocol = http
1941
 
    domain = voidspace
1942
 
    top_level_domain = org.uk
1943
 
 
1944
 
You would write the following configspec::
1945
 
 
1946
 
    port = ''
1947
 
    protocol = ''
1948
 
    domain = ''
1949
 
    top_level_domain = ''
1950
 
 
1951
 
 
1952
 
.. code-block:: python
1953
 
 
1954
 
    config = Configobj(filename, configspec=configspec)
1955
 
    val = SimpleVal()
1956
 
    test = config.validate(val)
1957
 
    if test == True:
1958
 
        print 'All values present.'
1959
 
    elif test == False:
1960
 
        print 'No values present!'
1961
 
    else:
1962
 
        for entry in test:
1963
 
            if test[entry] == False:
1964
 
                print '"%s" missing.' % entry
1965
 
 
1966
 
 
1967
 
Empty values
1968
 
============
1969
 
 
1970
 
Many config files from other applications allow empty values. As of version
1971
 
4.3.0, ConfigObj will read these as an empty string.
1972
 
 
1973
 
A new option/attribute has been added (``write_empty_values``) to allow
1974
 
ConfigObj to write empty strings as empty values.
1975
 
 
1976
 
.. code-block:: python
1977
 
 
1978
 
    from configobj import ConfigObj
1979
 
    cfg = '''
1980
 
        key =
1981
 
        key2 = # a comment
1982
 
    '''.splitlines()
1983
 
    config = ConfigObj(cfg)
1984
 
    print config
1985
 
    ConfigObj({'key': '', 'key2': ''})
1986
 
    
1987
 
    config.write_empty_values = True
1988
 
    for line in config.write():
1989
 
        print line
1990
 
    
1991
 
    key = 
1992
 
    key2 =     # a comment
1993
 
 
1994
 
 
1995
 
unrepr mode
1996
 
===========
1997
 
 
1998
 
The ``unrepr`` option allows you to store and retrieve the basic Python
1999
 
data-types using config files. It has to use a slightly different syntax to
2000
 
normal ConfigObj files. Unsurprisingly it uses Python syntax.
2001
 
 
2002
 
This means that lists are different (they are surrounded by square brackets),
2003
 
and strings *must* be quoted.
2004
 
 
2005
 
The types that ``unrepr`` can work with are :
2006
 
 
2007
 
    | strings, lists tuples
2008
 
    | None, True, False
2009
 
    | dictionaries, integers, floats
2010
 
    | longs and complex numbers
2011
 
    
2012
 
You can't store classes, types or instances.
2013
 
 
2014
 
``unrepr`` uses ``repr(object)`` to write out values, so it currently *doesn't*
2015
 
check that you are writing valid objects. If you attempt to read an unsupported
2016
 
value, ConfigObj will raise a ``configobj.UnknownType`` exception.
2017
 
 
2018
 
Values that are triple quoted cased. The triple quotes are removed *before*
2019
 
converting. This means that you can use triple quotes to write dictionaries
2020
 
over several lines in your config files. They won't be written like this
2021
 
though.
2022
 
 
2023
 
If you are writing config files by hand, for use with ``unrepr``, you should
2024
 
be aware of the following differences from normal ConfigObj syntax :
2025
 
 
2026
 
    | List : ``['A List', 'With', 'Strings']``
2027
 
    | Strings : ``"Must be quoted."``
2028
 
    | Backslash : ``"The backslash must be escaped \\"``
2029
 
 
2030
 
These all follow normal Python syntax.
2031
 
 
2032
 
In unrepr mode *inline comments* are not saved. This is because lines are
2033
 
parsed using the `compiler package <http://docs.python.org/lib/compiler.html>`_
2034
 
which discards comments.
2035
 
 
2036
 
 
2037
 
String Interpolation
2038
 
====================
2039
 
 
2040
 
.. note::
2041
 
    
2042
 
    String interpolation can slow down (slightly) the fetching of values
2043
 
    from your config object. If you aren't using interpolation and it
2044
 
    is performance critical then create your instance with
2045
 
    ``interpolation=False``.
2046
 
 
2047
 
ConfigObj allows string interpolation *similar* to the way ``ConfigParser``
2048
 
or ``string.Template`` work. The value of the ``interpolation`` attribute
2049
 
determines which style of interpolation you want to use. Valid values are
2050
 
"ConfigParser" or "Template" (case-insensitive, so "configparser" and
2051
 
"template" will also work). For backwards compatibility reasons, the value
2052
 
``True`` is also a valid value for the ``interpolation`` attribute, and
2053
 
will select ``ConfigParser``-style interpolation. At some undetermined point
2054
 
in the future, that default *may* change to ``Template``-style interpolation.
2055
 
 
2056
 
For ``ConfigParser``-style interpolation, you specify a value to be
2057
 
substituted by including ``%(name)s`` in the value.
2058
 
 
2059
 
For ``Template``-style interpolation, you specify a value to be substituted
2060
 
by including ``${cl}name{cr}`` in the value. Alternately, if 'name' is a valid
2061
 
Python identifier (i.e., is composed of nothing but alphanumeric characters,
2062
 
plus the underscore character), then the braces are optional and the value
2063
 
can be written as ``$name``.
2064
 
 
2065
 
Note that ``ConfigParser``-style interpolation and ``Template``-style
2066
 
interpolation are mutually exclusive; you cannot have a configuration file
2067
 
that's a mix of one or the other. Pick one and stick to it. ``Template``-style
2068
 
interpolation is simpler to read and write by hand, and is recommended if
2069
 
you don't have a particular reason to use ``ConfigParser``-style.
2070
 
 
2071
 
Interpolation checks first the current section to see if ``name`` is the key
2072
 
to a value. ('name' is case sensitive).
2073
 
 
2074
 
If it doesn't find it, next it checks the 'DEFAULT' sub-section of the current
2075
 
section.
2076
 
 
2077
 
If it still doesn't find it, it moves on to check the parent section and the
2078
 
parent section's 'DEFAULT' subsection, and so on all the way up to the main
2079
 
section.
2080
 
 
2081
 
If the value specified isn't found in any of these locations, then a
2082
 
``MissingInterpolationOption`` error is raised (a subclass of
2083
 
``ConfigObjError``).
2084
 
 
2085
 
If it is found then the returned value is also checked for substitutions. This
2086
 
allows you to make up compound values (for example directory paths) that use
2087
 
more than one default value. It also means it's possible to create circular
2088
 
references. If there are any circular references which would cause an infinite
2089
 
interpolation loop, an ``InterpolationLoopError`` is raised.
2090
 
 
2091
 
Both of these errors are subclasses of ``InterpolationError``, which is a
2092
 
subclass of ``ConfigObjError``.
2093
 
 
2094
 
String interpolation and validation don't play well together. This is because 
2095
 
validation overwrites values - and so may erase the interpolation references.
2096
 
See `Validation and Interpolation`_. (This can only happen if validation
2097
 
has to *change* the value).
2098
 
 
2099
 
New in ConfigObj 4.7.0: String interpolation is now done in members of list
2100
 
values.
2101
 
 
2102
 
 
2103
 
String Interpolation and List Values
2104
 
------------------------------------
2105
 
 
2106
 
Since version 4.7 string interpolation is done on string members of list values.
2107
 
If interpolation changes any members of the list then what you get back is a
2108
 
*copy* of the list rather than the original list.
2109
 
 
2110
 
This makes fetching list values slightly slower when interpolation is on, it
2111
 
also means that if you mutate the list changes won't be reflected in the
2112
 
original list:
2113
 
 
2114
 
.. code-block:: python
2115
 
 
2116
 
    >>> c = ConfigObj()
2117
 
    >>> c['foo'] = 'boo'
2118
 
    >>> c['bar'] = ['%(foo)s'] 
2119
 
    >>> c['bar']
2120
 
    ['boo']
2121
 
    >>> c['bar'].append('fish')
2122
 
    >>> c['bar']
2123
 
    ['boo']
2124
 
 
2125
 
Instead of mutating the list you must create a new list and reassign it.
2126
 
 
2127
 
 
2128
 
Comments
2129
 
========
2130
 
 
2131
 
Any line that starts with a '#', possibly preceded by whitespace, is a comment.
2132
 
 
2133
 
If a config file starts with comments then these are preserved as the
2134
 
initial_comment_.
2135
 
 
2136
 
If a config file ends with comments then these are preserved as the
2137
 
final_comment_.
2138
 
 
2139
 
Every key or section marker may have lines of comments immediately above it.
2140
 
These are saved as the ``comments`` attribute of the section. Each member is a
2141
 
list of lines.
2142
 
 
2143
 
You can also have a comment inline with a value. These are saved as the
2144
 
``inline_comments`` attribute of the section, with one entry per member of the
2145
 
section.
2146
 
 
2147
 
Subsections (section markers in the config file) can also have comments.
2148
 
 
2149
 
See `Section Attributes`_ for more on these attributes.
2150
 
 
2151
 
These comments are all written back out by the ``write`` method.
2152
 
 
2153
 
 
2154
 
flatten_errors
2155
 
==============
2156
 
 
2157
 
.. code-block:: python
2158
 
 
2159
 
    flatten_errors(cfg, res)
2160
 
 
2161
 
Validation_ is a powerful way of checking that the values supplied by the user
2162
 
make sense.
2163
 
 
2164
 
The validate_ method returns a results dictionary that represents pass or fail
2165
 
for each value. This doesn't give you any information about *why* the check
2166
 
failed.
2167
 
 
2168
 
``flatten_errors`` is an example function that turns a results dictionary into
2169
 
a flat list, that only contains values that *failed*.
2170
 
 
2171
 
``cfg`` is the ConfigObj instance being checked, ``res`` is the results
2172
 
dictionary returned by ``validate``.
2173
 
 
2174
 
It returns a list of keys that failed. Each member of the list is a tuple::
2175
 
 
2176
 
    ([list of sections...], key, result)
2177
 
 
2178
 
If ``validate`` was called with ``preserve_errors=False`` (the default)
2179
 
then ``result`` will always be ``False``.
2180
 
 
2181
 
*list of sections* is a flattened list of sections that the key was found
2182
 
in.
2183
 
 
2184
 
If the section was missing then key will be ``None``.
2185
 
 
2186
 
If the value (or section) was missing then ``result`` will be ``False``.
2187
 
 
2188
 
If ``validate`` was called with ``preserve_errors=True`` and a value
2189
 
was present, but failed the check, then ``result`` will be the exception
2190
 
object returned. You can use this as a string that describes the failure.
2191
 
 
2192
 
For example :
2193
 
 
2194
 
    *The value "3" is of the wrong type*.
2195
 
 
2196
 
 
2197
 
Example Usage
2198
 
-------------
2199
 
 
2200
 
The output from ``flatten_errors`` is a list of tuples.
2201
 
 
2202
 
Here is an example of how you could present this information to the user.
2203
 
 
2204
 
 
2205
 
.. code-block:: python
2206
 
 
2207
 
    vtor = validate.Validator()
2208
 
    # ini is your config file - cs is the configspec
2209
 
    cfg = ConfigObj(ini, configspec=cs)
2210
 
    res = cfg.validate(vtor, preserve_errors=True)
2211
 
    for entry in flatten_errors(cfg, res):
2212
 
        # each entry is a tuple
2213
 
        section_list, key, error = entry
2214
 
        if key is not None:
2215
 
           section_list.append(key)
2216
 
        else:
2217
 
            section_list.append('[missing section]')
2218
 
        section_string = ', '.join(section_list)
2219
 
        if error == False:
2220
 
            error = 'Missing value or section.'
2221
 
        print section_string, ' = ', error
2222
 
 
2223
 
 
2224
 
get_extra_values
2225
 
================
2226
 
 
2227
 
 
2228
 
.. code-block:: python
2229
 
 
2230
 
    get_extra_values(conf)
2231
 
 
2232
 
New in ConfigObj 4.7.0.
2233
 
 
2234
 
Find all the values and sections not in the configspec from a validated
2235
 
ConfigObj.
2236
 
 
2237
 
``get_extra_values`` returns a list of tuples where each tuple represents
2238
 
either an extra section, or an extra value.
2239
 
 
2240
 
The tuples contain two values, a tuple representing the section the value 
2241
 
is in and the name of the extra values. For extra values in the top level
2242
 
section the first member will be an empty tuple. For values in the 'foo'
2243
 
section the first member will be ``('foo',)``. For members in the 'bar'
2244
 
subsection of the 'foo' section the first member will be ``('foo', 'bar')``.
2245
 
 
2246
 
Extra sections will only have one entry. Values and subsections inside
2247
 
an extra section aren't listed separately.
2248
 
 
2249
 
NOTE: If you call ``get_extra_values`` on a ConfigObj instance that hasn't
2250
 
been validated it will return an empty list.
2251
 
 
2252
 
 
2253
 
Example Usage
2254
 
-------------
2255
 
 
2256
 
The output from ``get_extra_values`` is a list of tuples.
2257
 
 
2258
 
Here is an example of how you could present this information to the user.
2259
 
 
2260
 
.. code-block:: python
2261
 
 
2262
 
    vtor = validate.Validator()
2263
 
    # ini is your config file - cs is the configspec
2264
 
    cfg = ConfigObj(ini, configspec=cs)
2265
 
    cfg.validate(vtor, preserve_errors=True)
2266
 
    
2267
 
    for sections, name in get_extra_values(cfg):
2268
 
    
2269
 
        # this code gets the extra values themselves
2270
 
        the_section = cfg
2271
 
        for section in sections:
2272
 
            the_section = cfg[section]
2273
 
            
2274
 
        # the_value may be a section or a value
2275
 
        the_value = the_section[name]
2276
 
        
2277
 
        section_or_value = 'value
2278
 
        if isinstance(the_value, dict):
2279
 
            # Sections are subclasses of dict
2280
 
            section_or_value = 'section'
2281
 
        
2282
 
        section_string = ', '.join(sections) or "top level"
2283
 
        print 'Extra entry in section: %s. Entry %r is a %s' % (section_string, name, section_or_value)
2284
 
        
2285
 
 
2286
 
 
2287
 
CREDITS
2288
 
=======
2289
 
 
2290
 
ConfigObj 4 is written by (and copyright) `Michael Foord`_ and 
2291
 
`Nicola Larosa`_.
2292
 
 
2293
 
Particularly thanks to Nicola Larosa for help on the config file spec, the
2294
 
validation system and the doctests.
2295
 
 
2296
 
*validate.py* was originally written by Michael Foord and Mark Andrews.
2297
 
 
2298
 
Thanks to many others for input, patches and bugfixes.
2299
 
 
2300
 
 
2301
 
 
2302
 
LICENSE
2303
 
=======
2304
 
 
2305
 
ConfigObj, and related files, are licensed under the BSD license. This is a
2306
 
very unrestrictive license, but it comes with the usual disclaimer. This is
2307
 
free software: test it, break it, just don't blame us if it eats your data !
2308
 
Of course if it does, let us know and we'll fix the problem so it doesn't
2309
 
happen to anyone else::
2310
 
 
2311
 
    Copyright (c) 2004 - 2010, Michael Foord & Nicola Larosa
2312
 
    All rights reserved.
2313
 
 
2314
 
    Redistribution and use in source and binary forms, with or without
2315
 
    modification, are permitted provided that the following conditions are
2316
 
    met:
2317
 
 
2318
 
 
2319
 
        * Redistributions of source code must retain the above copyright
2320
 
          notice, this list of conditions and the following disclaimer.
2321
 
 
2322
 
        * Redistributions in binary form must reproduce the above
2323
 
          copyright notice, this list of conditions and the following
2324
 
          disclaimer in the documentation and/or other materials provided
2325
 
          with the distribution.
2326
 
 
2327
 
        * Neither the name of Michael Foord nor Nicola Larosa
2328
 
          may be used to endorse or promote products derived from this
2329
 
          software without specific prior written permission.
2330
 
 
2331
 
    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2332
 
    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2333
 
    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2334
 
    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2335
 
    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2336
 
    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2337
 
    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2338
 
    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2339
 
    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2340
 
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2341
 
    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2342
 
 
2343
 
You should also be able to find a copy of this license at : `BSD License`_
2344
 
 
2345
 
.. _BSD License: http://www.voidspace.org.uk/python/license.shtml
2346
 
 
2347
 
 
2348
 
TODO
2349
 
====
2350
 
 
2351
 
Better support for configuration from multiple files, including tracking
2352
 
*where* the original file came from and writing changes to the correct
2353
 
file.
2354
 
 
2355
 
Make ``newline`` a keyword argument (as well as an attribute) ?
2356
 
 
2357
 
``UTF16`` encoded files, when returned as a list of lines, will have the
2358
 
BOM at the start of every line. Should this be removed from all but the
2359
 
first line ?
2360
 
 
2361
 
Option to set warning type for unicode decode ? (Defaults to strict).
2362
 
 
2363
 
A method to optionally remove uniform indentation from multiline values.
2364
 
(do as an example of using ``walk`` - along with string-escape)
2365
 
 
2366
 
Should the results dictionary from validate be an ordered dictionary if
2367
 
`odict <http://www.voidspace.org.uk/python/odict.html>`_ is available ?
2368
 
 
2369
 
Implement some of the sequence methods (which include slicing) from the
2370
 
newer ``odict`` ?
2371
 
 
2372
 
Preserve line numbers of values (and possibly the original text of each value).
2373
 
 
2374
 
 
2375
 
ISSUES
2376
 
======
2377
 
 
2378
 
.. note::
2379
 
 
2380
 
    Please file any bug reports to `Michael Foord`_ or the **ConfigObj**
2381
 
    `Mailing List`_.
2382
 
 
2383
 
There is currently no way to specify the encoding of a configspec file.
2384
 
 
2385
 
As a consequence of the changes to configspec handling in version 4.6.0, when
2386
 
you create a ConfigObj instance and provide a configspec, the configspec
2387
 
attribute is only set on the ConfigObj instance - it isn't set on the sections until you validate. You also can't set the configspec attribute to be a dictionary. This wasn't documented but did work previously.
2388
 
 
2389
 
In order to fix the problem with hashes in configspecs I had to turn off the parsing of inline comments in configspecs. This will only affect you if you are using ``copy=True`` when validating and expecting inline comments to be copied from the configspec into the ConfigObj instance (all other comments will be copied as usual).
2390
 
    
2391
 
If you *create* the configspec by passing in a ConfigObj instance (usual way is to pass in a filename or list of lines) then you should pass in ``_inspec=True`` to the constructor to allow hashes in values. This is the magic that switches off inline comment parsing.
2392
 
 
2393
 
When using ``copy`` mode for validation, it won't copy ``DEFAULT``
2394
 
sections. This is so that you *can* use interpolation in configspec
2395
 
files. This is probably true even if interpolation is off in the 
2396
 
configspec.
2397
 
 
2398
 
You can't have a keyword with the same name as a section (in the same
2399
 
section). They are both dictionary keys - so they would overlap.
2400
 
 
2401
 
ConfigObj doesn't quote and unquote values if ``list_values=False``.
2402
 
This means that leading or trailing whitespace in values will be lost when
2403
 
writing. (Unless you manually quote).
2404
 
 
2405
 
Interpolation checks first the current section, then the 'DEFAULT' subsection
2406
 
of the current section, before moving on to the current section's parent and
2407
 
so on up the tree.
2408
 
 
2409
 
Does it matter that we don't support the ':' divider, which is supported
2410
 
by ``ConfigParser`` ?
2411
 
 
2412
 
String interpolation and validation don't play well together. When
2413
 
validation changes type it sets the value. This will correctly fetch the
2414
 
value using interpolation - but then overwrite the interpolation reference.
2415
 
If the value is unchanged by validation (it's a string) - but other types
2416
 
will be.
2417
 
 
2418
 
 
2419
 
CHANGELOG
2420
 
=========
2421
 
 
2422
 
This is an abbreviated changelog showing the major releases up to version 4.
2423
 
From version 4 it lists all releases and changes.
2424
 
 
2425
 
 
2426
 
2010/02/27 - Version 4.7.2
2427
 
--------------------------
2428
 
 
2429
 
* BUGFIX: Restore Python 2.3 compatibility
2430
 
* BUGFIX: Members that were lists were being returned as copies due to interpolation
2431
 
  introduced in 4.7. Lists are now only copies if interpolation changes a list
2432
 
  member.
2433
 
* BUGFIX: ``pop`` now does interpolation in list values as well.
2434
 
* BUGFIX: where interpolation matches a section name rather than a value it is
2435
 
  ignored instead of raising an exception on fetching the item.
2436
 
* BUGFIX: values that use interpolation to reference members that don't exist can
2437
 
  now be repr'd.
2438
 
* BUGFIX: Fix to avoid writing '\\r\\r\\n' on Windows when given a file opened in
2439
 
  text write mode ('w').
2440
 
  
2441
 
See `String Interpolation and List Values`_ for information about the problem with lists and interpolation.
2442
 
 
2443
 
 
2444
 
2010/02/06 - Version 4.7.1
2445
 
--------------------------
2446
 
 
2447
 
* Fix bug in options deprecation warning added in 4.7.0
2448
 
 
2449
 
 
2450
 
2010/01/09 - Version 4.7.0
2451
 
--------------------------
2452
 
 
2453
 
* Minimum supported version of Python is now 2.3
2454
 
* ~25% performance improvement thanks to Christian Heimes
2455
 
* String interpolation now works in list value members
2456
 
* After validation any additional entries not in the configspec are listed in
2457
 
  the ``extra_values`` section member
2458
 
* Addition of the ``get_extra_values`` function for finding all extra values
2459
 
  in a validated ConfigObj instance
2460
 
* Deprecated the use of the ``options`` dictionary in the ConfigObj constructor
2461
 
  and added explicit keyword arguments instead. Use \*\*options if you want
2462
 
  to initialise a ConfigObj instance from a dictionary
2463
 
* Constructing a ConfigObj from an existing ConfigObj instance now preserves
2464
 
  the order of values and sections from the original instance in the new one
2465
 
* BUGFIX: Checks that failed validation would not populate ``default_values`` and
2466
 
  ``restore_default_value()`` wouldn't work for those entries
2467
 
* BUGFIX: clear() now clears 'defaults'
2468
 
* BUGFIX: empty values in list values were accidentally valid syntax. They now
2469
 
  raise a ``ParseError``. e.g. "value = 1, , 2"
2470
 
* BUGFIX: Change to the result of a call to ``validate`` when ``preserve_errors``
2471
 
  is True. Previously sections where *all* values failed validation would
2472
 
  return False for the section rather than preserving the errors. False will
2473
 
  now only be returned for a section if it is missing
2474
 
* Distribution includes version 1.0.1 of validate.py
2475
 
* Removed __revision__ and __docformat__
2476
 
 
2477
 
 
2478
 
2009/04/13 - Version 4.6.0
2479
 
--------------------------
2480
 
 
2481
 
* Pickling of ConfigObj instances now supported (thanks to Christian Heimes)
2482
 
* Hashes in confgspecs are now allowed (see note below)
2483
 
* Replaced use of hasattr (which can swallow exceptions) with getattr
2484
 
* __many__ in configspecs can refer to scalars (ordinary values) as well as sections
2485
 
* You can use ___many___ (three underscores!) where you want to use __many__ as well
2486
 
* You can now have normal sections inside configspec sections that use __many__
2487
 
* You can now create an empty ConfigObj with a configspec, programmatically set values and then validate
2488
 
* A section that was supplied as a value (or vice-versa) in the actual config file would cause an exception during validation (the config file is still broken of course, but it is now handled gracefully)
2489
 
* Added ``as_list`` method
2490
 
* Removed the deprecated ``istrue``, ``encode`` and ``decode`` methods
2491
 
* Running test_configobj.py now also runs the doctests in the configobj module
2492
 
 
2493
 
As a consequence of the changes to configspec handling, when you create a ConfigObj instance and provide 
2494
 
a configspec, the configspec attribute is only set on the ConfigObj instance - it isn't set on the 
2495
 
sections until you validate. You also can't set the configspec attribute to be a dictionary. This wasn't 
2496
 
documented but did work previously.
2497
 
 
2498
 
In order to fix the problem with hashes in configspecs I had to turn off the parsing of inline comments 
2499
 
in configspecs. This will only affect you if you are using ``copy=True`` when validating and expecting 
2500
 
inline comments to be copied from the configspec into the ConfigObj instance (all other comments will be 
2501
 
copied as usual).
2502
 
    
2503
 
If you *create* the configspec by passing in a ConfigObj instance (usual way is to pass in a filename or 
2504
 
list of lines) then you should pass in ``_inspec=True`` to the constructor to allow hashes in values. 
2505
 
This is the magic that switches off inline comment parsing.
2506
 
 
2507
 
    
2508
 
2008/06/27 - Version 4.5.3
2509
 
--------------------------
2510
 
 
2511
 
BUGFIX: fixed a problem with ``copy=True`` when validating with configspecs that use
2512
 
``__many__`` sections.
2513
 
 
2514
 
 
2515
 
2008/02/05 - Version 4.5.2
2516
 
--------------------------
2517
 
 
2518
 
Distribution updated to include version 0.3.2 of validate_. This means that
2519
 
``None`` as a default value in configspecs works.
2520
 
 
2521
 
 
2522
 
2008/02/05 - Version 4.5.1
2523
 
--------------------------
2524
 
 
2525
 
Distribution updated to include version 0.3.1 of validate_. This means that
2526
 
Unicode configspecs now work.
2527
 
 
2528
 
 
2529
 
2008/02/05 - Version 4.5.0
2530
 
--------------------------
2531
 
 
2532
 
ConfigObj will now guarantee that files will be written terminated with a
2533
 
newline.
2534
 
 
2535
 
ConfigObj will no longer attempt to import the ``validate`` module, until/unless 
2536
 
you call ``ConfigObj.validate`` with ``preserve_errors=True``. This makes it 
2537
 
faster to import.
2538
 
 
2539
 
New methods ``restore_default`` and ``restore_defaults``. ``restore_default``
2540
 
resets an entry to its default value (and returns that value). ``restore_defaults``
2541
 
resets all entries to their default value. It doesn't modify entries without a 
2542
 
default value. You must have validated a ConfigObj (which populates the
2543
 
``default_values`` dictionary) before calling these methods.
2544
 
 
2545
 
BUGFIX: Proper quoting of keys, values and list values that contain hashes 
2546
 
(when writing).  When ``list_values=False``, values containing hashes are 
2547
 
triple quoted.
2548
 
 
2549
 
Added the ``reload`` method. This reloads a ConfigObj from file. If the filename
2550
 
attribute is not set then a ``ReloadError`` (a new exception inheriting from
2551
 
``IOError``) is raised.
2552
 
 
2553
 
BUGFIX: Files are read in with 'rb' mode, so that native/non-native line endings work!
2554
 
 
2555
 
Minor efficiency improvement in ``unrepr`` mode.
2556
 
 
2557
 
Added missing docstrings for some overidden dictionary methods.
2558
 
 
2559
 
Added the ``reset`` method. This restores a ConfigObj to a freshly created state.
2560
 
 
2561
 
Removed old CHANGELOG file.
2562
 
 
2563
 
 
2564
 
2007/02/04 - Version 4.4.0
2565
 
--------------------------
2566
 
 
2567
 
Official release of 4.4.0
2568
 
 
2569
 
 
2570
 
2006/12/17 - Version 4.3.3-alpha4
2571
 
---------------------------------
2572
 
 
2573
 
By Nicola Larosa
2574
 
 
2575
 
Allowed arbitrary indentation in the ``indent_type`` parameter, removed the
2576
 
``NUM_INDENT_SPACES`` and ``MAX_INTERPOL_DEPTH`` (a leftover) constants,
2577
 
added indentation tests (including another docutils workaround, sigh), updated
2578
 
the documentation.
2579
 
 
2580
 
By Michael Foord
2581
 
 
2582
 
Made the import of ``compiler`` conditional so that ``ConfigObj`` can be used
2583
 
with `IronPython <http://www.codeplex.com/IronPython>`_.
2584
 
 
2585
 
 
2586
 
2006/12/17 - Version 4.3.3-alpha3
2587
 
---------------------------------
2588
 
 
2589
 
By Nicola Larosa
2590
 
 
2591
 
Added a missing ``self.`` in the _handle_comment method and a related test,
2592
 
per Sourceforge bug #1523975.
2593
 
 
2594
 
 
2595
 
2006/12/09 - Version 4.3.3-alpha2
2596
 
---------------------------------
2597
 
 
2598
 
By Nicola Larosa
2599
 
 
2600
 
Changed interpolation search strategy, based on this patch by Robin Munn:
2601
 
http://sourceforge.net/mailarchive/message.php?msg_id=17125993
2602
 
 
2603
 
 
2604
 
2006/12/09 - Version 4.3.3-alpha1
2605
 
---------------------------------
2606
 
 
2607
 
By Nicola Larosa
2608
 
 
2609
 
Added Template-style interpolation, with tests, based on this patch by
2610
 
Robin Munn: http://sourceforge.net/mailarchive/message.php?msg_id=17125991
2611
 
(awful archives, bad Sourceforge, bad).
2612
 
 
2613
 
 
2614
 
2006/06/04 - Version 4.3.2
2615
 
--------------------------
2616
 
 
2617
 
Changed error handling, if parsing finds a single error then that error will
2618
 
be re-raised. That error will still have an ``errors`` and a ``config``
2619
 
attribute.
2620
 
 
2621
 
Fixed bug where '\\n' terminated files could be truncated.
2622
 
 
2623
 
Bugfix in ``unrepr`` mode, it couldn't handle '#' in values. (Thanks to
2624
 
Philippe Normand for the report.)
2625
 
 
2626
 
As a consequence of this fix, ConfigObj doesn't now keep inline comments in
2627
 
``unrepr`` mode. This is because the parser in the `compiler package`_
2628
 
doesn't keep comments.
2629
 
 
2630
 
Error messages are now more useful. They tell you the number of parsing errors
2631
 
and the line number of the first error. (In the case of multiple errors.)
2632
 
 
2633
 
Line numbers in exceptions now start at 1, not 0.
2634
 
 
2635
 
Errors in ``unrepr`` mode are now handled the same way as in the normal mode.
2636
 
The errors stored will be an ``UnreprError``.
2637
 
 
2638
 
 
2639
 
2006/04/29 - Version 4.3.1
2640
 
--------------------------
2641
 
 
2642
 
Added ``validate.py`` back into ``configobj.zip``. (Thanks to Stewart
2643
 
Midwinter)
2644
 
 
2645
 
Updated to `validate.py`_ 0.2.2.
2646
 
 
2647
 
Preserve tuples when calling the ``dict`` method. (Thanks to Gustavo Niemeyer.)
2648
 
 
2649
 
Changed ``__repr__`` to return a string that contains ``ConfigObj({ ... })``.
2650
 
 
2651
 
Change so that an options dictionary isn't modified by passing it to ConfigObj.
2652
 
(Thanks to Artarious.)
2653
 
 
2654
 
Added ability to handle negative integers in ``unrepr``. (Thanks to Kevin
2655
 
Dangoor.)
2656
 
 
2657
 
 
2658
 
2006/03/24 - Version 4.3.0
2659
 
--------------------------
2660
 
 
2661
 
Moved the tests and the CHANGELOG (etc) into a separate file. This has reduced
2662
 
the size of ``configobj.py`` by about 40%.
2663
 
 
2664
 
Added the ``unrepr`` mode to reading and writing config files. Thanks to Kevin
2665
 
Dangoor for this suggestion.
2666
 
 
2667
 
Empty values are now valid syntax. They are read as an empty string ``''``.
2668
 
(``key =``, or ``key = # comment``.)
2669
 
 
2670
 
``validate`` now honours the order of the configspec.
2671
 
 
2672
 
Added the ``copy`` mode to validate. Thanks to Louis Cordier for this
2673
 
suggestion.
2674
 
 
2675
 
Fixed bug where files written on windows could be given ``'\r\r\n'`` line
2676
 
terminators.
2677
 
 
2678
 
Fixed bug where last occurring comment line could be interpreted as the
2679
 
final comment if the last line isn't terminated.
2680
 
 
2681
 
Fixed bug where nested list values would be flattened when ``write`` is
2682
 
called. Now sub-lists have a string representation written instead.
2683
 
 
2684
 
Deprecated ``encode`` and ``decode`` methods instead.
2685
 
 
2686
 
You can now pass in a ConfigObj instance as a configspec (remember to read
2687
 
the configspec file using ``list_values=False``).
2688
 
 
2689
 
Sorted footnotes in the docs.
2690
 
 
2691
 
 
2692
 
2006/02/16 - Version 4.2.0
2693
 
--------------------------
2694
 
 
2695
 
Removed ``BOM_UTF8`` from ``__all__``.
2696
 
 
2697
 
The ``BOM`` attribute has become a boolean. (Defaults to ``False``.) It is
2698
 
*only* ``True`` for the ``UTF16/UTF8`` encodings.
2699
 
 
2700
 
File like objects no longer need a ``seek`` attribute.
2701
 
 
2702
 
Full unicode support added. New options/attributes ``encoding``,
2703
 
``default_encoding``.
2704
 
 
2705
 
ConfigObj no longer keeps a reference to file like objects. Instead the
2706
 
``write`` method takes a file like object as an optional argument. (Which
2707
 
will be used in preference of the ``filename`` attribute if that exists as
2708
 
well.)
2709
 
 
2710
 
utf16 files decoded to unicode.
2711
 
 
2712
 
If ``BOM`` is ``True``, but no encoding specified, then the utf8 BOM is
2713
 
written out at the start of the file. (It will normally only be ``True`` if
2714
 
the utf8 BOM was found when the file was read.)
2715
 
 
2716
 
Thanks to Aaron Bentley for help and testing on the unicode issues.
2717
 
 
2718
 
File paths are *not* converted to absolute paths, relative paths will
2719
 
remain relative as the ``filename`` attribute.
2720
 
 
2721
 
Fixed bug where ``final_comment`` wasn't returned if ``write`` is returning
2722
 
a list of lines.
2723
 
 
2724
 
Deprecated ``istrue``, replaced it with ``as_bool``.
2725
 
 
2726
 
Added ``as_int`` and ``as_float``.
2727
 
 
2728
 
 
2729
 
2005/12/14 - Version 4.1.0
2730
 
--------------------------
2731
 
 
2732
 
Added ``merge``, a recursive update.
2733
 
 
2734
 
Added ``preserve_errors`` to ``validate`` and the ``flatten_errors``
2735
 
example function.
2736
 
 
2737
 
Thanks to Matthew Brett for suggestions and helping me iron out bugs.
2738
 
    
2739
 
Fixed bug where a config file is *all* comment, the comment will now be
2740
 
``initial_comment`` rather than ``final_comment``.
2741
 
 
2742
 
Validation no longer done on the 'DEFAULT' section (only in the root level).
2743
 
This allows interpolation in configspecs.
2744
 
 
2745
 
Also use the new list syntax in validate_ 0.2.1. (For configspecs).
2746
 
 
2747
 
 
2748
 
2005/12/02 - Version 4.0.2
2749
 
--------------------------
2750
 
 
2751
 
Fixed bug in ``create_empty``. Thanks to Paul Jimenez for the report.
2752
 
 
2753
 
 
2754
 
2005/11/05 - Version 4.0.1
2755
 
--------------------------
2756
 
 
2757
 
Fixed bug in ``Section.walk`` when transforming names as well as values.
2758
 
 
2759
 
Added the ``istrue`` method. (Fetches the boolean equivalent of a string
2760
 
value).
2761
 
 
2762
 
Fixed ``list_values=False`` - they are now only quoted/unquoted if they
2763
 
are multiline values.
2764
 
 
2765
 
List values are written as ``item, item`` rather than ``item,item``.
2766
 
 
2767
 
 
2768
 
2005/10/17 - Version 4.0.0
2769
 
--------------------------
2770
 
 
2771
 
**ConfigObj 4.0.0 Final**
2772
 
 
2773
 
Fixed bug in ``setdefault``. When creating a new section with setdefault the
2774
 
reference returned would be to the dictionary passed in *not* to the new 
2775
 
section. Bug fixed and behaviour documented.
2776
 
 
2777
 
Obscure typo/bug fixed in ``write``. Wouldn't have affected anyone though.
2778
 
 
2779
 
 
2780
 
2005/09/09 - Version 4.0.0 beta 5
2781
 
---------------------------------
2782
 
 
2783
 
Removed ``PositionError``.
2784
 
 
2785
 
Allowed quotes around keys as documented.
2786
 
 
2787
 
Fixed bug with commas in comments. (matched as a list value)
2788
 
 
2789
 
 
2790
 
2005/09/07 - Version 4.0.0 beta 4
2791
 
---------------------------------
2792
 
 
2793
 
Fixed bug in ``__delitem__``. Deleting an item no longer deletes the 
2794
 
``inline_comments`` attribute.
2795
 
 
2796
 
Fixed bug in initialising ConfigObj from a ConfigObj.
2797
 
 
2798
 
Changed the mailing list address.
2799
 
 
2800
 
 
2801
 
2005/08/28 - Version 4.0.0 beta 3
2802
 
---------------------------------
2803
 
 
2804
 
Interpolation is switched off before writing out files.
2805
 
 
2806
 
Fixed bug in handling ``StringIO`` instances. (Thanks to report from
2807
 
Gustavo Niemeyer.)
2808
 
 
2809
 
Moved the doctests from the ``__init__`` method to a separate function.
2810
 
(For the sake of IDE calltips).
2811
 
 
2812
 
 
2813
 
2005/08/25 - Version 4.0.0 beta 2
2814
 
---------------------------------
2815
 
 
2816
 
Amendments to *validate.py*.
2817
 
 
2818
 
First public release.
2819
 
 
2820
 
 
2821
 
2005/08/21 - Version 4.0.0 beta 1
2822
 
---------------------------------
2823
 
 
2824
 
Reads nested subsections to any depth.
2825
 
 
2826
 
Multiline values.
2827
 
 
2828
 
Simplified options and methods.
2829
 
 
2830
 
New list syntax.
2831
 
 
2832
 
Faster, smaller, and better parser.
2833
 
 
2834
 
Validation greatly improved. Includes:
2835
 
 
2836
 
    * type conversion
2837
 
    * default values
2838
 
    * repeated sections
2839
 
 
2840
 
Improved error handling.
2841
 
 
2842
 
Plus lots of other improvements.
2843
 
 
2844
 
 
2845
 
2004/05/24 - Version 3.0.0
2846
 
--------------------------
2847
 
 
2848
 
Several incompatible changes: another major overhaul and change. (Lots of
2849
 
improvements though).
2850
 
 
2851
 
Added support for standard config files with sections. This has an entirely
2852
 
new interface: each section is a dictionary of values.
2853
 
 
2854
 
Changed the update method to be called writein: update clashes with a dict
2855
 
method.
2856
 
 
2857
 
Made various attributes keyword arguments, added several.
2858
 
 
2859
 
Configspecs and orderlists have changed a great deal.
2860
 
 
2861
 
Removed support for adding dictionaries: use update instead.
2862
 
 
2863
 
Now subclasses a new class called caselessDict. This should add various
2864
 
dictionary methods that could have caused errors before.
2865
 
 
2866
 
It also preserves the original casing of keywords when writing them back out.
2867
 
 
2868
 
Comments are also saved using a ``caselessDict``.
2869
 
 
2870
 
Using a non-string key will now raise a ``TypeError`` rather than converting 
2871
 
the key.
2872
 
 
2873
 
Added an exceptions keyword for *much* better handling of errors.
2874
 
 
2875
 
Made ``creatempty=False`` the default.
2876
 
 
2877
 
Now checks indict *and* any keyword args. Keyword args take precedence over
2878
 
indict.
2879
 
 
2880
 
``' ', ':', '=', ','`` and ``'\t'`` are now all valid dividers where the 
2881
 
keyword is unquoted.
2882
 
 
2883
 
ConfigObj now does no type checking against configspec when you set items.
2884
 
 
2885
 
delete and add methods removed (they were unnecessary).
2886
 
 
2887
 
Docs rewritten to include all this gumph and more; actually ConfigObj is
2888
 
*really* easy to use.
2889
 
 
2890
 
Support for stdout was removed.
2891
 
 
2892
 
A few new methods added.
2893
 
 
2894
 
Charmap is now incorporated into ConfigObj.
2895
 
 
2896
 
 
2897
 
2004/03/14 - Version 2.0.0 beta
2898
 
-------------------------------
2899
 
 
2900
 
Re-written it to subclass dict. My first forays into inheritance and operator
2901
 
overloading.
2902
 
 
2903
 
The config object now behaves like a dictionary.
2904
 
 
2905
 
I've completely broken the interface, but I don't think anyone was really
2906
 
using it anyway.
2907
 
 
2908
 
This new version is much more 'classy'.
2909
 
 
2910
 
It will also read straight from/to a filename and completely parse a config
2911
 
file without you *having* to supply a config spec.
2912
 
 
2913
 
Uses listparse, so can handle nested list items as values.
2914
 
 
2915
 
No longer has getval and setval methods: use normal dictionary methods, or add
2916
 
and delete.
2917
 
 
2918
 
 
2919
 
2004/01/29 - Version 1.0.5
2920
 
--------------------------
2921
 
 
2922
 
Version 1.0.5 has a couple of bugfixes as well as a couple of useful additions
2923
 
over previous versions.
2924
 
 
2925
 
Since 1.0.0 the buildconfig function has been moved into this distribution,
2926
 
and the methods reset, verify, getval and setval have been added.
2927
 
 
2928
 
A couple of bugs have been fixed.
2929
 
 
2930
 
 
2931
 
Origins
2932
 
-------
2933
 
 
2934
 
ConfigObj originated in a set of functions for reading config files in the
2935
 
`atlantibots <http://www.voidspace.org.uk/atlantibots/>`_ project. The original
2936
 
functions were written by Rob McNeur.
2937
 
 
2938
 
 
2939
 
----------
2940
 
 
2941
 
 
2942
 
Footnotes
2943
 
=========
2944
 
 
2945
 
.. [#] And if you discover any bugs, let us know. We'll fix them quickly.
2946
 
 
2947
 
.. [#] If you specify a filename that doesn't exist, ConfigObj will assume you
2948
 
    are creating a new one. See the *create_empty* and *file_error* options.
2949
 
 
2950
 
.. [#] They can be byte strings (*ordinary* strings) or Unicode.
2951
 
 
2952
 
.. [#] Except we don't support the RFC822 style line continuations, nor ':' as
2953
 
    a divider.
2954
 
 
2955
 
.. [#] This is a change in ConfigObj 4.2.0. Note that ConfigObj doesn't call
2956
 
    the seek method of any file like object you pass in. You may want to call
2957
 
    ``file_object.seek(0)`` yourself, first.
2958
 
 
2959
 
.. [#] A side effect of this is that it enables you to copy a ConfigObj :
2960
 
 
2961
 
    .. code-block:: python
2962
 
 
2963
 
        # only copies members
2964
 
        # not attributes/comments
2965
 
        config2 = ConfigObj(config1)
2966
 
 
2967
 
    Since ConfigObj 4.7.0 the order of members and sections will be
2968
 
    preserved when copying a ConfigObj instance.
2969
 
 
2970
 
.. [#] Other than lists of strings.
2971
 
 
2972
 
.. [#] The exception is if it detects a ``UTF16`` encoded file which it
2973
 
    must decode before parsing.
2974
 
     
2975
 
.. [#] The method signature shows that this method takes
2976
 
    two arguments. The second is the section to be written. This is because the
2977
 
    ``write`` method is called recursively.
2978
 
 
2979
 
.. [#] The dict method doesn't actually use the deepcopy mechanism. This means
2980
 
    if you add nested lists (etc) to your ConfigObj, then the dictionary
2981
 
    returned by dict may contain some references. For all *normal* ConfigObjs
2982
 
    it will return a deepcopy.
2983
 
 
2984
 
.. [#] Passing ``(section, key)`` rather than ``(value, key)`` allows you to
2985
 
    change the value by setting ``section[key] = newval``. It also gives you
2986
 
    access to the *rename* method of the section.
2987
 
 
2988
 
.. [#] Minimum required version of *validate.py* 0.2.0 .
2989
 
 
2990
 
.. _listquote: http://www.voidspace.org.uk/python/modules.shtml#listquote
2991
 
.. _Michael Foord: http://www.voidspace.org.uk/python/weblog/index.shtml
2992
 
.. _Nicola Larosa: http://www.teknico.net