/brz/remove-bazaar

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