~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/util/configobj/docs/configobj.txt

  • Committer: Martin Pool
  • Date: 2005-11-04 01:46:31 UTC
  • mto: (1185.33.49 bzr.dev)
  • mto: This revision was merged to the branch mainline in revision 1512.
  • Revision ID: mbp@sourcefrog.net-20051104014631-750e0ad4172c952c
Make biobench directly executable

Show diffs side-by-side

added added

removed removed

Lines of Context:
7
7
----------------------------------------
8
8
 
9
9
:Authors: Michael Foord, Nicola Larosa
10
 
:Version: ConfigObj 4.5.2
11
 
:Date: 2008/02/24
 
10
:Version: ConfigObj 4.0.0
 
11
:Date: 2005/10/17
12
12
:Homepage: `ConfigObj Homepage`_
13
13
:Sourceforge: Sourceforge_
14
 
:Development: `SVN Repository`_
15
14
:License: `BSD License`_
16
15
:Support: `Mailing List`_
17
16
 
18
17
.. _Mailing List: http://lists.sourceforge.net/lists/listinfo/configobj-develop
19
 
.. _SVN Repository: http://svn.pythonutils.python-hosting.com
20
18
 
21
19
.. meta::
22
20
   :description: ConfigObj - a Python module for easy reading and writing of 
24
22
   :keywords: python, script, module, config, configuration, data, persistence,
25
23
              developer, configparser
26
24
 
27
 
 
28
25
.. contents:: ConfigObj Manual
29
26
.. sectnum::
30
27
 
31
 
 
32
28
Introduction
33
29
============
34
30
 
36
32
file round tripper*. Its main feature is that it is very easy to use, with a
37
33
straightforward programmer's interface and a simple syntax for config files.
38
34
It has lots of other features though :
39
 
    
 
35
 
40
36
* Nested sections (subsections), to any level
41
37
* List values
42
38
* Multiple line values
43
39
* String interpolation (substitution)
44
40
* Integrated with a powerful validation system
45
41
 
46
 
    - including automatic type checking/conversion
47
 
    - repeated sections
48
 
    - and allowing default values
49
 
 
50
 
* When writing out config files, ConfigObj preserves all comments and the order of members and sections
51
 
* Many useful methods and options for working with configuration files (like the 'reload' method)
52
 
* Full Unicode support
53
 
 
 
42
    * including automatic type checking/conversion
 
43
    * repeated sections
 
44
    * and allowing default values
 
45
 
 
46
* All comments in the file are preserved
 
47
* The order of keys/sections is preserved
 
48
* No external dependencies
 
49
 
 
50
ConfigObj 4 is a complete rewrite of ConfigObj. A great deal has been
 
51
simplified and improved [#]_ since ConfigObj 3. If you have used ConfigObj
 
52
before then you need to read the section on `backwards compatibility`_.
 
53
 
 
54
ConfigObj now has a barrage [#]_ of doctests built into it, testing almost every
 
55
feature. Run ``python configobj.py -v`` to see them in action. Despite the tests,
 
56
ConfigObj 4 is actually smaller than version 3 and has no external dependencies.
54
57
 
55
58
For support and bug reports please use the ConfigObj `Mailing List`_.
56
59
 
 
60
.. hint::
 
61
 
 
62
    There is an article on using `ConfigObj for Data Persistence`_.
 
63
    
 
64
    The code from that article is available as ConfigPersist.py_.
 
65
 
 
66
.. _ConfigObj for Data Persistence: http://www.voidspace.org.uk/python/articles/configobj_for_data_persistence.shtml
 
67
.. _ConfigPersist.py: http://www.voidspace.org.uk/python/configpersist.html
57
68
 
58
69
Downloading
59
70
===========
60
71
 
61
 
The current version is **4.5.2**, dated 24th February 2008. ConfigObj 4 is
62
 
now stable. We still expect to pick up a few bugs along the way though [#]_.
 
72
The current version is **4.0.0**, dated 17th October 2005. ConfigObj 4 is
 
73
now stable. We may still expect to pick up a few bugs along the way though [#]_.
63
74
{sm;:-)}
64
75
 
65
76
You can get ConfigObj in the following ways :
74
85
 
75
86
* configobj.zip_ from Voidspace
76
87
 
77
 
    This also contains validate.py_  and `this document`_.
 
88
    This also contains validate.py_ , the `API Docs`_ and `this document`_.
78
89
 
79
90
* The latest development version can be obtained from the `Subversion
80
91
  Repository`_.
86
97
Documentation
87
98
-------------
88
99
 
89
 
*configobj.zip* also contains `this document`_.
90
 
 
91
 
* You can view `this document`_ online at the `ConfigObj Homepage`_.
92
 
 
 
100
*configobj.zip* contains `this document`_ and full `API Docs`_, generated by
 
101
the EpyDoc_ program.
 
102
 
 
103
* You can view `this document`_ online as the `ConfigObj Homepage`_.
 
104
 
 
105
* You can also browse the `API Docs`_ online.
93
106
 
94
107
Pythonutils
95
108
-----------
98
111
various other useful modules, and is required by many of the `Voidspace Python
99
112
Projects`_.
100
113
 
101
 
 
102
 
Development Version
103
 
-------------------
104
 
 
105
 
It is sometimes possible to get the latest *development version* of ConfigObj
106
 
from the `Subversion Repository <http://svn.pythonutils.python-hosting.com/trunk/pythonutils/>`_.
107
 
 
108
114
.. _configobj.py: http://www.voidspace.org.uk/cgi-bin/voidspace/downman.py?file=configobj.py
109
 
.. _configobj.zip: http://www.voidspace.org.uk/cgi-bin/voidspace/downman.py?file=configobj-4.5.2.zip
 
115
.. _configobj.zip: http://www.voidspace.org.uk/cgi-bin/voidspace/downman.py?file=configobj-4.0.0.zip
110
116
.. _validate.py: http://www.voidspace.org.uk/cgi-bin/voidspace/downman.py?file=validate.py
 
117
.. _API Docs: http://www.voidspace.org.uk/python/configobj-api/
111
118
.. _this document:
112
119
.. _configobj homepage: http://www.voidspace.org.uk/python/configobj.html
 
120
.. _Subversion Repository: http://svn.rest2web.python-hosting.com/branches/configobj4
113
121
.. _Sourceforge: http://sourceforge.net/projects/configobj
 
122
.. _EpyDoc: http://epydoc.sourceforge.net
114
123
.. _pythonutils: http://www.voidspace.org.uk/python/pythonutils.html
115
 
.. _Voidspace Python Projects: http://www.voidspace.org.uk/python/index.shtml
116
 
 
117
 
 
118
 
 
119
 
ConfigObj in the Real World
120
 
===========================
121
 
    
122
 
**ConfigObj** is widely used. Projects using it include:
123
 
 
124
 
* `Bazaar <http://bazaar-ng.org>`_.
125
 
 
126
 
    Bazaar is a Python distributed {acro;VCS;Version Control System}.
127
 
    ConfigObj is used to read ``bazaar.conf`` and ``branches.conf``.
128
 
 
129
 
* `Turbogears <http://www.turbogears.org/>`_
130
 
 
131
 
    Turbogears is a web application framework.
132
 
 
133
 
* `Chandler <http://chandler.osafoundation.org/>`_
134
 
 
135
 
   A Python and `wxPython <http://www.wxpython.org>`_ 
136
 
   {acro;PIM;Personal Information Manager}, being developed by the 
137
 
   `OSAFoundation <http://www.osafoundation.org/>`_.
138
 
 
139
 
* `matplotlib <http://matplotlib.sourceforge.net/>`_
140
 
 
141
 
        A 2D plotting library.
142
 
 
143
 
* `IPython <http://ipython.scipy.org/moin/>`_
144
 
 
145
 
    IPython is an enhanced interactive Python shell. IPython uses ConfigObj in a module called 'TConfig' that combines it with enthought `Traits <http://code.enthought.com/traits/>`_: `tconfig <http://ipython.scipy.org/ipython/ipython/browser/ipython/branches/saw/sandbox/tconfig>`_.
146
 
    
147
 
* `Elisa - the Fluendo Mediacenter <http://elisa.fluendo.com/>`_    
148
 
    
149
 
    Elisa is an open source cross-platform media center solution designed to be simple for people not particularly familiar with computers.
150
 
 
 
124
.. _Voidspace Python Projects: http://www.voidspace.org.uk/python
151
125
 
152
126
Getting Started
153
127
===============
155
129
The outstanding feature of using ConfigObj is simplicity. Most functions can be
156
130
performed with single line commands.
157
131
 
158
 
 
159
132
Reading a Config File
160
133
---------------------
161
134
 
196
169
 
197
170
    {-coloring}
198
171
 
199
 
 
200
172
Writing a Config File
201
173
---------------------
202
174
 
246
218
    Keywords and section names can only be strings [#]_. Attempting to set
247
219
    anything else will raise a ``ValueError``.
248
220
 
249
 
 
250
221
Config Files
251
222
------------
252
223
 
296
267
    # The 'final_comment'
297
268
    # Which also may be several lines
298
269
 
299
 
 
300
270
ConfigObj specifications
301
271
========================
302
272
 
308
278
 
309
279
    {-coloring}
310
280
 
311
 
 
312
281
infile
313
282
------
314
283
 
322
291
  the options_ ``file_error`` and ``create_empty``. The filename will be
323
292
  preserved as the ``filename`` attribute. This can be changed at any time.
324
293
 
325
 
* A list of lines. Any trailing newlines will be removed from the lines. The
 
294
* A list of lines. Any trailing ``\n`` will be removed from the lines. The
326
295
  ``filename`` attribute of your ConfigObj will be ``None``.
327
296
 
328
 
* A ``StringIO`` instance or file object, or any object with a ``read`` method.
329
 
  The ``filename`` attribute of your ConfigObj will be ``None`` [#]_.
 
297
* A ``StringIO`` instance or file object, or any object with ``seek`` and
 
298
  ``read`` methods. The object you pass in will be preserved as the
 
299
  ``filename`` attribute of your ConfigObj. If it has a ``write`` method [#]_
 
300
  then you can use the ConfigObj ``write`` method. Note that a file object
 
301
  passed in won't have its ``close`` method called by ConfigObj.
330
302
 
331
303
* A dictionary. You can initialise a ConfigObj from a dictionary [#]_. The
332
304
  ``filename`` attribute of your ConfigObj will be ``None``. All keys must be
333
305
  strings. In this case, the order of values and sections is arbitrary.
334
306
 
335
 
 
336
307
options
337
308
-------
338
309
 
358
329
 
359
330
    If ``True`` (the default) then list values are possible. If ``False``, the
360
331
    values are not parsed for lists.
361
 
        
362
 
        If ``list_values = False`` then single line values are not quoted or
363
 
        unquoted when reading and writing.
364
332
 
365
 
    Changing this value affects whether single line values will be quoted or 
366
 
    not when writing.
 
333
    Altering this value after initial parsing has no effect.
367
334
 
368
335
* 'create_empty': ``False``
369
336
 
386
353
    default.
387
354
 
388
355
    You can set this attribute to change whether string interpolation is done
389
 
    when values are fetched. See the `String Interpolation`_ section for more details.
 
356
    when values are fetched. See the interpolation_ section for more details.
390
357
 
391
358
* 'configspec': ``None``
392
359
 
416
383
    non-string value [#]_ will raise a ``TypeError`` (no type conversion is
417
384
    done by validation).
418
385
 
419
 
* 'indent_type': ``'    '``
 
386
* 'indent_type': ``' '``
420
387
 
421
 
    Indentation is not significant; it can however be present in the input and
422
 
    output config. Any combination of tabs and spaces may be used: the string
423
 
    will be repeated for each level of indentation. Typical values are: ``''``
424
 
    (no indentation), ``'    '`` (indentation with four spaces, the default),
425
 
    ``'\t'`` (indentation with one tab).
 
388
    Indentation is not significant; it can however be present in the output
 
389
    config. Allowable values are: ``''`` (no indentation), ``' '`` (indentation
 
390
    with spaces, fixed at four per level), or ``'\t'`` (indentation with tabs,
 
391
    one tab per level).
426
392
 
427
393
    If this option is not specified, and the ConfigObj is initialised with a
428
394
    dictionary, the indentation used in the output is the default one, that is,
429
 
    four spaces.
 
395
    spaces.
430
396
 
431
397
    If this option is not specified, and the ConfigObj is initialised with a
432
398
    list of lines or a file, the indentation used in the first indented line is
436
402
    If this option *is* specified, the option value is used in the output
437
403
    config, overriding the type of indentation in the input config (if any).
438
404
 
439
 
* 'encoding': ``None``
440
 
 
441
 
    By default **ConfigObj** does not decode the file/strings you pass it into
442
 
    Unicode [#]_. If you want your config file as Unicode (keys and members)
443
 
    you need to provide an encoding to decode the file with. This encoding will
444
 
    also be used to encode the config file when writing.
445
 
    
446
 
    You can change the encoding attribute at any time.
447
 
    
448
 
    Any characters in your strings that can't be encoded with the specified
449
 
    encoding will raise a ``UnicodeEncodeError``.
450
 
    
451
 
    .. note::
452
 
    
453
 
        ``UTF16`` encoded files will automatically be detected and decoded,
454
 
        even if ``encoding`` is ``None``.
455
 
        
456
 
        This is because it is a 16-bit encoding, and ConfigObj will mangle it
457
 
        (split characters on byte boundaries) if it parses it without decoding.
458
 
 
459
 
* 'default_encoding': ``None``
460
 
 
461
 
    When using the ``write`` method, **ConfigObj** uses the ``encoding``
462
 
    attribute to encode the Unicode strings. If any members (or keys) have
463
 
    been set as byte strings instead of Unicode, these must first be decoded
464
 
    to Unicode before outputting in the specified encoding.
465
 
 
466
 
    ``default_encoding``, if specified, is the encoding used to decode byte
467
 
    strings in the **ConfigObj** before writing. If this is ``None``, then
468
 
    the Python default encoding (``sys.defaultencoding`` - usually ASCII) is
469
 
    used.
470
 
    
471
 
    For most Western European users, a value of ``latin-1`` is sensible.
472
 
    
473
 
    ``default_encoding`` is *only* used if an ``encoding`` is specified.
474
 
    
475
 
    Any characters in byte-strings that can't be decoded using the
476
 
    ``default_encoding`` will raise a ``UnicodeDecodeError``.
477
 
 
478
 
* 'unrepr': ``False``
479
 
 
480
 
    The ``unrepr`` option reads and writes files in a different mode. This
481
 
    allows you to store and retrieve the basic Python data-types using config
482
 
    files.
483
 
    
484
 
    This uses Python syntax for lists and quoting. See `unrepr mode`_ for the
485
 
    full details.
486
 
 
487
 
* 'write_empty_values': ``False`` 
488
 
 
489
 
    If ``write_empty_values`` is ``True``, empty strings are written as
490
 
    empty values. See `Empty Values`_ for more details.
491
 
 
492
 
 
493
405
Methods
494
406
-------
495
407
 
497
409
subclass of ``dict``, the builtin dictionary type. This means it also has
498
410
**all** the normal dictionary methods.
499
411
 
500
 
In addition, the following `Section Methods`_ may be useful :
501
 
 
502
 
* 'restore_default'
503
 
* 'restore_defaults'
504
 
* 'walk'
505
 
* 'merge'
506
 
* 'dict'
507
 
* 'as_bool'
508
 
* 'as_float'
509
 
* 'as_int'
510
 
 
511
 
Read about Sections_ for details of all the methods.
512
 
 
513
 
.. hint::
514
 
 
515
 
    The *merge* method of sections is a recursive update.
516
 
    
517
 
    You can use this to merge sections, or even whole ConfigObjs, into each
518
 
    other.
519
 
    
520
 
    You would typically use this to create a default ConfigObj and then merge
521
 
    in user settings. This way users only need to specify values that are
522
 
    different from the default. You can use configspecs and validation to
523
 
    achieve the same thing of course.
524
 
    
 
412
In addition, the *encode*, *decode*, *walk*, and *dict* methods of section may
 
413
be useful. The sections and subsections are also instances of ``Section``. Read
 
414
about Sections_ for details of all the methods.
525
415
 
526
416
The public methods available on ConfigObj are :
527
417
 
528
418
* 'write'
529
419
* 'validate'
530
 
* 'reset'
531
 
* 'reload'
532
 
 
533
420
 
534
421
write
535
422
~~~~~
536
423
 
537
 
::
538
 
 
539
 
    write(file_object=None)
540
 
 
541
 
This method writes the current ConfigObj and takes a single, optional argument
542
 
[#]_.
543
 
 
544
 
If you pass in a file like object to the ``write`` method, the config file will
545
 
be written to this. (The only method of this object that is used is its
546
 
``write`` method, so a ``StringIO`` instance, or any other file like object
547
 
will work.)
548
 
 
549
 
Otherwise, the behaviour of this method depends on the ``filename`` attribute
550
 
of the ConfigObj.
551
 
 
552
 
``filename``
553
 
    ConfigObj will write the configuration to the file specified.
 
424
This method takes no arguments [#]_. It writes the current ConfigObj. What that
 
425
means depends on the ``filename`` attribute of the ConfigObj.
 
426
 
 
427
filename
 
428
    ConfigObj will write the configuration to file.
554
429
 
555
430
``None``
556
431
    ``write`` returns a list of lines. (Not ``'\n'`` terminated)
557
432
 
 
433
``StringIO``
 
434
    If ``filename`` is an object with a seek attribute, then the config file is
 
435
    written to that object.
 
436
 
558
437
First the 'initial_comment' is written, then the config file, followed by the
559
438
'final_comment'. Comment lines and inline comments are written with each
560
439
key/value.
561
440
 
562
 
 
563
441
validate
564
442
~~~~~~~~
565
443
 
566
 
::
567
 
 
568
 
    validate(validator, preserve_errors=False, copy=False)
569
 
 
570
444
.. raw:: html
571
445
 
572
446
    {+coloring}
581
455
    test = config.validate(val)
582
456
    if test == True:
583
457
        print 'Succeeded.'
 
458
 
584
459
    {-coloring}
585
460
 
586
 
The validate method uses the `validate 
587
 
<http://www.voidspace.org.uk/python/validate.html>`__ module to do the
588
 
validation.
589
 
    
590
461
This method validates the ConfigObj against the configspec. By doing type
591
 
conversion as well it can abstract away the config file altogether and present
 
462
conversion as well, it can abstract away the config file altogether and present
592
463
the config *data* to your application (in the types it expects it to be).
593
464
 
594
465
If the ``configspec`` attribute of the ConfigObj is ``None``, it raises a
606
477
 
607
478
.. hint::
608
479
 
609
 
    The system of configspecs can seem confusing at first, but is actually
610
 
    quite simple and powerful. For a concrete example of how to use it, you may
611
 
    find this blog entry helpful :
612
 
    `Transforming Values with ConfigObj <http://www.voidspace.org.uk/python/weblog/arch_d7_2006_03_04.shtml#e257>`_.
613
 
 
614
 
 
615
 
The ``copy`` parameter fills in missing values from the configspec (default
616
 
values), *without* marking the values as defaults. It also causes comments to
617
 
be copied from the configspec into the config file. This allows you to use a
618
 
configspec to create default config files. (Normally default values aren't
619
 
written out by the ``write`` method.)
620
 
 
621
 
As of ConfigObj 4.3.0 you can also pass in a ConfigObj instance as your
622
 
configspec. This is especially useful if you need to specify the encoding of
623
 
your configspec file. When you read your configspec file, you *must* specify
624
 
``list_values=False``.
625
 
 
626
 
.. raw:: html
627
 
 
628
 
    {+coloring}
629
 
    from configobj import ConfigObj
630
 
    configspec = ConfigObj(configspecfilename, encoding='UTF8',
631
 
                           list_values=False)
632
 
    config = ConfigObj(filename, configspec=configspec)
633
 
    {-coloring}
 
480
    If your ConfigObj is only comprised of basic data types, then you can use
 
481
    a function from the ConfigPersist.py_ module to auto-generate your
 
482
    configspec.
634
483
    
 
484
    See `ConfigObj for Data Persistence`_.
635
485
 
636
486
Return Value
637
487
############
638
488
 
639
 
By default, the validate method either returns ``True`` (everything passed) 
640
 
or a dictionary of ``True``/``False`` representing pass/fail. The dictionary 
641
 
follows the structure of the ConfigObj.
 
489
The validate method either returns ``True`` (everything passed) or a dictionary 
 
490
of ``True``/``False`` representing pass/fail. The dictionary follows the 
 
491
structure of the ConfigObj
642
492
 
643
493
If a whole section passes then it is replaced with the value ``True``. If a 
644
494
whole section fails, then it is replaced with the value ``False``.
646
496
If a value is missing, and there is no default in the check, then the check 
647
497
automatically fails.
648
498
 
649
 
The ``validate`` method takes an optional keyword argument ``preserve_errors``.
650
 
If you set this to ``True``, instead of getting ``False`` for failed checks you
651
 
get the actual error object from the **validate** module. This usually contains
652
 
useful information about why the check failed.
653
 
 
654
 
See the `flatten_errors`_ function for how to turn your results dictionary into
655
 
a useful list of error messages.
656
 
 
657
 
Even if ``preserve_errors`` is ``True``, missing keys or sections will still be
658
 
represented by a ``False`` in the results dictionary.
659
 
 
660
 
 
661
499
Mentioning Default Values
662
500
#########################
663
501
 
698
536
    ``None``. This is because setting a value to a non-string raises an error
699
537
    if stringify is unset.
700
538
 
701
 
The default value can be a list. See `List Values`_ for the way to do this.
702
 
 
703
 
Writing invalid default values is a *guaranteed* way of confusing your users.
704
 
Default values **must** pass the check.
705
 
 
706
 
 
707
539
Mentioning Repeated Sections
708
540
############################
709
541
 
722
554
 
723
555
See `Repeated Sections`_ for examples.
724
556
 
725
 
 
726
557
Mentioning SimpleVal
727
558
####################
728
559
 
744
575
 
745
576
    {-coloring}
746
577
 
747
 
 
748
 
Mentioning copy Mode
749
 
####################
750
 
 
751
 
As discussed in `Mentioning Default Values`_, you can use a configspec to
752
 
supply default values. These are marked in the ConfigObj instance as defaults,
753
 
and *not* written out by the ``write`` mode. This means that your users only
754
 
need to supply values that are different from the defaults.
755
 
 
756
 
This can be inconvenient if you *do* want to write out the default values,
757
 
for example to write out a default config file.
758
 
 
759
 
If you set ``copy=True`` when you call validate, then no values are marked as
760
 
defaults. In addition, all comments from the configspec are copied into
761
 
your ConfigObj instance. You can then call ``write`` to create your config
762
 
file.
763
 
    
764
 
There is a limitation with this. In order to allow `String Interpolation`_ to work
765
 
within configspecs, ``DEFAULT`` sections are not processed by
766
 
validation; even in copy mode.
767
 
 
768
 
 
769
 
reload
770
 
~~~~~~
771
 
 
772
 
If a ConfigObj instance was loaded from the filesystem, then this method will reload it. It
773
 
will also reuse any configspec you supplied at instantiation (including reloading it from
774
 
the filesystem if you passed it in as a filename).
775
 
 
776
 
If the ConfigObj does not have a filename attribute pointing to a file, then a ``ReloadError`` 
777
 
will be raised.
778
 
 
779
 
 
780
 
reset
781
 
~~~~~
782
 
 
783
 
This method takes no arguments and doesn't return anything. It restores a ConfigObj
784
 
instance to a freshly created state.
785
 
 
786
 
 
787
578
Attributes
788
579
----------
789
580
 
795
586
* BOM
796
587
* initial_comment
797
588
* final_comment
798
 
* list_values
799
 
* encoding
800
 
* default_encoding
801
 
* unrepr
802
 
* write_empty_values
803
 
* newlines
804
589
 
805
590
.. note::
806
591
 
813
598
* raise_errors
814
599
* create_empty
815
600
* file_error
816
 
 
817
 
 
818
 
interpolation
819
 
~~~~~~~~~~~~~
 
601
* list_values
 
602
 
 
603
interpolate
 
604
~~~~~~~~~~~
820
605
 
821
606
ConfigObj can perform string interpolation in a *similar* way to
822
 
``ConfigParser``. See the `String Interpolation`_ section for full details.
 
607
``ConfigParser``. See the interpolation_ section for full details.
823
608
 
824
 
If ``interpolation`` is set to ``False``, then interpolation is *not* done when
 
609
If ``interpolate`` is set to ``False``, then interpolation is *not* done when
825
610
you fetch values.
826
611
 
827
 
 
828
612
stringify
829
613
~~~~~~~~~
830
614
 
835
619
If stringify is unset (``False``) then attempting to set a value to a non
836
620
string (or a list of strings) will raise a ``TypeError``.
837
621
 
838
 
 
839
622
BOM
840
623
~~~
841
624
 
842
625
If the initial config file *started* with the UTF8 Unicode signature (known
843
 
slightly incorrectly as the {acro;BOM;Byte Order Mark}), or the UTF16 BOM, then
844
 
this attribute is set to ``True``. Otherwise it is ``False``.
845
 
 
846
 
If it is set to ``True`` when ``write`` is called then, if ``encoding`` is set
847
 
to ``None`` *or* to ``utf_8`` (and variants) a UTF BOM will be written.
848
 
 
849
 
For UTF16 encodings, a BOM is *always* written.
850
 
 
 
626
slightly incorrectly as the {acro;BOM;Byte Order Mark}), then this value will
 
627
be set to the UTF8 BOM. Otherwise it is ``None``.
 
628
 
 
629
If it is set, then it is  written out by the ``write`` method.
851
630
 
852
631
initial_comment
853
632
~~~~~~~~~~~~~~~
859
638
 
860
639
The write method puts these lines before it starts writing out the members.
861
640
 
862
 
 
863
641
final_comment
864
642
~~~~~~~~~~~~~
865
643
 
871
649
The ``write`` method puts these lines after it finishes writing out the
872
650
members.
873
651
 
874
 
 
875
 
list_values
876
 
~~~~~~~~~~~
877
 
 
878
 
This attribute is ``True`` or ``False``. If set to ``False`` then values are
879
 
not parsed for list values. In addition single line values are not unquoted.
880
 
 
881
 
This allows you to do your own parsing of values. It exists primarily to
882
 
support the reading of the configspec_ - but has other use cases.
883
 
 
884
 
For example you could use the ``LineParser`` from the
885
 
`listquote module <http://www.voidspace.org.uk/python/listquote.html#lineparser>`_ 
886
 
to read values for nested lists.
887
 
 
888
 
Single line values aren't quoted when writing - but multiline values are
889
 
handled as normal.
890
 
 
891
 
.. caution::
892
 
 
893
 
    Because values aren't quoted, leading or trailing whitespace can be
894
 
        lost.
895
 
 
896
 
    This behaviour was changed in version 4.0.1.
897
 
        
898
 
        Prior to this, single line values might have been quoted; even with
899
 
        ``list_values=False``. This means that files written by **ConfigObj**
900
 
        *could* now be incompatible - and need the quotes removing by hand.
901
 
 
902
 
 
903
 
encoding
904
 
~~~~~~~~
905
 
 
906
 
This is the encoding used to encode the output, when you call ``write``. It
907
 
must be a valid encoding `recognised by Python <http://docs.python.org/lib/standard-encodings.html>`_.
908
 
 
909
 
If this value is ``None`` then no encoding is done when ``write`` is called.
910
 
 
911
 
 
912
 
default_encoding
913
 
~~~~~~~~~~~~~~~~
914
 
 
915
 
If encoding is set, any byte-strings in your ConfigObj instance (keys or
916
 
members) will first be decoded to Unicode using the encoding specified by the
917
 
``default_encoding`` attribute. This ensures that the output is in the encoding
918
 
specified.
919
 
 
920
 
If this value is ``None`` then ``sys.defaultencoding`` is used instead.
921
 
 
922
 
 
923
 
unrepr
924
 
~~~~~~
925
 
 
926
 
Another boolean value. If this is set, then ``repr(value)`` is used to write
927
 
values. This writes values in a slightly different way to the normal ConfigObj
928
 
file syntax.
929
 
 
930
 
This preserves basic Python data-types when read back in. See `unrepr mode`_
931
 
for more details.
932
 
 
933
 
 
934
 
write_empty_values
935
 
~~~~~~~~~~~~~~~~~~
936
 
 
937
 
Also boolean. If set, values that are an empty string (``''``) are written as
938
 
empty values. See `Empty Values`_ for more details.
939
 
 
940
 
 
941
 
newlines
942
 
~~~~~~~~
943
 
 
944
 
When a config file is read, ConfigObj records the type of newline separators in the
945
 
file and uses this separator when writing. It defaults to ``None``, and ConfigObj
946
 
uses the system default (``os.sep``) if write is called without newlines having
947
 
been set.
948
 
 
949
 
 
950
652
The Config File Format
951
653
======================
952
654
 
1063
765
 
1064
766
    {+coloring}
1065
767
 
1066
 
    ConfigObj({
 
768
    {
1067
769
        'keyword1': 'value1',
1068
770
        'keyword2': 'value2',
1069
771
        'section 1': {
1086
788
                'keyword2': 'value2',
1087
789
            },
1088
790
        },
1089
 
    })
 
791
    }
1090
792
 
1091
793
    {-coloring}
1092
794
 
1093
795
Sections are ordered: note how the structure of the resulting ConfigObj is in
1094
796
the same order as the original file.
1095
797
 
1096
 
.. note::
1097
 
 
1098
 
    In ConfigObj 4.3.0 *empty values* became valid syntax. They are read as the
1099
 
    empty string. There is also an option/attribute (``write_empty_values``) to
1100
 
    allow the writing of these.
1101
 
    
1102
 
    This is mainly to support 'legacy' config files, written from other
1103
 
    applications. This is documented under `Empty Values`_.
1104
 
    
1105
 
    `unrepr mode`_ introduces *another* syntax variation, used for storing
1106
 
    basic Python datatypes in config files. {sm;:-)}
1107
 
 
1108
 
 
1109
798
Sections
1110
799
========
1111
800
 
1171
860
 
1172
861
* 'values'
1173
862
 
1174
 
 
1175
863
Section Attributes
1176
864
------------------
1177
865
 
1201
889
    Setting any of these values in the section removes them from the defaults
1202
890
    list.
1203
891
 
1204
 
* default_values
1205
 
 
1206
 
    This attribute is a dictionary mapping keys to the default values for the
1207
 
    keys. By default it is an empty dictionary and is populated when you
1208
 
    validate the ConfigObj.
1209
 
 
1210
892
* scalars, sections
1211
893
 
1212
894
    These attributes are normal lists, representing the order that members,
1258
940
 
1259
941
    See the validation_ section for full details of how to write configspecs.
1260
942
 
1261
 
 
1262
943
Section Methods
1263
944
---------------
1264
945
 
1265
 
* **dict**
 
946
* 'dict'
1266
947
 
1267
948
    This method takes no arguments. It returns a deep copy of the section as a
1268
949
    dictionary. All subsections will also be dictionaries, and list values will
1269
950
    be copies, rather than references to the original [#]_.
1270
951
 
1271
 
* **rename**
 
952
* rename
1272
953
 
1273
954
    ``rename(oldkey, newkey)``
1274
955
 
1277
958
    It is mainly implemented for the ``encode`` and ``decode`` methods, which
1278
959
    provide some Unicode support.
1279
960
 
1280
 
* **merge**
1281
 
 
1282
 
    ``merge(indict)``
1283
 
    
1284
 
    This method is a *recursive update* method. It allows you to merge two
1285
 
    config files together.
1286
 
    
1287
 
    You would typically use this to create a default ConfigObj and then merge
1288
 
    in user settings. This way users only need to specify values that are
1289
 
    different from the default.
1290
 
    
1291
 
    For example :
1292
 
    
1293
 
    .. raw:: html
1294
 
    
1295
 
        {+coloring}
1296
 
        
1297
 
        # def_cfg contains your default config settings
1298
 
        # user_cfg contains the user settings
1299
 
        cfg = ConfigObj(def_cfg)
1300
 
        usr = ConfigObj(user_cfg)
1301
 
        #
1302
 
        cfg.merge(usr)
1303
 
        
1304
 
        """
1305
 
        cfg now contains a combination of the default settings and the user
1306
 
        settings.
1307
 
        
1308
 
        The user settings will have overwritten any of the default ones.
1309
 
        """
1310
 
    
1311
 
        {-coloring}
1312
 
    
1313
 
* **walk**
 
961
* walk
1314
962
 
1315
963
    This method can be used to transform values and names. See `walking a
1316
964
    section`_ for examples and explanation.
1317
965
 
1318
 
* **decode**
 
966
* decode
1319
967
 
1320
968
    ``decode(encoding)``
1321
969
 
1322
970
    This method decodes names and values into Unicode objects, using the
1323
971
    supplied encoding.
1324
972
 
1325
 
* **encode**
 
973
    Because of the way ConfigObj reads files, config files should be in an
 
974
    ASCII compatible encoding. See encodings_ for more details.
 
975
 
 
976
* encode
1326
977
 
1327
978
    ``encode(encoding)``
1328
979
 
1330
981
 
1331
982
    It encodes names and values using the supplied encoding. If any of your
1332
983
    names/values are strings rather than Unicode, Python will have to do an
1333
 
    implicit decode first. (This method uses ``sys.defaultencoding`` for
1334
 
    implicit decodes.)
1335
 
 
1336
 
* **as_bool**
1337
 
 
1338
 
    ``as_bool(key)``
1339
 
    
1340
 
    Returns ``True`` if the key contains a string that represents ``True``, or
1341
 
    is the ``True`` object.
1342
 
    
1343
 
    Returns ``False`` if the key contains a string that represents ``False``, 
1344
 
    or is the ``False`` object. 
1345
 
 
1346
 
    Raises a ``ValueError`` if the key contains anything else.
1347
 
    
1348
 
    Strings that represent ``True`` are (not case sensitive) : ::
1349
 
    
1350
 
        true, yes, on, 1
1351
 
        
1352
 
    Strings that represent ``False`` are : ::
1353
 
    
1354
 
        false, no, off, 0
1355
 
    
1356
 
    .. note::
1357
 
    
1358
 
        In ConfigObj 4.1.0, this method was called ``istrue``. That method is
1359
 
        now deprecated and will issue a warning when used. It will go away
1360
 
        in a future release.
1361
 
        
1362
 
* **as_int**
1363
 
 
1364
 
    ``as_int(key)``
1365
 
    
1366
 
    This returns the value contained in the specified key as an integer.
1367
 
    
1368
 
    It raises a ``ValueError`` if the conversion can't be done.
1369
 
 
1370
 
* **as_float**
1371
 
 
1372
 
    ``as_float(key)``
1373
 
    
1374
 
    This returns the value contained in the specified key as a float.
1375
 
    
1376
 
    It raises a ``ValueError`` if the conversion can't be done.
1377
 
    
1378
 
* **restore_default**
1379
 
 
1380
 
    ``restore_default(key)``
1381
 
    
1382
 
    Restore (and return) the default value for the specified key.
1383
 
    
1384
 
    This method will only work for a ConfigObj that was created
1385
 
    with a configspec and has been validated.
1386
 
    
1387
 
    If there is no default value for this key, ``KeyError`` is raised.
1388
 
 
1389
 
* **restore_defaults**
1390
 
    
1391
 
    ``restore_defaults()``
1392
 
 
1393
 
    Recursively restore default values to all members
1394
 
    that have them.
1395
 
    
1396
 
    This method will only work for a ConfigObj that was created
1397
 
    with a configspec and has been validated.
1398
 
    
1399
 
    It doesn't delete or modify entries without default values.
1400
 
 
 
984
    implicit decode first.
 
985
 
 
986
    See encodings_ for more details.
1401
987
 
1402
988
Walking a Section
1403
989
-----------------
1442
1028
If you are using the return value from ``walk`` *and* ``call_on_sections``,
1443
1029
note that walk discards the return value when it calls your function.
1444
1030
 
1445
 
.. caution::
1446
 
 
1447
 
    You can use ``walk`` to transform the names of members of a section
1448
 
    but you mustn't add or delete members.
1449
 
 
1450
 
 
1451
1031
Examples
1452
1032
--------
1453
1033
 
1460
1040
 
1461
1041
You can use this for transforming all values in your ConfigObj. For example
1462
1042
you might like the nested lists from ConfigObj 3. This was provided by the
1463
 
listquote_ module. You could switch off the parsing for list values
 
1043
listquote_ module [#]_. You could switch off the parsing for list values
1464
1044
(``list_values=False``) and use listquote to parse every value.
1465
1045
 
1466
1046
Another thing you might want to do is use the Python escape codes in your
1536
1116
 
1537
1117
    {-coloring}
1538
1118
 
1539
 
Here's a simple example of using ``walk`` to transform names and values. One
1540
 
usecase of this would be to create a *standard* config file with placeholders
1541
 
for section and keynames. You can then use walk to create new config files
1542
 
and change values and member names :
1543
 
 
1544
 
.. raw:: html
1545
 
 
1546
 
    {+coloring}
1547
 
 
1548
 
    # We use 'XXXX' as a placeholder
1549
 
    config = '''
1550
 
    XXXXkey1 = XXXXvalue1
1551
 
    XXXXkey2 = XXXXvalue2
1552
 
    XXXXkey3 = XXXXvalue3
1553
 
    [XXXXsection1]
1554
 
    XXXXkey1 = XXXXvalue1
1555
 
    XXXXkey2 = XXXXvalue2
1556
 
    XXXXkey3 = XXXXvalue3
1557
 
    [XXXXsection2]
1558
 
    XXXXkey1 = XXXXvalue1
1559
 
    XXXXkey2 = XXXXvalue2
1560
 
    XXXXkey3 = XXXXvalue3
1561
 
        [[XXXXsection1]]
1562
 
        XXXXkey1 = XXXXvalue1
1563
 
        XXXXkey2 = XXXXvalue2
1564
 
        XXXXkey3 = XXXXvalue3
1565
 
    '''.splitlines()
1566
 
    cfg = ConfigObj(config)
1567
 
    #
1568
 
    def transform(section, key):
1569
 
        val = section[key]
1570
 
        newkey = key.replace('XXXX', 'CLIENT1')
1571
 
        section.rename(key, newkey)
1572
 
        if isinstance(val, (tuple, list, dict)):
1573
 
            pass
1574
 
        else:
1575
 
            val = val.replace('XXXX', 'CLIENT1')
1576
 
            section[newkey] = val
1577
 
    #
1578
 
    cfg.walk(transform, call_on_sections=True)
1579
 
    print cfg
1580
 
    ConfigObj({'CLIENT1key1': 'CLIENT1value1', 'CLIENT1key2': 'CLIENT1value2', 
1581
 
    'CLIENT1key3': 'CLIENT1value3', 
1582
 
    'CLIENT1section1': {'CLIENT1key1': 'CLIENT1value1', 
1583
 
        'CLIENT1key2': 'CLIENT1value2', 'CLIENT1key3': 'CLIENT1value3'}, 
1584
 
    'CLIENT1section2': {'CLIENT1key1': 'CLIENT1value1', 
1585
 
        'CLIENT1key2': 'CLIENT1value2', 'CLIENT1key3': 'CLIENT1value3', 
1586
 
        'CLIENT1section1': {'CLIENT1key1': 'CLIENT1value1', 
1587
 
            'CLIENT1key2': 'CLIENT1value2', 'CLIENT1key3': 'CLIENT1value3'}}})
1588
 
            
1589
 
    {-coloring}
1590
 
 
1591
 
 
1592
1119
Exceptions
1593
1120
==========
1594
1121
 
1600
1127
    raised.
1601
1128
 
1602
1129
2) If you try to set a non-string key, or a non string value when
1603
 
    ``stringify=False``, a ``TypeError`` will be raised.
 
1130
    ``stringify=False`, a ``TypeError`` will be raised.
1604
1131
 
1605
1132
3) A badly built config file will cause parsing errors.
1606
1133
 
1613
1140
    (in a configspec), a ``RepeatSectionError`` will be raised.
1614
1141
 
1615
1142
Number 5 (which is actually two different types of exceptions) is documented
1616
 
    in `String Interpolation`_.
 
1143
    in interpolation_.
1617
1144
 
1618
1145
Number 6 is explained in the validation_ section.
1619
1146
 
1642
1169
 
1643
1170
* ``ConfigspecError``
1644
1171
 
1645
 
    An error occurred whilst parsing a configspec.
1646
 
 
1647
 
* ``UnreprError``
1648
 
 
1649
 
    An error occurred when parsing a value in `unrepr mode`_.
1650
 
    
1651
 
* ``ReloadError``
1652
 
 
1653
 
    ``reload`` was called on a ConfigObj instance that doesn't have a valid 
1654
 
    filename attribute.
 
1172
    An error occured whilst parsing a configspec.
1655
1173
 
1656
1174
When parsing a configspec, ConfigObj will stop on the first error it
1657
1175
encounters.  It will raise a ``ConfigspecError``. This will have an ``error``
1658
1176
attribute, which is the actual error that was raised.
1659
1177
 
1660
 
Behaviour when parsing a config file depends on the option ``raise_errors``.
 
1178
Behavior when parsing a config file depends on the option ``raise_errors``.
1661
1179
If ConfigObj encounters an error while parsing a config file:
1662
1180
 
1663
1181
    If ``raise_errors=True`` then ConfigObj will raise the appropriate error
1666
1184
    If ``raise_errors=False`` (the default) then parsing will continue to the
1667
1185
    end and *all* errors will be collected.
1668
1186
 
1669
 
If ``raise_errors`` is False and multiple errors are found a ``ConfigObjError``
1670
 
is raised. The error raised has a ``config`` attribute, which is the parts of
1671
 
the ConfigObj that parsed successfully. It also has an attribute ``errors``,
1672
 
which is a list of *all* the errors raised. Each entry in the list is an
1673
 
instance of the appropriate error type. Each one has the following attributes
1674
 
(useful for delivering a sensible error message to your user) :
 
1187
In the second case a ``ConfigObjError`` is raised after parsing has stopped.
 
1188
The error raised has a ``config`` attribute, which is the parts of the
 
1189
ConfigObj that parsed successfully. It also has an attribute ``errors``, which
 
1190
is a list of *all* the errors raised. Each entry in the list is an instance of
 
1191
the appropriate error type. Each one has the following attributes (useful for
 
1192
delivering a sensible error message to your user) :
1675
1193
 
1676
1194
* ``line``: the original line that caused the error.
1677
1195
 
1679
1197
 
1680
1198
* ``message``: the error message that accompanied the error.
1681
1199
 
1682
 
If only one error is found, then that error is re-raised. The error still has
1683
 
the ``config`` and ``errors`` attributes. This means that your error handling
1684
 
code can be the same whether one error is raised in parsing , or several.
1685
 
 
1686
 
It also means that in the most common case (a single error) a useful error
1687
 
message will be raised.
1688
 
 
1689
1200
.. note::
1690
1201
 
1691
1202
    One wrongly written line could break the basic structure of your config
1693
1204
    list of all the lines that caused errors may not be as useful as it sounds.
1694
1205
    {sm;:-(}.
1695
1206
 
1696
 
 
1697
1207
Validation
1698
1208
==========
1699
1209
 
1700
 
.. hint::
1701
 
 
1702
 
    The system of configspecs can seem confusing at first, but is actually
1703
 
    quite simple and powerful. For a concrete example of how to use it, you may
1704
 
    find this blog entry helpful :
1705
 
    `Transforming Values with ConfigObj <http://www.voidspace.org.uk/python/weblog/arch_d7_2006_03_04.shtml#e257>`_.
1706
 
 
1707
1210
Validation is done through a combination of the configspec_ and a ``Validator``
1708
1211
object. For this you need *validate.py* [#]_. See downloading_ if you don't
1709
1212
have a copy.
1722
1225
application configuration (boolean, integers, floats, etc) and the text format
1723
1226
of your config file.
1724
1227
 
1725
 
 
1726
1228
configspec
1727
1229
----------
1728
1230
 
1760
1262
For full details on writing configspecs, please refer to the `validate.py
1761
1263
documentation`_.
1762
1264
 
1763
 
.. important::
1764
 
 
1765
 
    Your configspec is read by ConfigObj in the same way as a config file.
1766
 
    
1767
 
    That means you can do interpolation *within* your configspec.
1768
 
    
1769
 
    In order to allow this, checks in the 'DEFAULT' section (of the root level
1770
 
    of your configspec) are *not* used.
1771
 
 
1772
 
If you need to specify the encoding of your configspec, then you can pass in a
1773
 
ConfigObj instance as your configspec. When you read your configspec file, you
1774
 
*must* specify ``list_values=False``.
1775
 
 
1776
 
.. raw:: html
1777
 
 
1778
 
    {+coloring}
1779
 
    from configobj import ConfigObj
1780
 
    configspec = ConfigObj(configspecfilename, encoding='UTF8',
1781
 
        list_values=False)
1782
 
    config = ConfigObj(filename, configspec=configspec)
1783
 
    {-coloring}
1784
 
 
1785
1265
.. _validate.py documentation: http://www.voidspace.org.uk/python/validate.html
1786
1266
 
1787
 
 
1788
1267
Type Conversion
1789
1268
---------------
1790
1269
 
1799
1278
set the stringify_ attribute to ``False``. If this is the case, attempting to
1800
1279
set a value to a non-string will raise an error.
1801
1280
 
1802
 
 
1803
1281
Default Values
1804
1282
--------------
1805
1283
 
1827
1305
 
1828
1306
    Note that ``default=None`` is case sensitive.
1829
1307
 
1830
 
 
1831
 
List Values
1832
 
~~~~~~~~~~~
1833
 
 
1834
 
It's possible that you will want to specify a list as a default value. To avoid
1835
 
confusing syntax with commas and quotes you use a list constructor to specify 
1836
 
that keyword arguments are lists. This includes the ``default`` value. This 
1837
 
makes checks look something like : ::
1838
 
 
1839
 
    checkname(default=list('val1', 'val2', 'val3'))
1840
 
 
1841
 
This works with all keyword arguments, but is most useful for default values.
1842
 
 
1843
 
 
1844
1308
Repeated Sections
1845
1309
-----------------
1846
1310
 
1877
1341
sub-sections. Defaults work in the normal way in repeated sections.
1878
1342
 
1879
1343
 
1880
 
Copy Mode
1881
 
---------
1882
 
 
1883
 
Because you can specify default values in your configspec, you can use
1884
 
ConfigObj to write out default config files for your application.
1885
 
 
1886
 
However, normally values supplied from a default in a configspec are *not*
1887
 
written out by the ``write`` method.
1888
 
 
1889
 
To do this, you need to specify ``copy=True`` when you call validate. As well
1890
 
as not marking values as default, all the comments in the configspec file
1891
 
will be copied into your ConfigObj instance.
1892
 
 
1893
 
.. raw:: html
1894
 
 
1895
 
    {+coloring}
1896
 
    from configobj import ConfigObj
1897
 
    from validate import Validator
1898
 
    vdt = Validator()
1899
 
    config = ConfigObj(configspec='default.ini')
1900
 
    config.filename = 'new_default.ini'
1901
 
    config.validate(vdt, copy=True)
1902
 
    config.write()
1903
 
    {-coloring}
1904
 
 
1905
 
 
1906
1344
Validation and Interpolation
1907
1345
----------------------------
1908
1346
 
1916
1354
overwritten. If validation changes type - the value has to be overwritten, and
1917
1355
any interpolation references are lost {sm;:-(}.
1918
1356
 
1919
 
 
1920
1357
SimpleVal
1921
1358
---------
1922
1359
 
1967
1404
 
1968
1405
    {-coloring}
1969
1406
 
1970
 
 
1971
 
Empty values
1972
 
============
1973
 
 
1974
 
Many config files from other applications allow empty values. As of version
1975
 
4.3.0, ConfigObj will read these as an empty string.
1976
 
 
1977
 
A new option/attribute has been added (``write_empty_values``) to allow
1978
 
ConfigObj to write empty strings as empty values.
1979
 
 
1980
 
.. raw:: html
1981
 
 
1982
 
    {+coloring}
1983
 
    from configobj import ConfigObj
1984
 
    cfg = '''
1985
 
        key =
1986
 
        key2 = # a comment
1987
 
    '''.splitlines()
1988
 
    config = ConfigObj(cfg)
1989
 
    print config
1990
 
    ConfigObj({'key': '', 'key2': ''})
1991
 
    
1992
 
    config.write_empty_values = True
1993
 
    for line in config.write():
1994
 
        print line
1995
 
    
1996
 
    key = 
1997
 
    key2 =     # a comment
1998
 
    {-coloring}
1999
 
 
2000
 
 
2001
 
unrepr mode
2002
 
===========
2003
 
 
2004
 
The ``unrepr`` option allows you to store and retrieve the basic Python
2005
 
data-types using config files. It has to use a slightly different syntax to
2006
 
normal ConfigObj files. Unsurprisingly it uses Python syntax.
2007
 
 
2008
 
This means that lists are different (they are surrounded by square brackets),
2009
 
and strings *must* be quoted.
2010
 
 
2011
 
The types that ``unrepr`` can work with are :
2012
 
 
2013
 
    | strings, lists tuples
2014
 
    | None, True, False
2015
 
    | dictionaries, integers, floats
2016
 
    | longs and complex numbers
2017
 
    
2018
 
You can't store classes, types or instances.
2019
 
 
2020
 
``unrepr`` uses ``repr(object)`` to write out values, so it currently *doesn't*
2021
 
check that you are writing valid objects. If you attempt to read an unsupported
2022
 
value, ConfigObj will raise a ``configobj.UnknownType`` exception.
2023
 
 
2024
 
Values that are triple quoted cased. The triple quotes are removed *before*
2025
 
converting. This means that you can use triple quotes to write dictionaries
2026
 
over several lines in your config files. They won't be written like this
2027
 
though.
2028
 
 
2029
 
If you are writing config files by hand, for use with ``unrepr``, you should
2030
 
be aware of the following differences from normal ConfigObj syntax :
2031
 
 
2032
 
    | List : ``['A List', 'With', 'Strings']``
2033
 
    | Strings : ``"Must be quoted."``
2034
 
    | Backslash : ``"The backslash must be escaped \\"``
2035
 
 
2036
 
These all follow normal Python syntax.
2037
 
 
2038
 
In unrepr mode *inline comments* are not saved. This is because lines are
2039
 
parsed using the `compiler package <http://docs.python.org/lib/compiler.html>`_
2040
 
which discards comments.
2041
 
 
2042
 
 
2043
 
String Interpolation
2044
 
====================
 
1407
Interpolation
 
1408
=============
2045
1409
 
2046
1410
ConfigObj allows string interpolation *similar* to the way ``ConfigParser``
2047
 
or ``string.Template`` work. The value of the ``interpolation`` attribute
2048
 
determines which style of interpolation you want to use. Valid values are
2049
 
"ConfigParser" or "Template" (case-insensitive, so "configparser" and
2050
 
"template" will also work). For backwards compatibility reasons, the value
2051
 
``True`` is also a valid value for the ``interpolation`` attribute, and
2052
 
will select ``ConfigParser``-style interpolation. At some undetermined point
2053
 
in the future, that default *may* change to ``Template``-style interpolation.
2054
 
 
2055
 
For ``ConfigParser``-style interpolation, you specify a value to be
2056
 
substituted by including ``%(name)s`` in the value.
2057
 
 
2058
 
For ``Template``-style interpolation, you specify a value to be substituted
2059
 
by including ``${cl}name{cr}`` in the value. Alternately, if 'name' is a valid
2060
 
Python identifier (i.e., is composed of nothing but alphanumeric characters,
2061
 
plus the underscore character), then the braces are optional and the value
2062
 
can be written as ``$name``.
2063
 
 
2064
 
Note that ``ConfigParser``-style interpolation and ``Template``-style
2065
 
interpolation are mutually exclusive; you cannot have a configuration file
2066
 
that's a mix of one or the other. Pick one and stick to it. ``Template``-style
2067
 
interpolation is simpler to read and write by hand, and is recommended if
2068
 
you don't have a particular reason to use ``ConfigParser``-style.
2069
 
 
2070
 
Interpolation checks first the current section to see if ``name`` is the key
2071
 
to a value. ('name' is case sensitive).
2072
 
 
2073
 
If it doesn't find it, next it checks the 'DEFAULT' sub-section of the current
2074
 
section.
2075
 
 
2076
 
If it still doesn't find it, it moves on to check the parent section and the
2077
 
parent section's 'DEFAULT' subsection, and so on all the way up to the main
2078
 
section.
2079
 
 
2080
 
If the value specified isn't found in any of these locations, then a
2081
 
``MissingInterpolationOption`` error is raised (a subclass of
2082
 
``ConfigObjError``).
 
1411
 
 
1412
You specify a value to be substituted by including ``%(name)s`` in the value.
 
1413
 
 
1414
Interpolation checks first the 'DEFAULT' sub-section of the current section to
 
1415
see if ``name`` is the key to a value. ('name' is case sensitive).
 
1416
 
 
1417
If it doesn't find it, next it checks the 'DEFAULT' section of the parent
 
1418
section, last it checks the 'DEFAULT' section of the main section.
 
1419
 
 
1420
If the value specified isn't found then a ``MissingInterpolationOption`` error
 
1421
is raised (a subclass of ``ConfigObjError``).
2083
1422
 
2084
1423
If it is found then the returned value is also checked for substitutions. This
2085
1424
allows you to make up compound values (for example directory paths) that use
2086
1425
more than one default value. It also means it's possible to create circular
2087
 
references. If there are any circular references which would cause an infinite
2088
 
interpolation loop, an ``InterpolationLoopError`` is raised.
 
1426
references. If after ten replacements there are still values to substitute, an
 
1427
``InterpolationDepthError`` is raised.
2089
1428
 
2090
1429
Both of these errors are subclasses of ``InterpolationError``, which is a
2091
1430
subclass of ``ConfigObjError``.
2095
1434
See `Validation and Interpolation`_. (This can only happen if validation
2096
1435
has to *change* the value).
2097
1436
 
2098
 
 
2099
1437
Comments
2100
1438
========
2101
1439
 
2121
1459
 
2122
1460
These comments are all written back out by the ``write`` method.
2123
1461
 
2124
 
 
2125
 
flatten_errors
2126
 
==============
2127
 
 
2128
 
::
2129
 
 
2130
 
    flatten_errors(cfg, res)
2131
 
 
2132
 
Validation_ is a powerful way of checking that the values supplied by the user
2133
 
make sense.
2134
 
 
2135
 
The validate_ method returns a results dictionary that represents pass or fail
2136
 
for each value. This doesn't give you any information about *why* the check
2137
 
failed.
2138
 
 
2139
 
``flatten_errors`` is an example function that turns a results dictionary into
2140
 
a flat list, that only contains values that *failed*.
2141
 
 
2142
 
``cfg`` is the ConfigObj instance being checked, ``res`` is the results
2143
 
dictionary returned by ``validate``.
2144
 
 
2145
 
It returns a list of keys that failed. Each member of the list is a tuple : ::
2146
 
 
2147
 
    ([list of sections...], key, result)
2148
 
 
2149
 
If ``validate`` was called with ``preserve_errors=False`` (the default)
2150
 
then ``result`` will always be ``False``.
2151
 
 
2152
 
*list of sections* is a flattened list of sections that the key was found
2153
 
in.
2154
 
 
2155
 
If the section was missing then key will be ``None``.
2156
 
 
2157
 
If the value (or section) was missing then ``result`` will be ``False``.
2158
 
 
2159
 
If ``validate`` was called with ``preserve_errors=True`` and a value
2160
 
was present, but failed the check, then ``result`` will be the exception
2161
 
object returned. You can use this as a string that describes the failure.
2162
 
 
2163
 
For example :
2164
 
 
2165
 
    *The value "3" is of the wrong type*.
2166
 
 
2167
 
 
2168
 
Example Usage
2169
 
-------------
2170
 
 
2171
 
The output from ``flatten_errors`` is a list of tuples.
2172
 
 
2173
 
Here is an example of how you could present this information to the user.
2174
 
 
2175
 
.. raw:: html
2176
 
 
2177
 
    {+coloring}
2178
 
    
2179
 
    vtor = validate.Validator()
2180
 
    # ini is your config file - cs is the configspec
2181
 
    cfg = ConfigObj(ini, configspec=cs)
2182
 
    res = cfg.validate(vtor, preserve_errors=True)
2183
 
    for entry in flatten_errors(cfg, res):
2184
 
        # each entry is a tuple
2185
 
        section_list, key, error = entry
2186
 
        if key is not None:
2187
 
           section_list.append(key)
2188
 
        else:
2189
 
            section_list.append('[missing section]')
2190
 
        section_string = ', '.join(section_list)
2191
 
        if error == False:
2192
 
            error = 'Missing value or section.'
2193
 
        print section_string, ' = ', error
2194
 
 
2195
 
    {-coloring}
2196
 
 
 
1462
Encodings
 
1463
=========
 
1464
 
 
1465
ConfigObj 4 is designed to work with ASCII compatible encodings [#]_. If you
 
1466
need support for other character sets, then I suggest you use the UTF8
 
1467
encoding for your config files.
 
1468
 
 
1469
By default ConfigObj leaves keys/members as encoded byte strings (ordinary
 
1470
strings). If you want to access the config file members as Unicode objects
 
1471
rather than strings, you can use the ``decode`` method. This takes an encoding
 
1472
as its argument and decodes all members and keys into Unicode. It will only
 
1473
work if *all* members are byte strings (or lists of strings) , so you should do
 
1474
it before calling ``validate``.
 
1475
 
 
1476
If you want to turn the Unicode strings back into byte strings, you can call
 
1477
the ``encode`` method. This also takes an encoding as its argument and assumes
 
1478
*all* keys/members are Unicode.
 
1479
 
 
1480
If you start working with Unicode strings, you may find you get
 
1481
``UnicodeDecodeError`` or ``UnicodeEncodeError`` in unexpected places. This is
 
1482
because you have forced Python to do an *implicit* encode or decode.
 
1483
 
 
1484
Implicit decodes (and encodes) use the encoding returned by
 
1485
``sys.getdefaultencoding()``. This is *usually* ASCII. This means that if you
 
1486
have any non-ASCII characters, Python doesn't know how to treat them and will
 
1487
raise an error.
 
1488
 
 
1489
This happens if you add a byte string to a Unicode string, compare a byte
 
1490
string to a Unicode string, print a Unicode string, or write it to a file. If
 
1491
you work with Unicode, you should do the appropriate encode or decode first.
 
1492
 
 
1493
Backwards Compatibility
 
1494
=======================
 
1495
 
 
1496
There have been a lot of changes since ConfigObj 3. The core parser is now
 
1497
based on regular expressions, and is a lot faster and smaller. There is now no
 
1498
difference in the way we treat flat files and non-flatfiles, that is, no empty
 
1499
sections. This means some of the code can be a lot simpler, less code does
 
1500
more of the work [#]_.
 
1501
 
 
1502
There have been other simplifications: for example we only have eight options
 
1503
instead of seventeen.
 
1504
 
 
1505
Most config files created for ConfigObj 3 will be read with no changes and many
 
1506
programs will work without having to alter code. Some of the changes do break
 
1507
backwards compatibility: for example, code that uses the previous options will
 
1508
now raise an error. It should be very easy to fix these, though.
 
1509
 
 
1510
Below is a list of all the changes that affect backwards compatibility. This
 
1511
doesn't include details of method signatures that have changed, because almost
 
1512
all of them have.
 
1513
 
 
1514
Incompatible Changes
 
1515
--------------------
 
1516
 
 
1517
(I have removed a lot of needless complications: this list is probably not
 
1518
conclusive, many option/attribute/method names have changed.)
 
1519
 
 
1520
Case sensitive.
 
1521
 
 
1522
The only valid divider is '='.
 
1523
 
 
1524
Line continuations with ``\`` removed.
 
1525
 
 
1526
No recursive lists in values.
 
1527
 
 
1528
No empty sections.
 
1529
 
 
1530
No distinction between flatfiles and non flatfiles.
 
1531
 
 
1532
Change in list syntax: use commas to indicate list, not parentheses (square
 
1533
brackets and parentheses are no longer recognised as lists).
 
1534
 
 
1535
';' is no longer valid for comments, and no multiline comments.
 
1536
 
 
1537
No attribute-style access to values.
 
1538
 
 
1539
Empty values not allowed: use '' or "".
 
1540
 
 
1541
In ConfigObj 3, setting a non-flatfile member to ``None`` would initialise it
 
1542
as an empty section.
 
1543
 
 
1544
The escape entities '&mjf-lf;' and '&mjf-quot;' have gone, replaced by triple
 
1545
quote, multiple line values.
 
1546
 
 
1547
The ``newline``, ``force_return``, and ``default`` options have gone.
 
1548
 
 
1549
The ``encoding`` and ``backup_encoding`` methods have gone, replaced with the
 
1550
``encode`` and ``decode`` methods.
 
1551
 
 
1552
``fileerror`` and ``createempty`` options have become ``file_error`` and
 
1553
``create_empty``.
 
1554
 
 
1555
Partial configspecs (for specifying the order members should be written out,
 
1556
and which should be present) have gone. The configspec is no longer used to
 
1557
specify order for the ``write`` method.
 
1558
 
 
1559
Exceeding the maximum depth of recursion in string interpolation now raises an
 
1560
error ``InterpolationDepthError``.
 
1561
 
 
1562
Specifying a value for interpolation which doesn't exist now raises a
 
1563
``MissingInterpolationOption`` error (instead of merely being ignored).
 
1564
 
 
1565
The ``writein`` method has been removed.
 
1566
 
 
1567
The comments attribute is now a list (``inline_comments`` equates to the old
 
1568
comments attribute).
2197
1569
 
2198
1570
ConfigObj 3
2199
 
===========
 
1571
-----------
2200
1572
 
2201
1573
ConfigObj 3 is now deprecated in favour of ConfigObj 4. I can fix bugs in
2202
1574
ConfigObj 3 if needed, though.
2208
1580
.. _ConfigObj 3.3.1: http://www.voidspace.org.uk/cgi-bin/voidspace/downman.py?file=configobj3.zip
2209
1581
.. _ConfigObj 3 Docs: http://www.voidspace.org.uk/python/configobj3.html
2210
1582
 
2211
 
 
2212
1583
CREDITS
2213
1584
=======
2214
1585
 
2218
1589
Particularly thanks to Nicola Larosa for help on the config file spec, the
2219
1590
validation system and the doctests.
2220
1591
 
2221
 
*validate.py* was originally written by Michael Foord and Mark Andrews.
 
1592
*validate.py* was originally written by Michael Foord and `Mark Andrews`_.
2222
1593
 
2223
1594
Thanks to others for input and bugfixes.
2224
1595
 
2225
 
 
2226
1596
LICENSE
2227
1597
=======
2228
1598
 
2232
1602
Of course if it does, let us know and we'll fix the problem so it doesn't
2233
1603
happen to anyone else {sm;:-)}. ::
2234
1604
 
2235
 
    Copyright (c) 2004 - 2008, Michael Foord & Nicola Larosa
 
1605
    Copyright (c) 2004 & 2005, Michael Foord & Nicola Larosa
2236
1606
    All rights reserved.
2237
1607
 
2238
1608
    Redistribution and use in source and binary forms, with or without
2266
1636
 
2267
1637
You should also be able to find a copy of this license at : `BSD License`_
2268
1638
 
2269
 
.. _BSD License: http://www.voidspace.org.uk/python/license.shtml
2270
 
 
 
1639
.. _BSD License: http://www.voidspace.org.uk/documents/BSD-LICENSE.txt
2271
1640
 
2272
1641
TODO
2273
1642
====
2274
1643
 
2275
 
Better support for configuration from multiple files, including tracking
2276
 
*where* the original file came from and writing changes to the correct
2277
 
file.
2278
 
 
2279
 
Make ``newline`` an option (as well as an attribute) ?
2280
 
 
2281
 
``UTF16`` encoded files, when returned as a list of lines, will have the
2282
 
BOM at the start of every line. Should this be removed from all but the
2283
 
first line ?
2284
 
 
2285
 
Option to set warning type for unicode decode ? (Defaults to strict).
2286
 
 
2287
 
A method to optionally remove uniform indentation from multiline values.
2288
 
(do as an example of using ``walk`` - along with string-escape)
2289
 
 
2290
 
Should the results dictionary from validate be an ordered dictionary if
2291
 
`odict <http://www.voidspace.org.uk/python/odict.html>`_ is available ?
2292
 
 
2293
 
Implement some of the sequence methods (which include slicing) from the
2294
 
newer ``odict`` ?
2295
 
 
2296
 
Preserve line numbers of values (and possibly the original text of each value).
2297
 
 
 
1644
Fix any bugs (and resolvable issues).
 
1645
 
 
1646
Do an example for the 'walk' which removes uniform indentation in multiline
 
1647
values.
 
1648
 
 
1649
When initialising a section from a ConfigObj *or* an ``OrderedDictionary``
 
1650
we could preserve ordering.
 
1651
 
 
1652
Add an *odict* method which returns an `OrderedDictionary``.
2298
1653
 
2299
1654
ISSUES
2300
1655
======
2301
1656
 
2302
1657
.. note::
2303
1658
 
2304
 
    Please file any bug reports to `Michael Foord`_ or the **ConfigObj**
 
1659
    Please file any bug reports to `Michael Foord`_ or the ConfigObj
2305
1660
    `Mailing List`_.
2306
1661
 
2307
 
There is currently no way to specify the encoding of a configspec file.
2308
 
 
2309
 
When using ``copy`` mode for validation, it won't copy ``DEFAULT``
2310
 
sections. This is so that you *can* use interpolation in configspec
2311
 
files.
2312
 
 
2313
 
``validate`` doesn't report *extra* values or sections.
2314
 
 
2315
 
You can't have a keyword with the same name as a section (in the same
2316
 
section). They are both dictionary keys - so they would overlap.
2317
 
 
2318
 
ConfigObj doesn't quote and unquote values if ``list_values=False``.
2319
 
This means that leading or trailing whitespace in values will be lost when
2320
 
writing. (Unless you manually quote).
2321
 
 
2322
 
Interpolation checks first the current section, then the 'DEFAULT' subsection
2323
 
of the current section, before moving on to the current section's parent and
2324
 
so on up the tree.
2325
 
 
2326
 
Does it matter that we don't support the ':' divider, which is supported
2327
 
by ``ConfigParser`` ?
2328
 
 
2329
 
String interpolation and validation don't play well together. When
2330
 
validation changes type it sets the value. This will correctly fetch the
2331
 
value using interpolation - but then overwrite the interpolation reference.
2332
 
If the value is unchanged by validation (it's a string) - but other types
2333
 
will be.
2334
 
 
 
1662
You can't have a keyword with the same name as a section (in the same section).
 
1663
They are both dictionary keys, so they would overlap.
 
1664
 
 
1665
Interpolation checks first the 'DEFAULT' sub-section of the current section,
 
1666
next it checks the 'DEFAULT' section of the parent section, last it checks the
 
1667
'DEFAULT' section of the main section.
 
1668
 
 
1669
Logically a 'DEFAULT' section should apply to all subsections of the *same
 
1670
parent*: this means that checking the 'DEFAULT' sub-section in the *current
 
1671
section* is not necessarily logical ?
 
1672
 
 
1673
In order to simplify Unicode support (which is possibly of limited value
 
1674
in a config file ?) I have removed automatic support, and added thev``encode``
 
1675
and ``decode`` methods. These can be used to transform keys and entries.
 
1676
Because the regex looks for specific values on inital parsing (i.e. the quotes
 
1677
and the equals signs) it can only read ASCII compatible encodings. For Unicode
 
1678
I suggest ``UTF8``, which is ASCII compatible.
 
1679
 
 
1680
.. note::
 
1681
 
 
1682
    There is no reason why you shouldn't decode your config file into Unicode
 
1683
    before passing them to ConfigObj (as a list of lines). This should give you
 
1684
    Unicode keys and values.
 
1685
 
 
1686
Does it matter that we don't support the ':' divider, which is supported by
 
1687
``ConfigParser`` ?
 
1688
 
 
1689
Following error with "list_values=False" : ::
 
1690
 
 
1691
    >>> a = ["a='hello', 'goodbye'"]
 
1692
    >>>
 
1693
    >>> c(a, list_values=False)
 
1694
    {'a': "hello', 'goodbye"}
 
1695
 
 
1696
The regular expression correctly removes the value - ``"'hello', 'goodbye'"`` -
 
1697
and then unquote just removes the front and back quotes (called by
 
1698
``_handle_value``). What should we do ?? We *ought* to raise an exception - 
 
1699
because if lists are off it's an invalid value. This is not desired if you want 
 
1700
to do your own list processing e.g. using listquote for nested lists. It would
 
1701
be *better* in this case not to unquote. Raising an exception would require a
 
1702
new regex.
 
1703
 
 
1704
String interpolation and validation don't play well together. See 
 
1705
`Validation and Interpolation`_.
2335
1706
 
2336
1707
CHANGELOG
2337
1708
=========
2338
1709
 
2339
1710
This is an abbreviated changelog showing the major releases up to version 4.
2340
 
From version 4 it lists all releases and changes.
2341
 
 
2342
 
 
2343
 
2008/02/05 - Version 4.5.2
2344
 
--------------------------
2345
 
 
2346
 
Distribution updated to include version 0.3.2 of validate_. This means that
2347
 
``None`` as a default value win configspecs works.
2348
 
 
2349
 
 
2350
 
2008/02/05 - Version 4.5.1
2351
 
--------------------------
2352
 
 
2353
 
Distribution updated to include version 0.3.1 of validate_. This means that
2354
 
Unicode configspecs now work.
2355
 
 
2356
 
 
2357
 
2008/02/05 - Version 4.5.0
2358
 
--------------------------
2359
 
 
2360
 
ConfigObj will now guarantee that files will be written terminated with a
2361
 
newline.
2362
 
 
2363
 
ConfigObj will no longer attempt to import the ``validate`` module, until/unless 
2364
 
you call ``ConfigObj.validate`` with ``preserve_errors=True``. This makes it 
2365
 
faster to import.
2366
 
 
2367
 
New methods ``restore_default`` and ``restore_defaults``. ``restore_default``
2368
 
resets an entry to its default value (and returns that value). ``restore_defaults``
2369
 
resets all entries to their default value. It doesn't modify entries without a 
2370
 
default value. You must have validated a ConfigObj (which populates the
2371
 
``default_values`` dictionary) before calling these methods.
2372
 
 
2373
 
BUGFIX: Proper quoting of keys, values and list values that contain hashes 
2374
 
(when writing).  When ``list_values=False``, values containing hashes are 
2375
 
triple quoted.
2376
 
 
2377
 
Added the ``reload`` method. This reloads a ConfigObj from file. If the filename
2378
 
attribute is not set then a ``ReloadError`` (a new exception inheriting from
2379
 
``IOError``) is raised.
2380
 
 
2381
 
BUGFIX: Files are read in with 'rb' mode, so that native/non-native line endings work!
2382
 
 
2383
 
Minor efficiency improvement in ``unrepr`` mode.
2384
 
 
2385
 
Added missing docstrings for some overidden dictionary methods.
2386
 
 
2387
 
Added the ``reset`` method. This restores a ConfigObj to a freshly created state.
2388
 
 
2389
 
Removed old CHANGELOG file.
2390
 
 
2391
 
 
2392
 
2007/02/04 - Version 4.4.0
2393
 
--------------------------
2394
 
 
2395
 
Official release of 4.4.0
2396
 
 
2397
 
 
2398
 
2006/12/17 - Version 4.3.3-alpha4
2399
 
---------------------------------
2400
 
 
2401
 
By Nicola Larosa
2402
 
 
2403
 
Allowed arbitrary indentation in the ``indent_type`` parameter, removed the
2404
 
``NUM_INDENT_SPACES`` and ``MAX_INTERPOL_DEPTH`` (a leftover) constants,
2405
 
added indentation tests (including another docutils workaround, sigh), updated
2406
 
the documentation.
2407
 
 
2408
 
By Michael Foord
2409
 
 
2410
 
Made the import of ``compiler`` conditional so that ``ConfigObj`` can be used
2411
 
with `IronPython <http://www.codeplex.com/IronPython>`_.
2412
 
 
2413
 
 
2414
 
2006/12/17 - Version 4.3.3-alpha3
2415
 
---------------------------------
2416
 
 
2417
 
By Nicola Larosa
2418
 
 
2419
 
Added a missing ``self.`` in the _handle_comment method and a related test,
2420
 
per Sourceforge bug #1523975.
2421
 
 
2422
 
 
2423
 
2006/12/09 - Version 4.3.3-alpha2
2424
 
---------------------------------
2425
 
 
2426
 
By Nicola Larosa
2427
 
 
2428
 
Changed interpolation search strategy, based on this patch by Robin Munn:
2429
 
http://sourceforge.net/mailarchive/message.php?msg_id=17125993
2430
 
 
2431
 
 
2432
 
2006/12/09 - Version 4.3.3-alpha1
2433
 
---------------------------------
2434
 
 
2435
 
By Nicola Larosa
2436
 
 
2437
 
Added Template-style interpolation, with tests, based on this patch by
2438
 
Robin Munn: http://sourceforge.net/mailarchive/message.php?msg_id=17125991
2439
 
(awful archives, bad Sourceforge, bad).
2440
 
 
2441
 
 
2442
 
2006/06/04 - Version 4.3.2
2443
 
--------------------------
2444
 
 
2445
 
Changed error handling, if parsing finds a single error then that error will
2446
 
be re-raised. That error will still have an ``errors`` and a ``config``
2447
 
attribute.
2448
 
 
2449
 
Fixed bug where '\\n' terminated files could be truncated.
2450
 
 
2451
 
Bugfix in ``unrepr`` mode, it couldn't handle '#' in values. (Thanks to
2452
 
Philippe Normand for the report.)
2453
 
 
2454
 
As a consequence of this fix, ConfigObj doesn't now keep inline comments in
2455
 
``unrepr`` mode. This is because the parser in the `compiler package`_
2456
 
doesn't keep comments. {sm;:-)}
2457
 
 
2458
 
Error messages are now more useful. They tell you the number of parsing errors
2459
 
and the line number of the first error. (In the case of multiple errors.)
2460
 
 
2461
 
Line numbers in exceptions now start at 1, not 0.
2462
 
 
2463
 
Errors in ``unrepr`` mode are now handled the same way as in the normal mode.
2464
 
The errors stored will be an ``UnreprError``.
2465
 
 
2466
 
 
2467
 
2006/04/29 - Version 4.3.1
2468
 
--------------------------
2469
 
 
2470
 
Added ``validate.py`` back into ``configobj.zip``. (Thanks to Stewart
2471
 
Midwinter)
2472
 
 
2473
 
Updated to `validate.py`_ 0.2.2.
2474
 
 
2475
 
Preserve tuples when calling the ``dict`` method. (Thanks to Gustavo Niemeyer.)
2476
 
 
2477
 
Changed ``__repr__`` to return a string that contains ``ConfigObj({ ... })``.
2478
 
 
2479
 
Change so that an options dictionary isn't modified by passing it to ConfigObj.
2480
 
(Thanks to Artarious.)
2481
 
 
2482
 
Added ability to handle negative integers in ``unrepr``. (Thanks to Kevin
2483
 
Dangoor.)
2484
 
 
2485
 
 
2486
 
2006/03/24 - Version 4.3.0
2487
 
--------------------------
2488
 
 
2489
 
Moved the tests and the CHANGELOG (etc) into a separate file. This has reduced
2490
 
the size of ``configobj.py`` by about 40%.
2491
 
 
2492
 
Added the ``unrepr`` mode to reading and writing config files. Thanks to Kevin
2493
 
Dangoor for this suggestion.
2494
 
 
2495
 
Empty values are now valid syntax. They are read as an empty string ``''``.
2496
 
(``key =``, or ``key = # comment``.)
2497
 
 
2498
 
``validate`` now honours the order of the configspec.
2499
 
 
2500
 
Added the ``copy`` mode to validate. Thanks to Louis Cordier for this
2501
 
suggestion.
2502
 
 
2503
 
Fixed bug where files written on windows could be given ``'\r\r\n'`` line
2504
 
terminators.
2505
 
 
2506
 
Fixed bug where last occurring comment line could be interpreted as the
2507
 
final comment if the last line isn't terminated.
2508
 
 
2509
 
Fixed bug where nested list values would be flattened when ``write`` is
2510
 
called. Now sub-lists have a string representation written instead.
2511
 
 
2512
 
Deprecated ``encode`` and ``decode`` methods instead.
2513
 
 
2514
 
You can now pass in a ConfigObj instance as a configspec (remember to read
2515
 
the configspec file using ``list_values=False``).
2516
 
 
2517
 
Sorted footnotes in the docs.
2518
 
 
2519
 
 
2520
 
2006/02/16 - Version 4.2.0
2521
 
--------------------------
2522
 
 
2523
 
Removed ``BOM_UTF8`` from ``__all__``.
2524
 
 
2525
 
The ``BOM`` attribute has become a boolean. (Defaults to ``False``.) It is
2526
 
*only* ``True`` for the ``UTF16/UTF8`` encodings.
2527
 
 
2528
 
File like objects no longer need a ``seek`` attribute.
2529
 
 
2530
 
Full unicode support added. New options/attributes ``encoding``,
2531
 
``default_encoding``.
2532
 
 
2533
 
ConfigObj no longer keeps a reference to file like objects. Instead the
2534
 
``write`` method takes a file like object as an optional argument. (Which
2535
 
will be used in preference of the ``filename`` attribute if that exists as
2536
 
well.)
2537
 
 
2538
 
utf16 files decoded to unicode.
2539
 
 
2540
 
If ``BOM`` is ``True``, but no encoding specified, then the utf8 BOM is
2541
 
written out at the start of the file. (It will normally only be ``True`` if
2542
 
the utf8 BOM was found when the file was read.)
2543
 
 
2544
 
Thanks to Aaron Bentley for help and testing on the unicode issues.
2545
 
 
2546
 
File paths are *not* converted to absolute paths, relative paths will
2547
 
remain relative as the ``filename`` attribute.
2548
 
 
2549
 
Fixed bug where ``final_comment`` wasn't returned if ``write`` is returning
2550
 
a list of lines.
2551
 
 
2552
 
Deprecated ``istrue``, replaced it with ``as_bool``.
2553
 
 
2554
 
Added ``as_int`` and ``as_float``.
2555
 
 
2556
 
 
2557
 
2005/12/14 - Version 4.1.0
2558
 
--------------------------
2559
 
 
2560
 
Added ``merge``, a recursive update.
2561
 
 
2562
 
Added ``preserve_errors`` to ``validate`` and the ``flatten_errors``
2563
 
example function.
2564
 
 
2565
 
Thanks to Matthew Brett for suggestions and helping me iron out bugs.
2566
 
    
2567
 
Fixed bug where a config file is *all* comment, the comment will now be
2568
 
``initial_comment`` rather than ``final_comment``.
2569
 
 
2570
 
Validation no longer done on the 'DEFAULT' section (only in the root level).
2571
 
This allows interpolation in configspecs.
2572
 
 
2573
 
Also use the new list syntax in validate_ 0.2.1. (For configspecs).
2574
 
 
2575
 
 
2576
 
2005/12/02 - Version 4.0.2
2577
 
--------------------------
2578
 
 
2579
 
Fixed bug in ``create_empty``. Thanks to Paul Jimenez for the report.
2580
 
 
2581
 
 
2582
 
2005/11/05 - Version 4.0.1
2583
 
--------------------------
2584
 
 
2585
 
Fixed bug in ``Section.walk`` when transforming names as well as values.
2586
 
 
2587
 
Added the ``istrue`` method. (Fetches the boolean equivalent of a string
2588
 
value).
2589
 
 
2590
 
Fixed ``list_values=False`` - they are now only quoted/unquoted if they
2591
 
are multiline values.
2592
 
 
2593
 
List values are written as ``item, item`` rather than ``item,item``.
2594
 
 
 
1711
From version 4 it lists all releases and changes. *More* data on individual
 
1712
changes may be found in the source code.
2595
1713
 
2596
1714
2005/10/17 - Version 4.0.0
2597
1715
--------------------------
2604
1722
 
2605
1723
Obscure typo/bug fixed in ``write``. Wouldn't have affected anyone though.
2606
1724
 
2607
 
 
2608
1725
2005/09/09 - Version 4.0.0 beta 5
2609
1726
---------------------------------
2610
1727
 
2614
1731
 
2615
1732
Fixed bug with commas in comments. (matched as a list value)
2616
1733
 
2617
 
 
2618
1734
2005/09/07 - Version 4.0.0 beta 4
2619
1735
---------------------------------
2620
1736
 
2625
1741
 
2626
1742
Changed the mailing list address.
2627
1743
 
2628
 
 
2629
1744
2005/08/28 - Version 4.0.0 beta 3
2630
1745
---------------------------------
2631
1746
 
2632
1747
Interpolation is switched off before writing out files.
2633
1748
 
2634
1749
Fixed bug in handling ``StringIO`` instances. (Thanks to report from
2635
 
Gustavo Niemeyer.)
 
1750
"Gustavo Niemeyer" <gustavo@niemeyer.net>)
2636
1751
 
2637
1752
Moved the doctests from the ``__init__`` method to a separate function.
2638
1753
(For the sake of IDE calltips).
2639
1754
 
2640
 
 
2641
1755
2005/08/25 - Version 4.0.0 beta 2
2642
1756
---------------------------------
2643
1757
 
2644
1758
Amendments to *validate.py*.
2645
1759
 
2646
 
First public release.
2647
 
 
 
1760
Official release.
2648
1761
 
2649
1762
2005/08/21 - Version 4.0.0 beta 1
2650
1763
---------------------------------
2667
1780
 
2668
1781
Improved error handling.
2669
1782
 
2670
 
Plus lots of other improvements. {sm;:grin:}
2671
 
 
 
1783
Plus lots of other improvements {sm;:grin:}.
2672
1784
 
2673
1785
2004/05/24 - Version 3.0.0
2674
1786
--------------------------
2721
1833
 
2722
1834
Charmap is now incorporated into ConfigObj.
2723
1835
 
2724
 
 
2725
1836
2004/03/14 - Version 2.0.0 beta
2726
1837
-------------------------------
2727
1838
 
2731
1842
The config object now behaves like a dictionary.
2732
1843
 
2733
1844
I've completely broken the interface, but I don't think anyone was really
2734
 
using it anyway.
 
1845
 using it anyway.
2735
1846
 
2736
 
This new version is much more 'classy'. {sm;:wink:}
 
1847
This new version is much more 'classy' {sm;:wink:}
2737
1848
 
2738
1849
It will also read straight from/to a filename and completely parse a config
2739
1850
file without you *having* to supply a config spec.
2743
1854
No longer has getval and setval methods: use normal dictionary methods, or add
2744
1855
and delete.
2745
1856
 
2746
 
 
2747
1857
2004/01/29 - Version 1.0.5
2748
1858
--------------------------
2749
1859
 
2755
1865
 
2756
1866
A couple of bugs have been fixed.
2757
1867
 
2758
 
 
2759
1868
Origins
2760
1869
-------
2761
1870
 
2762
1871
ConfigObj originated in a set of functions for reading config files in the
2763
 
`atlantibots <http://www.voidspace.org.uk/atlantibots/>`_ project. The original
2764
 
functions were written by Rob McNeur.
 
1872
atlantibots_ project. The original functions were written by Rob McNeur...
2765
1873
 
 
1874
.. _atlantibots: http://www.voidspace.org.uk/atlantibots
2766
1875
 
2767
1876
----------
2768
1877
 
2769
 
 
2770
1878
Footnotes
2771
1879
=========
2772
1880
 
 
1881
.. [#] The core parser is now based on regular expressions, so it's a lot
 
1882
    faster.
 
1883
 
 
1884
.. [#] 134 of them, at the time of writing.
 
1885
 
2773
1886
.. [#] And if you discover any bugs, let us know. We'll fix them quickly.
2774
1887
 
2775
1888
.. [#] If you specify a filename that doesn't exist, ConfigObj will assume you
2776
1889
    are creating a new one. See the *create_empty* and *file_error* options_.
2777
1890
 
2778
 
.. [#] They can be byte strings (*ordinary* strings) or Unicode.
 
1891
.. [#] They can be byte strings ('ordinary' strings) or Unicode. If they are
 
1892
    Unicode then ConfigObj will have to do an implicit encode before writing.
 
1893
    See the encodings_ section for more details.
2779
1894
 
2780
1895
.. [#] Except we don't support the RFC822 style line continuations, nor ':' as
2781
1896
    a divider.
2782
1897
 
2783
 
.. [#] This is a change in ConfigObj 4.2.0. Note that ConfigObj doesn't call
2784
 
    the seek method of any file like object you pass in. You may want to call
2785
 
    ``file_object.seek(0)`` yourself, first.
 
1898
.. [#] For a file object that will depend what mode it was opened with. You
 
1899
    can read *and* write to a ``StringIO`` instance, but not always to a
 
1900
    ``cStringIO`` instance.
2786
1901
 
2787
1902
.. [#] A side effect of this is that it enables you to copy a ConfigObj :
2788
1903
 
2789
 
    .. raw:: html
2790
 
    
2791
 
        {+coloring}
2792
 
    
2793
 
        # only copies members
2794
 
        # not attributes/comments
2795
 
        config2 = ConfigObj(config1)
2796
 
    
2797
 
        {-coloring}
 
1904
.. raw:: html
 
1905
 
 
1906
    {+coloring}
 
1907
 
 
1908
    # only copies members
 
1909
    # not attributes/comments
 
1910
    config2 = ConfigObj(config1)
 
1911
 
 
1912
    {-coloring}
 
1913
 
 
1914
..
2798
1915
 
2799
1916
    The order of values and sections will not be preserved, though.
2800
1917
 
2801
1918
.. [#] Other than lists of strings.
2802
1919
 
2803
 
.. [#] The exception is if it detects a ``UTF16`` encoded file which it
2804
 
    must decode before parsing.
2805
 
     
2806
 
.. [#] The method signature shows that this method takes
2807
 
    two arguments. The second is the section to be written. This is because the
2808
 
    ``write`` method is called recursively.
 
1920
.. [#] The method signature in the API docs will show that it does in fact
 
1921
    take one argument: the section to be written. This is because the
 
1922
    ``write`` method is called recursively. Using this argument *forces* write
 
1923
    to return a list of lines, so it's probably not very useful to you.
2809
1924
 
2810
1925
.. [#] The dict method doesn't actually use the deepcopy mechanism. This means
2811
1926
    if you add nested lists (etc) to your ConfigObj, then the dictionary
2816
1931
    change the value by setting ``section[key] = newval``. It also gives you
2817
1932
    access to the *rename* method of the section.
2818
1933
 
 
1934
.. [#] A current bug in unquoting when ``list_values=False`` currently makes
 
1935
    this impossible. We are considering the best way to fix this.
 
1936
 
2819
1937
.. [#] Minimum required version of *validate.py* 0.2.0 .
2820
1938
 
 
1939
.. [#] There's nothing to stop you decoding the whole config file to Unicode
 
1940
    *first*.
 
1941
 
 
1942
.. [#] It also makes ConfigObj a lot simpler to *use*.
2821
1943
 
2822
1944
.. note::
2823
1945
 
2825
1947
    textmacros module and the PySrc CSS stuff. See
2826
1948
    http://www.voidspace.org.uk/python/firedrop2/textmacros.shtml
2827
1949
 
2828
 
 
2829
1950
.. raw:: html
2830
1951
 
2831
1952
    <div align="center">
2832
 
        <p>
2833
 
            <a href="http://www.python.org">
2834
 
                <img src="images/new_python.gif" width="100" height="103" border="0" 
2835
 
                    alt="Powered by Python" />
2836
 
            </a>
2837
 
            <a href="http://sourceforge.net">
2838
 
                <img src="http://sourceforge.net/sflogo.php?group_id=123265&amp;type=1" width="88" height="31" border="0" alt="SourceForge.net Logo" />
2839
 
            </a>
2840
 
            <a href="http://www.opensource.org">
2841
 
                <img src="images/osi-certified-120x100.gif" width="120" height="100" border="0"
2842
 
                    alt="Certified Open Source"/>
2843
 
            </a>
2844
 
        </p>
2845
 
        <p>
2846
 
            <a href="http://www.voidspace.org.uk/python/index.shtml">
2847
 
                <img src="images/pythonbanner.gif" width="468" height="60" 
2848
 
                alt="Python on Voidspace" border="0" />
2849
 
            </a>
2850
 
        </p>
2851
 
 
 
1953
        <a href="http://sourceforge.net/donate/index.php?group_id=123265">
 
1954
            <img src="http://images.sourceforge.net/images/project-support.jpg" width="88" height="32" border="0" alt="Support This Project" /> 
 
1955
        </a>
 
1956
        <a href="http://sourceforge.net">
 
1957
            <img src="http://sourceforge.net/sflogo.php?group_id=123265&amp;type=1" width="88" height="31" border="0" alt="SourceForge.net Logo" />
 
1958
        </a>
 
1959
        <br />
 
1960
        <a href="http://www.python.org">
 
1961
            <img src="images/powered_by_python.jpg" width="602" height="186" border="0" />
 
1962
        </a>
 
1963
        <a href="http://www.opensource.org">
 
1964
            <img src="images/osi-certified-120x100.gif" width="120" height="100" border="0" />
 
1965
            <br /><strong>Certified Open Source</strong>
 
1966
        </a>
 
1967
        <br /><br />
 
1968
        <script type="text/javascript" language="JavaScript">var site="s16atlantibots"</script>
 
1969
        <script type="text/javascript" language="JavaScript1.2" src="http://s16.sitemeter.com/js/counter.js?site=s16atlantibots"></script>
 
1970
        <noscript>
 
1971
            <a href="http://s16.sitemeter.com/stats.asp?site=s16atlantibots">
 
1972
                <img src="http://s16.sitemeter.com/meter.asp?site=s16atlantibots" alt="Site Meter" border=0 />
 
1973
            </a>
 
1974
        </noscript>
 
1975
        <br />
2852
1976
    </div>
2853
1977
 
2854
1978
.. _listquote: http://www.voidspace.org.uk/python/modules.shtml#listquote
2855
 
.. _Michael Foord: http://www.voidspace.org.uk/python/weblog/index.shtml
 
1979
.. _Michael Foord: http://www.voidspace.org.uk
2856
1980
.. _Nicola Larosa: http://www.teknico.net
 
1981
.. _Mark Andrews: http://www.la-la.com