blob: ae93504917f855f44d366924f8057cd5cdd3571a [file] [log] [blame]
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00001:mod:`configparser` --- Configuration file parser
Georg Brandl116aa622007-08-15 14:28:22 +00002=================================================
3
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00004.. module:: configparser
Georg Brandl116aa622007-08-15 14:28:22 +00005 :synopsis: Configuration file parser.
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. moduleauthor:: Ken Manheimer <klm@zope.com>
8.. moduleauthor:: Barry Warsaw <bwarsaw@python.org>
9.. moduleauthor:: Eric S. Raymond <esr@thyrsus.com>
Łukasz Langa26d513c2010-11-10 18:57:39 +000010.. moduleauthor:: Łukasz Langa <lukasz@langa.pl>
Georg Brandl116aa622007-08-15 14:28:22 +000011.. sectionauthor:: Christopher G. Petrilli <petrilli@amber.org>
Łukasz Langa26d513c2010-11-10 18:57:39 +000012.. sectionauthor:: Łukasz Langa <lukasz@langa.pl>
Georg Brandl116aa622007-08-15 14:28:22 +000013
Andrew Kuchling2e3743c2014-03-19 16:23:01 -040014**Source code:** :source:`Lib/configparser.py`
15
Georg Brandl116aa622007-08-15 14:28:22 +000016.. index::
17 pair: .ini; file
18 pair: configuration; file
19 single: ini file
20 single: Windows ini file
21
Łukasz Langa7f64c8a2010-12-16 01:16:22 +000022This module provides the :class:`ConfigParser` class which implements a basic
23configuration language which provides a structure similar to what's found in
24Microsoft Windows INI files. You can use this to write Python programs which
25can be customized by end users easily.
Georg Brandl116aa622007-08-15 14:28:22 +000026
Georg Brandle720c0a2009-04-27 16:20:50 +000027.. note::
Georg Brandl116aa622007-08-15 14:28:22 +000028
Georg Brandle720c0a2009-04-27 16:20:50 +000029 This library does *not* interpret or write the value-type prefixes used in
30 the Windows Registry extended version of INI syntax.
Georg Brandl116aa622007-08-15 14:28:22 +000031
Łukasz Langa26d513c2010-11-10 18:57:39 +000032.. seealso::
33
34 Module :mod:`shlex`
35 Support for a creating Unix shell-like mini-languages which can be used
36 as an alternate format for application configuration files.
37
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000038 Module :mod:`json`
39 The json module implements a subset of JavaScript syntax which can also
40 be used for this purpose.
41
Georg Brandlbb27c122010-11-11 07:26:40 +000042
Łukasz Langa26d513c2010-11-10 18:57:39 +000043Quick Start
44-----------
45
Georg Brandlbb27c122010-11-11 07:26:40 +000046Let's take a very basic configuration file that looks like this:
Łukasz Langa26d513c2010-11-10 18:57:39 +000047
Georg Brandlbb27c122010-11-11 07:26:40 +000048.. code-block:: ini
Łukasz Langa26d513c2010-11-10 18:57:39 +000049
Georg Brandlbb27c122010-11-11 07:26:40 +000050 [DEFAULT]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000051 ServerAliveInterval = 45
52 Compression = yes
53 CompressionLevel = 9
54 ForwardX11 = yes
Łukasz Langa26d513c2010-11-10 18:57:39 +000055
Georg Brandlbb27c122010-11-11 07:26:40 +000056 [bitbucket.org]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000057 User = hg
Łukasz Langa26d513c2010-11-10 18:57:39 +000058
Georg Brandlbb27c122010-11-11 07:26:40 +000059 [topsecret.server.com]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000060 Port = 50022
61 ForwardX11 = no
Łukasz Langa26d513c2010-11-10 18:57:39 +000062
Fred Drake5a7c11f2010-11-13 05:24:17 +000063The structure of INI files is described `in the following section
64<#supported-ini-file-structure>`_. Essentially, the file
Łukasz Langa26d513c2010-11-10 18:57:39 +000065consists of sections, each of which contains keys with values.
Georg Brandlbb27c122010-11-11 07:26:40 +000066:mod:`configparser` classes can read and write such files. Let's start by
Łukasz Langa26d513c2010-11-10 18:57:39 +000067creating the above configuration file programatically.
68
Łukasz Langa26d513c2010-11-10 18:57:39 +000069.. doctest::
70
Georg Brandlbb27c122010-11-11 07:26:40 +000071 >>> import configparser
Łukasz Langa7f64c8a2010-12-16 01:16:22 +000072 >>> config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +000073 >>> config['DEFAULT'] = {'ServerAliveInterval': '45',
74 ... 'Compression': 'yes',
75 ... 'CompressionLevel': '9'}
76 >>> config['bitbucket.org'] = {}
77 >>> config['bitbucket.org']['User'] = 'hg'
78 >>> config['topsecret.server.com'] = {}
79 >>> topsecret = config['topsecret.server.com']
80 >>> topsecret['Port'] = '50022' # mutates the parser
81 >>> topsecret['ForwardX11'] = 'no' # same here
82 >>> config['DEFAULT']['ForwardX11'] = 'yes'
83 >>> with open('example.ini', 'w') as configfile:
84 ... config.write(configfile)
85 ...
Łukasz Langa26d513c2010-11-10 18:57:39 +000086
Fred Drake5a7c11f2010-11-13 05:24:17 +000087As you can see, we can treat a config parser much like a dictionary.
88There are differences, `outlined later <#mapping-protocol-access>`_, but
89the behavior is very close to what you would expect from a dictionary.
Łukasz Langa26d513c2010-11-10 18:57:39 +000090
Fred Drake5a7c11f2010-11-13 05:24:17 +000091Now that we have created and saved a configuration file, let's read it
92back and explore the data it holds.
Łukasz Langa26d513c2010-11-10 18:57:39 +000093
Łukasz Langa26d513c2010-11-10 18:57:39 +000094.. doctest::
95
Georg Brandlbb27c122010-11-11 07:26:40 +000096 >>> import configparser
Łukasz Langa7f64c8a2010-12-16 01:16:22 +000097 >>> config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +000098 >>> config.sections()
99 []
100 >>> config.read('example.ini')
101 ['example.ini']
102 >>> config.sections()
103 ['bitbucket.org', 'topsecret.server.com']
104 >>> 'bitbucket.org' in config
105 True
106 >>> 'bytebong.com' in config
107 False
108 >>> config['bitbucket.org']['User']
109 'hg'
110 >>> config['DEFAULT']['Compression']
111 'yes'
112 >>> topsecret = config['topsecret.server.com']
113 >>> topsecret['ForwardX11']
114 'no'
115 >>> topsecret['Port']
116 '50022'
117 >>> for key in config['bitbucket.org']: print(key)
118 ...
119 user
120 compressionlevel
121 serveraliveinterval
122 compression
123 forwardx11
124 >>> config['bitbucket.org']['ForwardX11']
125 'yes'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000126
Fred Drake5a7c11f2010-11-13 05:24:17 +0000127As we can see above, the API is pretty straightforward. The only bit of magic
Łukasz Langa26d513c2010-11-10 18:57:39 +0000128involves the ``DEFAULT`` section which provides default values for all other
Fred Drake5a7c11f2010-11-13 05:24:17 +0000129sections [1]_. Note also that keys in sections are
130case-insensitive and stored in lowercase [1]_.
Georg Brandlbb27c122010-11-11 07:26:40 +0000131
Łukasz Langa26d513c2010-11-10 18:57:39 +0000132
133Supported Datatypes
134-------------------
135
136Config parsers do not guess datatypes of values in configuration files, always
Georg Brandlbb27c122010-11-11 07:26:40 +0000137storing them internally as strings. This means that if you need other
138datatypes, you should convert on your own:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000139
Łukasz Langa26d513c2010-11-10 18:57:39 +0000140.. doctest::
141
Georg Brandlbb27c122010-11-11 07:26:40 +0000142 >>> int(topsecret['Port'])
143 50022
144 >>> float(topsecret['CompressionLevel'])
145 9.0
Łukasz Langa26d513c2010-11-10 18:57:39 +0000146
Łukasz Langa34cea142014-09-14 23:37:03 -0700147Since this task is so common, config parsers provide a range of handy getter
148methods to handle integers, floats and booleans. The last one is the most
149interesting because simply passing the value to ``bool()`` would do no good
150since ``bool('False')`` is still ``True``. This is why config parsers also
151provide :meth:`getboolean`. This method is case-insensitive and recognizes
152Boolean values from ``'yes'``/``'no'``, ``'on'``/``'off'``,
153``'true'``/``'false'`` and ``'1'``/``'0'`` [1]_. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000154
Łukasz Langa26d513c2010-11-10 18:57:39 +0000155.. doctest::
156
Georg Brandlbb27c122010-11-11 07:26:40 +0000157 >>> topsecret.getboolean('ForwardX11')
158 False
159 >>> config['bitbucket.org'].getboolean('ForwardX11')
160 True
161 >>> config.getboolean('bitbucket.org', 'Compression')
162 True
Łukasz Langa26d513c2010-11-10 18:57:39 +0000163
164Apart from :meth:`getboolean`, config parsers also provide equivalent
Fred Drake5a7c11f2010-11-13 05:24:17 +0000165:meth:`getint` and :meth:`getfloat` methods, but these are far less
166useful since conversion using :func:`int` and :func:`float` is
167sufficient for these types.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000168
Georg Brandlbb27c122010-11-11 07:26:40 +0000169
Łukasz Langa26d513c2010-11-10 18:57:39 +0000170Fallback Values
171---------------
172
Fred Drake5a7c11f2010-11-13 05:24:17 +0000173As with a dictionary, you can use a section's :meth:`get` method to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000174provide fallback values:
175
Łukasz Langa26d513c2010-11-10 18:57:39 +0000176.. doctest::
177
Georg Brandlbb27c122010-11-11 07:26:40 +0000178 >>> topsecret.get('Port')
179 '50022'
180 >>> topsecret.get('CompressionLevel')
181 '9'
182 >>> topsecret.get('Cipher')
183 >>> topsecret.get('Cipher', '3des-cbc')
184 '3des-cbc'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000185
Fred Drake5a7c11f2010-11-13 05:24:17 +0000186Please note that default values have precedence over fallback values.
187For instance, in our example the ``'CompressionLevel'`` key was
188specified only in the ``'DEFAULT'`` section. If we try to get it from
189the section ``'topsecret.server.com'``, we will always get the default,
190even if we specify a fallback:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000191
Łukasz Langa26d513c2010-11-10 18:57:39 +0000192.. doctest::
193
Georg Brandlbb27c122010-11-11 07:26:40 +0000194 >>> topsecret.get('CompressionLevel', '3')
195 '9'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000196
197One more thing to be aware of is that the parser-level :meth:`get` method
198provides a custom, more complex interface, maintained for backwards
Fred Drake5a7c11f2010-11-13 05:24:17 +0000199compatibility. When using this method, a fallback value can be provided via
200the ``fallback`` keyword-only argument:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000201
Łukasz Langa26d513c2010-11-10 18:57:39 +0000202.. doctest::
203
Georg Brandlbb27c122010-11-11 07:26:40 +0000204 >>> config.get('bitbucket.org', 'monster',
205 ... fallback='No such things as monsters')
206 'No such things as monsters'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000207
208The same ``fallback`` argument can be used with the :meth:`getint`,
209:meth:`getfloat` and :meth:`getboolean` methods, for example:
210
Łukasz Langa26d513c2010-11-10 18:57:39 +0000211.. doctest::
212
Georg Brandlbb27c122010-11-11 07:26:40 +0000213 >>> 'BatchMode' in topsecret
214 False
215 >>> topsecret.getboolean('BatchMode', fallback=True)
216 True
217 >>> config['DEFAULT']['BatchMode'] = 'no'
218 >>> topsecret.getboolean('BatchMode', fallback=True)
219 False
220
Łukasz Langa26d513c2010-11-10 18:57:39 +0000221
222Supported INI File Structure
223----------------------------
224
Georg Brandl96a60ae2010-07-28 13:13:46 +0000225A configuration file consists of sections, each led by a ``[section]`` header,
Fred Drakea4923622010-08-09 12:52:45 +0000226followed by key/value entries separated by a specific string (``=`` or ``:`` by
Georg Brandlbb27c122010-11-11 07:26:40 +0000227default [1]_). By default, section names are case sensitive but keys are not
Fred Drake5a7c11f2010-11-13 05:24:17 +0000228[1]_. Leading and trailing whitespace is removed from keys and values.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000229Values can be omitted, in which case the key/value delimiter may also be left
230out. Values can also span multiple lines, as long as they are indented deeper
231than the first line of the value. Depending on the parser's mode, blank lines
232may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000233
Fred Drake5a7c11f2010-11-13 05:24:17 +0000234Configuration files may include comments, prefixed by specific
235characters (``#`` and ``;`` by default [1]_). Comments may appear on
Łukasz Langab25a7912010-12-17 01:32:29 +0000236their own on an otherwise empty line, possibly indented. [1]_
Georg Brandl96a60ae2010-07-28 13:13:46 +0000237
Georg Brandlbb27c122010-11-11 07:26:40 +0000238For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000239
Georg Brandlbb27c122010-11-11 07:26:40 +0000240.. code-block:: ini
Georg Brandl116aa622007-08-15 14:28:22 +0000241
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000242 [Simple Values]
Łukasz Langab25a7912010-12-17 01:32:29 +0000243 key=value
244 spaces in keys=allowed
245 spaces in values=allowed as well
246 spaces around the delimiter = obviously
247 you can also use : to delimit keys from values
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000248
249 [All Values Are Strings]
250 values like this: 1000000
251 or this: 3.14159265359
252 are they treated as numbers? : no
253 integers, floats and booleans are held as: strings
254 can use the API to get converted values directly: true
Georg Brandl116aa622007-08-15 14:28:22 +0000255
Georg Brandl96a60ae2010-07-28 13:13:46 +0000256 [Multiline Values]
257 chorus: I'm a lumberjack, and I'm okay
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000258 I sleep all night and I work all day
Georg Brandl116aa622007-08-15 14:28:22 +0000259
Georg Brandl96a60ae2010-07-28 13:13:46 +0000260 [No Values]
261 key_without_value
262 empty string value here =
Georg Brandl116aa622007-08-15 14:28:22 +0000263
Łukasz Langab25a7912010-12-17 01:32:29 +0000264 [You can use comments]
265 # like this
266 ; or this
267
268 # By default only in an empty line.
269 # Inline comments can be harmful because they prevent users
270 # from using the delimiting characters as parts of values.
271 # That being said, this can be customized.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000272
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000273 [Sections Can Be Indented]
274 can_values_be_as_well = True
275 does_that_mean_anything_special = False
276 purpose = formatting for readability
277 multiline_values = are
278 handled just fine as
279 long as they are indented
280 deeper than the first line
281 of a value
282 # Did I mention we can indent comments, too?
Georg Brandl116aa622007-08-15 14:28:22 +0000283
Georg Brandl96a60ae2010-07-28 13:13:46 +0000284
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000285Interpolation of values
286-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000287
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000288On top of the core functionality, :class:`ConfigParser` supports
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000289interpolation. This means values can be preprocessed before returning them
290from ``get()`` calls.
291
292.. class:: BasicInterpolation()
293
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000294 The default implementation used by :class:`ConfigParser`. It enables
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000295 values to contain format strings which refer to other values in the same
296 section, or values in the special default section [1]_. Additional default
297 values can be provided on initialization.
298
299 For example:
300
301 .. code-block:: ini
302
303 [Paths]
304 home_dir: /Users
305 my_dir: %(home_dir)s/lumberjack
306 my_pictures: %(my_dir)s/Pictures
307
308
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000309 In the example above, :class:`ConfigParser` with *interpolation* set to
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000310 ``BasicInterpolation()`` would resolve ``%(home_dir)s`` to the value of
311 ``home_dir`` (``/Users`` in this case). ``%(my_dir)s`` in effect would
312 resolve to ``/Users/lumberjack``. All interpolations are done on demand so
313 keys used in the chain of references do not have to be specified in any
314 specific order in the configuration file.
315
316 With ``interpolation`` set to ``None``, the parser would simply return
317 ``%(my_dir)s/Pictures`` as the value of ``my_pictures`` and
318 ``%(home_dir)s/lumberjack`` as the value of ``my_dir``.
319
320.. class:: ExtendedInterpolation()
321
322 An alternative handler for interpolation which implements a more advanced
Łukasz Langa34cea142014-09-14 23:37:03 -0700323 syntax, used for instance in ``zc.buildout``. Extended interpolation is
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000324 using ``${section:option}`` to denote a value from a foreign section.
Łukasz Langa34cea142014-09-14 23:37:03 -0700325 Interpolation can span multiple levels. For convenience, if the
326 ``section:`` part is omitted, interpolation defaults to the current section
327 (and possibly the default values from the special section).
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000328
329 For example, the configuration specified above with basic interpolation,
330 would look like this with extended interpolation:
331
332 .. code-block:: ini
333
334 [Paths]
335 home_dir: /Users
336 my_dir: ${home_dir}/lumberjack
337 my_pictures: ${my_dir}/Pictures
338
339 Values from other sections can be fetched as well:
340
341 .. code-block:: ini
342
343 [Common]
344 home_dir: /Users
345 library_dir: /Library
346 system_dir: /System
347 macports_dir: /opt/local
348
349 [Frameworks]
350 Python: 3.2
351 path: ${Common:system_dir}/Library/Frameworks/
352
353 [Arthur]
354 nickname: Two Sheds
355 last_name: Jackson
356 my_dir: ${Common:home_dir}/twosheds
357 my_pictures: ${my_dir}/Pictures
358 python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
Georg Brandlbb27c122010-11-11 07:26:40 +0000359
Łukasz Langa26d513c2010-11-10 18:57:39 +0000360Mapping Protocol Access
361-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000362
Łukasz Langa26d513c2010-11-10 18:57:39 +0000363.. versionadded:: 3.2
Georg Brandl96a60ae2010-07-28 13:13:46 +0000364
Łukasz Langa26d513c2010-11-10 18:57:39 +0000365Mapping protocol access is a generic name for functionality that enables using
Georg Brandlbb27c122010-11-11 07:26:40 +0000366custom objects as if they were dictionaries. In case of :mod:`configparser`,
Łukasz Langa26d513c2010-11-10 18:57:39 +0000367the mapping interface implementation is using the
368``parser['section']['option']`` notation.
369
370``parser['section']`` in particular returns a proxy for the section's data in
Georg Brandlbb27c122010-11-11 07:26:40 +0000371the parser. This means that the values are not copied but they are taken from
372the original parser on demand. What's even more important is that when values
Łukasz Langa26d513c2010-11-10 18:57:39 +0000373are changed on a section proxy, they are actually mutated in the original
374parser.
375
376:mod:`configparser` objects behave as close to actual dictionaries as possible.
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300377The mapping interface is complete and adheres to the
378:class:`~collections.abc.MutableMapping` ABC.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000379However, there are a few differences that should be taken into account:
380
Georg Brandlbb27c122010-11-11 07:26:40 +0000381* By default, all keys in sections are accessible in a case-insensitive manner
382 [1]_. E.g. ``for option in parser["section"]`` yields only ``optionxform``'ed
383 option key names. This means lowercased keys by default. At the same time,
Fred Drake5a7c11f2010-11-13 05:24:17 +0000384 for a section that holds the key ``'a'``, both expressions return ``True``::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000385
Georg Brandlbb27c122010-11-11 07:26:40 +0000386 "a" in parser["section"]
387 "A" in parser["section"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000388
Georg Brandlbb27c122010-11-11 07:26:40 +0000389* All sections include ``DEFAULTSECT`` values as well which means that
390 ``.clear()`` on a section may not leave the section visibly empty. This is
Łukasz Langa26d513c2010-11-10 18:57:39 +0000391 because default values cannot be deleted from the section (because technically
Donald Stufft8b852f12014-05-20 12:58:38 -0400392 they are not there). If they are overridden in the section, deleting causes
Georg Brandlbb27c122010-11-11 07:26:40 +0000393 the default value to be visible again. Trying to delete a default value
394 causes a ``KeyError``.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000395
Łukasz Langa3a8479a2012-12-31 03:38:39 +0100396* ``DEFAULTSECT`` cannot be removed from the parser:
397
398 * trying to delete it raises ``ValueError``,
399
400 * ``parser.clear()`` leaves it intact,
401
402 * ``parser.popitem()`` never returns it.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000403
Łukasz Langa71b37a52010-12-17 21:56:32 +0000404* ``parser.get(section, option, **kwargs)`` - the second argument is **not**
Łukasz Langa34cea142014-09-14 23:37:03 -0700405 a fallback value. Note however that the section-level ``get()`` methods are
Łukasz Langa71b37a52010-12-17 21:56:32 +0000406 compatible both with the mapping protocol and the classic configparser API.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000407
Łukasz Langa71b37a52010-12-17 21:56:32 +0000408* ``parser.items()`` is compatible with the mapping protocol (returns a list of
409 *section_name*, *section_proxy* pairs including the DEFAULTSECT). However,
410 this method can also be invoked with arguments: ``parser.items(section, raw,
Łukasz Langa34cea142014-09-14 23:37:03 -0700411 vars)``. The latter call returns a list of *option*, *value* pairs for
Łukasz Langa71b37a52010-12-17 21:56:32 +0000412 a specified ``section``, with all interpolations expanded (unless
413 ``raw=True`` is provided).
Łukasz Langa26d513c2010-11-10 18:57:39 +0000414
415The mapping protocol is implemented on top of the existing legacy API so that
Łukasz Langa71b37a52010-12-17 21:56:32 +0000416subclasses overriding the original interface still should have mappings working
417as expected.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000418
Georg Brandlbb27c122010-11-11 07:26:40 +0000419
Łukasz Langa26d513c2010-11-10 18:57:39 +0000420Customizing Parser Behaviour
421----------------------------
422
423There are nearly as many INI format variants as there are applications using it.
424:mod:`configparser` goes a long way to provide support for the largest sensible
Georg Brandlbb27c122010-11-11 07:26:40 +0000425set of INI styles available. The default functionality is mainly dictated by
Łukasz Langa26d513c2010-11-10 18:57:39 +0000426historical background and it's very likely that you will want to customize some
427of the features.
428
Fred Drake5a7c11f2010-11-13 05:24:17 +0000429The most common way to change the way a specific config parser works is to use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000430the :meth:`__init__` options:
431
432* *defaults*, default value: ``None``
433
434 This option accepts a dictionary of key-value pairs which will be initially
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000435 put in the ``DEFAULT`` section. This makes for an elegant way to support
436 concise configuration files that don't specify values which are the same as
437 the documented default.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000438
Fred Drake5a7c11f2010-11-13 05:24:17 +0000439 Hint: if you want to specify default values for a specific section, use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000440 :meth:`read_dict` before you read the actual file.
441
442* *dict_type*, default value: :class:`collections.OrderedDict`
443
444 This option has a major impact on how the mapping protocol will behave and how
Fred Drake5a7c11f2010-11-13 05:24:17 +0000445 the written configuration files look. With the default ordered
Łukasz Langa26d513c2010-11-10 18:57:39 +0000446 dictionary, every section is stored in the order they were added to the
Georg Brandlbb27c122010-11-11 07:26:40 +0000447 parser. Same goes for options within sections.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000448
449 An alternative dictionary type can be used for example to sort sections and
Georg Brandlbb27c122010-11-11 07:26:40 +0000450 options on write-back. You can also use a regular dictionary for performance
Łukasz Langa26d513c2010-11-10 18:57:39 +0000451 reasons.
452
453 Please note: there are ways to add a set of key-value pairs in a single
Georg Brandlbb27c122010-11-11 07:26:40 +0000454 operation. When you use a regular dictionary in those operations, the order
455 of the keys may be random. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000456
Łukasz Langa26d513c2010-11-10 18:57:39 +0000457 .. doctest::
458
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000459 >>> parser = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000460 >>> parser.read_dict({'section1': {'key1': 'value1',
461 ... 'key2': 'value2',
462 ... 'key3': 'value3'},
463 ... 'section2': {'keyA': 'valueA',
464 ... 'keyB': 'valueB',
465 ... 'keyC': 'valueC'},
466 ... 'section3': {'foo': 'x',
467 ... 'bar': 'y',
468 ... 'baz': 'z'}
469 ... })
470 >>> parser.sections()
471 ['section3', 'section2', 'section1']
472 >>> [option for option in parser['section3']]
473 ['baz', 'foo', 'bar']
Łukasz Langa26d513c2010-11-10 18:57:39 +0000474
475 In these operations you need to use an ordered dictionary as well:
476
Łukasz Langa26d513c2010-11-10 18:57:39 +0000477 .. doctest::
478
Georg Brandlbb27c122010-11-11 07:26:40 +0000479 >>> from collections import OrderedDict
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000480 >>> parser = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000481 >>> parser.read_dict(
482 ... OrderedDict((
483 ... ('s1',
484 ... OrderedDict((
485 ... ('1', '2'),
486 ... ('3', '4'),
487 ... ('5', '6'),
488 ... ))
489 ... ),
490 ... ('s2',
491 ... OrderedDict((
492 ... ('a', 'b'),
493 ... ('c', 'd'),
494 ... ('e', 'f'),
495 ... ))
496 ... ),
497 ... ))
498 ... )
499 >>> parser.sections()
500 ['s1', 's2']
501 >>> [option for option in parser['s1']]
502 ['1', '3', '5']
503 >>> [option for option in parser['s2'].values()]
504 ['b', 'd', 'f']
Łukasz Langa26d513c2010-11-10 18:57:39 +0000505
506* *allow_no_value*, default value: ``False``
507
508 Some configuration files are known to include settings without values, but
509 which otherwise conform to the syntax supported by :mod:`configparser`. The
Fred Drake5a7c11f2010-11-13 05:24:17 +0000510 *allow_no_value* parameter to the constructor can be used to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000511 indicate that such values should be accepted:
512
Łukasz Langa26d513c2010-11-10 18:57:39 +0000513 .. doctest::
514
Georg Brandlbb27c122010-11-11 07:26:40 +0000515 >>> import configparser
Łukasz Langa26d513c2010-11-10 18:57:39 +0000516
Georg Brandlbb27c122010-11-11 07:26:40 +0000517 >>> sample_config = """
518 ... [mysqld]
519 ... user = mysql
520 ... pid-file = /var/run/mysqld/mysqld.pid
521 ... skip-external-locking
522 ... old_passwords = 1
523 ... skip-bdb
Łukasz Langab25a7912010-12-17 01:32:29 +0000524 ... # we don't need ACID today
525 ... skip-innodb
Georg Brandlbb27c122010-11-11 07:26:40 +0000526 ... """
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000527 >>> config = configparser.ConfigParser(allow_no_value=True)
Georg Brandlbb27c122010-11-11 07:26:40 +0000528 >>> config.read_string(sample_config)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000529
Georg Brandlbb27c122010-11-11 07:26:40 +0000530 >>> # Settings with values are treated as before:
531 >>> config["mysqld"]["user"]
532 'mysql'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000533
Georg Brandlbb27c122010-11-11 07:26:40 +0000534 >>> # Settings without values provide None:
535 >>> config["mysqld"]["skip-bdb"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000536
Georg Brandlbb27c122010-11-11 07:26:40 +0000537 >>> # Settings which aren't specified still raise an error:
538 >>> config["mysqld"]["does-not-exist"]
539 Traceback (most recent call last):
540 ...
541 KeyError: 'does-not-exist'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000542
543* *delimiters*, default value: ``('=', ':')``
544
Łukasz Langa34cea142014-09-14 23:37:03 -0700545 Delimiters are substrings that delimit keys from values within a section.
546 The first occurrence of a delimiting substring on a line is considered
547 a delimiter. This means values (but not keys) can contain the delimiters.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000548
549 See also the *space_around_delimiters* argument to
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000550 :meth:`ConfigParser.write`.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000551
Łukasz Langab25a7912010-12-17 01:32:29 +0000552* *comment_prefixes*, default value: ``('#', ';')``
Łukasz Langa26d513c2010-11-10 18:57:39 +0000553
Łukasz Langab25a7912010-12-17 01:32:29 +0000554* *inline_comment_prefixes*, default value: ``None``
555
556 Comment prefixes are strings that indicate the start of a valid comment within
557 a config file. *comment_prefixes* are used only on otherwise empty lines
Łukasz Langa34cea142014-09-14 23:37:03 -0700558 (optionally indented) whereas *inline_comment_prefixes* can be used
559 after every valid value (e.g. section names, options and empty lines
560 as well). By default inline comments are disabled and ``'#'`` and
561 ``';'`` are used as prefixes for whole line comments.
Łukasz Langab25a7912010-12-17 01:32:29 +0000562
563 .. versionchanged:: 3.2
564 In previous versions of :mod:`configparser` behaviour matched
565 ``comment_prefixes=('#',';')`` and ``inline_comment_prefixes=(';',)``.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000566
567 Please note that config parsers don't support escaping of comment prefixes so
Łukasz Langab25a7912010-12-17 01:32:29 +0000568 using *inline_comment_prefixes* may prevent users from specifying option
Łukasz Langa34cea142014-09-14 23:37:03 -0700569 values with characters used as comment prefixes. When in doubt, avoid
570 setting *inline_comment_prefixes*. In any circumstances, the only way of
571 storing comment prefix characters at the beginning of a line in multiline
572 values is to interpolate the prefix, for example::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000573
Łukasz Langab25a7912010-12-17 01:32:29 +0000574 >>> from configparser import ConfigParser, ExtendedInterpolation
575 >>> parser = ConfigParser(interpolation=ExtendedInterpolation())
576 >>> # the default BasicInterpolation could be used as well
577 >>> parser.read_string("""
578 ... [DEFAULT]
579 ... hash = #
580 ...
581 ... [hashes]
582 ... shebang =
583 ... ${hash}!/usr/bin/env python
584 ... ${hash} -*- coding: utf-8 -*-
585 ...
586 ... extensions =
587 ... enabled_extension
588 ... another_extension
589 ... #disabled_by_comment
590 ... yet_another_extension
591 ...
592 ... interpolation not necessary = if # is not at line start
593 ... even in multiline values = line #1
594 ... line #2
595 ... line #3
596 ... """)
597 >>> print(parser['hashes']['shebang'])
Łukasz Langa26d513c2010-11-10 18:57:39 +0000598
Łukasz Langab25a7912010-12-17 01:32:29 +0000599 #!/usr/bin/env python
600 # -*- coding: utf-8 -*-
601 >>> print(parser['hashes']['extensions'])
602
603 enabled_extension
604 another_extension
605 yet_another_extension
606 >>> print(parser['hashes']['interpolation not necessary'])
607 if # is not at line start
608 >>> print(parser['hashes']['even in multiline values'])
609 line #1
610 line #2
611 line #3
612
613* *strict*, default value: ``True``
614
615 When set to ``True``, the parser will not allow for any section or option
Łukasz Langa26d513c2010-11-10 18:57:39 +0000616 duplicates while reading from a single source (using :meth:`read_file`,
Łukasz Langa34cea142014-09-14 23:37:03 -0700617 :meth:`read_string` or :meth:`read_dict`). It is recommended to use strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000618 parsers in new applications.
619
Łukasz Langab25a7912010-12-17 01:32:29 +0000620 .. versionchanged:: 3.2
621 In previous versions of :mod:`configparser` behaviour matched
622 ``strict=False``.
623
Łukasz Langa26d513c2010-11-10 18:57:39 +0000624* *empty_lines_in_values*, default value: ``True``
625
Fred Drake5a7c11f2010-11-13 05:24:17 +0000626 In config parsers, values can span multiple lines as long as they are
627 indented more than the key that holds them. By default parsers also let
628 empty lines to be parts of values. At the same time, keys can be arbitrarily
629 indented themselves to improve readability. In consequence, when
630 configuration files get big and complex, it is easy for the user to lose
631 track of the file structure. Take for instance:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000632
Georg Brandlbb27c122010-11-11 07:26:40 +0000633 .. code-block:: ini
Łukasz Langa26d513c2010-11-10 18:57:39 +0000634
Georg Brandlbb27c122010-11-11 07:26:40 +0000635 [Section]
636 key = multiline
637 value with a gotcha
Łukasz Langa26d513c2010-11-10 18:57:39 +0000638
Georg Brandlbb27c122010-11-11 07:26:40 +0000639 this = is still a part of the multiline value of 'key'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000640
Georg Brandlbb27c122010-11-11 07:26:40 +0000641 This can be especially problematic for the user to see if she's using a
642 proportional font to edit the file. That is why when your application does
643 not need values with empty lines, you should consider disallowing them. This
644 will make empty lines split keys every time. In the example above, it would
Łukasz Langa26d513c2010-11-10 18:57:39 +0000645 produce two keys, ``key`` and ``this``.
646
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000647* *default_section*, default value: ``configparser.DEFAULTSECT`` (that is:
648 ``"DEFAULT"``)
649
650 The convention of allowing a special section of default values for other
651 sections or interpolation purposes is a powerful concept of this library,
Łukasz Langa34cea142014-09-14 23:37:03 -0700652 letting users create complex declarative configurations. This section is
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000653 normally called ``"DEFAULT"`` but this can be customized to point to any
Łukasz Langa34cea142014-09-14 23:37:03 -0700654 other valid section name. Some typical values include: ``"general"`` or
655 ``"common"``. The name provided is used for recognizing default sections
656 when reading from any source and is used when writing configuration back to
657 a file. Its current value can be retrieved using the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000658 ``parser_instance.default_section`` attribute and may be modified at runtime
659 (i.e. to convert files from one format to another).
660
661* *interpolation*, default value: ``configparser.BasicInterpolation``
662
663 Interpolation behaviour may be customized by providing a custom handler
664 through the *interpolation* argument. ``None`` can be used to turn off
665 interpolation completely, ``ExtendedInterpolation()`` provides a more
Łukasz Langa34cea142014-09-14 23:37:03 -0700666 advanced variant inspired by ``zc.buildout``. More on the subject in the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000667 `dedicated documentation section <#interpolation-of-values>`_.
Łukasz Langab25a7912010-12-17 01:32:29 +0000668 :class:`RawConfigParser` has a default value of ``None``.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000669
Łukasz Langa26d513c2010-11-10 18:57:39 +0000670
Fred Drake5a7c11f2010-11-13 05:24:17 +0000671More advanced customization may be achieved by overriding default values of
672these parser attributes. The defaults are defined on the classes, so they
Donald Stufft8b852f12014-05-20 12:58:38 -0400673may be overridden by subclasses or by attribute assignment.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000674
Fred Drake5a7c11f2010-11-13 05:24:17 +0000675.. attribute:: BOOLEAN_STATES
Łukasz Langa26d513c2010-11-10 18:57:39 +0000676
677 By default when using :meth:`getboolean`, config parsers consider the
678 following values ``True``: ``'1'``, ``'yes'``, ``'true'``, ``'on'`` and the
Georg Brandlbb27c122010-11-11 07:26:40 +0000679 following values ``False``: ``'0'``, ``'no'``, ``'false'``, ``'off'``. You
680 can override this by specifying a custom dictionary of strings and their
Fred Drake5a7c11f2010-11-13 05:24:17 +0000681 Boolean outcomes. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000682
Łukasz Langa26d513c2010-11-10 18:57:39 +0000683 .. doctest::
684
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000685 >>> custom = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000686 >>> custom['section1'] = {'funky': 'nope'}
687 >>> custom['section1'].getboolean('funky')
688 Traceback (most recent call last):
689 ...
690 ValueError: Not a boolean: nope
691 >>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}
692 >>> custom['section1'].getboolean('funky')
693 False
Łukasz Langa26d513c2010-11-10 18:57:39 +0000694
Fred Drake5a7c11f2010-11-13 05:24:17 +0000695 Other typical Boolean pairs include ``accept``/``reject`` or
Łukasz Langa26d513c2010-11-10 18:57:39 +0000696 ``enabled``/``disabled``.
697
Fred Drake5a7c11f2010-11-13 05:24:17 +0000698.. method:: optionxform(option)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000699
Fred Drake5a7c11f2010-11-13 05:24:17 +0000700 This method transforms option names on every read, get, or set
701 operation. The default converts the name to lowercase. This also
702 means that when a configuration file gets written, all keys will be
703 lowercase. Override this method if that's unsuitable.
704 For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000705
Łukasz Langa26d513c2010-11-10 18:57:39 +0000706 .. doctest::
707
Georg Brandlbb27c122010-11-11 07:26:40 +0000708 >>> config = """
709 ... [Section1]
710 ... Key = Value
711 ...
712 ... [Section2]
713 ... AnotherKey = Value
714 ... """
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000715 >>> typical = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000716 >>> typical.read_string(config)
717 >>> list(typical['Section1'].keys())
718 ['key']
719 >>> list(typical['Section2'].keys())
720 ['anotherkey']
721 >>> custom = configparser.RawConfigParser()
722 >>> custom.optionxform = lambda option: option
723 >>> custom.read_string(config)
724 >>> list(custom['Section1'].keys())
725 ['Key']
726 >>> list(custom['Section2'].keys())
727 ['AnotherKey']
728
Łukasz Langa66c908e2011-01-28 11:57:30 +0000729.. attribute:: SECTCRE
730
Łukasz Langa34cea142014-09-14 23:37:03 -0700731 A compiled regular expression used to parse section headers. The default
732 matches ``[section]`` to the name ``"section"``. Whitespace is considered
733 part of the section name, thus ``[ larch ]`` will be read as a section of
734 name ``" larch "``. Override this attribute if that's unsuitable. For
735 example:
Łukasz Langa66c908e2011-01-28 11:57:30 +0000736
737 .. doctest::
738
739 >>> config = """
740 ... [Section 1]
741 ... option = value
742 ...
743 ... [ Section 2 ]
744 ... another = val
745 ... """
746 >>> typical = ConfigParser()
747 >>> typical.read_string(config)
748 >>> typical.sections()
749 ['Section 1', ' Section 2 ']
750 >>> custom = ConfigParser()
751 >>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]")
752 >>> custom.read_string(config)
753 >>> custom.sections()
754 ['Section 1', 'Section 2']
755
756 .. note::
757
758 While ConfigParser objects also use an ``OPTCRE`` attribute for recognizing
759 option lines, it's not recommended to override it because that would
760 interfere with constructor options *allow_no_value* and *delimiters*.
761
Łukasz Langa26d513c2010-11-10 18:57:39 +0000762
763Legacy API Examples
764-------------------
765
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000766Mainly because of backwards compatibility concerns, :mod:`configparser`
767provides also a legacy API with explicit ``get``/``set`` methods. While there
768are valid use cases for the methods outlined below, mapping protocol access is
769preferred for new projects. The legacy API is at times more advanced,
770low-level and downright counterintuitive.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000771
772An example of writing to a configuration file::
773
774 import configparser
775
776 config = configparser.RawConfigParser()
777
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000778 # Please note that using RawConfigParser's set functions, you can assign
779 # non-string values to keys internally, but will receive an error when
780 # attempting to write to a file or when you get it in non-raw mode. Setting
781 # values using the mapping protocol or ConfigParser's set() does not allow
782 # such assignments to take place.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000783 config.add_section('Section1')
R David Murray1a1883d2012-09-29 14:40:23 -0400784 config.set('Section1', 'an_int', '15')
785 config.set('Section1', 'a_bool', 'true')
786 config.set('Section1', 'a_float', '3.1415')
Łukasz Langa26d513c2010-11-10 18:57:39 +0000787 config.set('Section1', 'baz', 'fun')
788 config.set('Section1', 'bar', 'Python')
789 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
790
791 # Writing our configuration file to 'example.cfg'
792 with open('example.cfg', 'w') as configfile:
793 config.write(configfile)
794
795An example of reading the configuration file again::
796
797 import configparser
798
799 config = configparser.RawConfigParser()
800 config.read('example.cfg')
801
802 # getfloat() raises an exception if the value is not a float
803 # getint() and getboolean() also do this for their respective types
R David Murray1a1883d2012-09-29 14:40:23 -0400804 a_float = config.getfloat('Section1', 'a_float')
805 an_int = config.getint('Section1', 'an_int')
806 print(a_float + an_int)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000807
808 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
809 # This is because we are using a RawConfigParser().
R David Murray1a1883d2012-09-29 14:40:23 -0400810 if config.getboolean('Section1', 'a_bool'):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000811 print(config.get('Section1', 'foo'))
812
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000813To get interpolation, use :class:`ConfigParser`::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000814
815 import configparser
816
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000817 cfg = configparser.ConfigParser()
Łukasz Langa26d513c2010-11-10 18:57:39 +0000818 cfg.read('example.cfg')
819
Éric Araujo941afed2011-09-01 02:47:34 +0200820 # Set the optional *raw* argument of get() to True if you wish to disable
Łukasz Langa26d513c2010-11-10 18:57:39 +0000821 # interpolation in a single get operation.
822 print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!"
823 print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!"
824
Éric Araujo941afed2011-09-01 02:47:34 +0200825 # The optional *vars* argument is a dict with members that will take
Łukasz Langa26d513c2010-11-10 18:57:39 +0000826 # precedence in interpolation.
827 print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation',
828 'baz': 'evil'}))
829
Éric Araujo941afed2011-09-01 02:47:34 +0200830 # The optional *fallback* argument can be used to provide a fallback value
Łukasz Langa26d513c2010-11-10 18:57:39 +0000831 print(cfg.get('Section1', 'foo'))
832 # -> "Python is fun!"
833
834 print(cfg.get('Section1', 'foo', fallback='Monty is not.'))
835 # -> "Python is fun!"
836
837 print(cfg.get('Section1', 'monster', fallback='No such things as monsters.'))
838 # -> "No such things as monsters."
839
840 # A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError
841 # but we can also use:
842
843 print(cfg.get('Section1', 'monster', fallback=None))
844 # -> None
845
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000846Default values are available in both types of ConfigParsers. They are used in
847interpolation if an option used is not defined elsewhere. ::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000848
849 import configparser
850
851 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000852 config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'})
Łukasz Langa26d513c2010-11-10 18:57:39 +0000853 config.read('example.cfg')
854
855 print(config.get('Section1', 'foo')) # -> "Python is fun!"
856 config.remove_option('Section1', 'bar')
857 config.remove_option('Section1', 'baz')
858 print(config.get('Section1', 'foo')) # -> "Life is hard!"
859
Georg Brandlbb27c122010-11-11 07:26:40 +0000860
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000861.. _configparser-objects:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000862
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000863ConfigParser Objects
864--------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000865
Łukasz Langab25a7912010-12-17 01:32:29 +0000866.. class:: ConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation())
Georg Brandl116aa622007-08-15 14:28:22 +0000867
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000868 The main configuration parser. When *defaults* is given, it is initialized
Georg Brandl96a60ae2010-07-28 13:13:46 +0000869 into the dictionary of intrinsic defaults. When *dict_type* is given, it
870 will be used to create the dictionary objects for the list of sections, for
871 the options within a section, and for the default values.
872
Fred Drake5a7c11f2010-11-13 05:24:17 +0000873 When *delimiters* is given, it is used as the set of substrings that
Georg Brandl96a60ae2010-07-28 13:13:46 +0000874 divide keys from values. When *comment_prefixes* is given, it will be used
Łukasz Langab25a7912010-12-17 01:32:29 +0000875 as the set of substrings that prefix comments in otherwise empty lines.
Łukasz Langa34cea142014-09-14 23:37:03 -0700876 Comments can be indented. When *inline_comment_prefixes* is given, it will
877 be used as the set of substrings that prefix comments in non-empty lines.
Łukasz Langab25a7912010-12-17 01:32:29 +0000878
Łukasz Langab25a7912010-12-17 01:32:29 +0000879 When *strict* is ``True`` (the default), the parser won't allow for
Fred Drakea4923622010-08-09 12:52:45 +0000880 any section or option duplicates while reading from a single source (file,
881 string or dictionary), raising :exc:`DuplicateSectionError` or
Fred Drake5a7c11f2010-11-13 05:24:17 +0000882 :exc:`DuplicateOptionError`. When *empty_lines_in_values* is ``False``
Fred Drakea4923622010-08-09 12:52:45 +0000883 (default: ``True``), each empty line marks the end of an option. Otherwise,
884 internal empty lines of a multiline option are kept as part of the value.
885 When *allow_no_value* is ``True`` (default: ``False``), options without
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000886 values are accepted; the value held for these is ``None`` and they are
887 serialized without the trailing delimiter.
Fred Drake03c44a32010-02-19 06:08:41 +0000888
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000889 When *default_section* is given, it specifies the name for the special
890 section holding default values for other sections and interpolation purposes
Łukasz Langa34cea142014-09-14 23:37:03 -0700891 (normally named ``"DEFAULT"``). This value can be retrieved and changed on
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000892 runtime using the ``default_section`` instance attribute.
893
894 Interpolation behaviour may be customized by providing a custom handler
895 through the *interpolation* argument. ``None`` can be used to turn off
896 interpolation completely, ``ExtendedInterpolation()`` provides a more
Łukasz Langa34cea142014-09-14 23:37:03 -0700897 advanced variant inspired by ``zc.buildout``. More on the subject in the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000898 `dedicated documentation section <#interpolation-of-values>`_.
899
900 All option names used in interpolation will be passed through the
901 :meth:`optionxform` method just like any other option name reference. For
902 example, using the default implementation of :meth:`optionxform` (which
903 converts option names to lower case), the values ``foo %(bar)s`` and ``foo
904 %(BAR)s`` are equivalent.
Georg Brandl116aa622007-08-15 14:28:22 +0000905
Raymond Hettinger231b7f12009-03-03 00:23:19 +0000906 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +0000907 The default *dict_type* is :class:`collections.OrderedDict`.
908
Fred Drake03c44a32010-02-19 06:08:41 +0000909 .. versionchanged:: 3.2
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000910 *allow_no_value*, *delimiters*, *comment_prefixes*, *strict*,
911 *empty_lines_in_values*, *default_section* and *interpolation* were
912 added.
Georg Brandl116aa622007-08-15 14:28:22 +0000913
Fred Drake03c44a32010-02-19 06:08:41 +0000914
Georg Brandlbb27c122010-11-11 07:26:40 +0000915 .. method:: defaults()
Georg Brandl116aa622007-08-15 14:28:22 +0000916
Georg Brandlbb27c122010-11-11 07:26:40 +0000917 Return a dictionary containing the instance-wide defaults.
Georg Brandl116aa622007-08-15 14:28:22 +0000918
919
Georg Brandlbb27c122010-11-11 07:26:40 +0000920 .. method:: sections()
Georg Brandl116aa622007-08-15 14:28:22 +0000921
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000922 Return a list of the sections available; the *default section* is not
923 included in the list.
Georg Brandl116aa622007-08-15 14:28:22 +0000924
925
Georg Brandlbb27c122010-11-11 07:26:40 +0000926 .. method:: add_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000927
Georg Brandlbb27c122010-11-11 07:26:40 +0000928 Add a section named *section* to the instance. If a section by the given
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000929 name already exists, :exc:`DuplicateSectionError` is raised. If the
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000930 *default section* name is passed, :exc:`ValueError` is raised. The name
931 of the section must be a string; if not, :exc:`TypeError` is raised.
932
933 .. versionchanged:: 3.2
934 Non-string section names raise :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000935
Georg Brandl116aa622007-08-15 14:28:22 +0000936
Georg Brandlbb27c122010-11-11 07:26:40 +0000937 .. method:: has_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000938
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000939 Indicates whether the named *section* is present in the configuration.
940 The *default section* is not acknowledged.
Georg Brandl116aa622007-08-15 14:28:22 +0000941
Georg Brandl116aa622007-08-15 14:28:22 +0000942
Georg Brandlbb27c122010-11-11 07:26:40 +0000943 .. method:: options(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000944
Georg Brandlbb27c122010-11-11 07:26:40 +0000945 Return a list of options available in the specified *section*.
Georg Brandl116aa622007-08-15 14:28:22 +0000946
Georg Brandl116aa622007-08-15 14:28:22 +0000947
Georg Brandlbb27c122010-11-11 07:26:40 +0000948 .. method:: has_option(section, option)
Georg Brandl116aa622007-08-15 14:28:22 +0000949
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000950 If the given *section* exists, and contains the given *option*, return
Łukasz Langa34cea142014-09-14 23:37:03 -0700951 :const:`True`; otherwise return :const:`False`. If the specified
Łukasz Langa71b37a52010-12-17 21:56:32 +0000952 *section* is :const:`None` or an empty string, DEFAULT is assumed.
Georg Brandl116aa622007-08-15 14:28:22 +0000953
Georg Brandl116aa622007-08-15 14:28:22 +0000954
Georg Brandlbb27c122010-11-11 07:26:40 +0000955 .. method:: read(filenames, encoding=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000956
Georg Brandlbb27c122010-11-11 07:26:40 +0000957 Attempt to read and parse a list of filenames, returning a list of
958 filenames which were successfully parsed. If *filenames* is a string, it
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000959 is treated as a single filename. If a file named in *filenames* cannot
960 be opened, that file will be ignored. This is designed so that you can
961 specify a list of potential configuration file locations (for example,
962 the current directory, the user's home directory, and some system-wide
963 directory), and all existing configuration files in the list will be
964 read. If none of the named files exist, the :class:`ConfigParser`
965 instance will contain an empty dataset. An application which requires
966 initial values to be loaded from a file should load the required file or
967 files using :meth:`read_file` before calling :meth:`read` for any
968 optional files::
Georg Brandl116aa622007-08-15 14:28:22 +0000969
Georg Brandlbb27c122010-11-11 07:26:40 +0000970 import configparser, os
Georg Brandl8dcaa732010-07-29 12:17:40 +0000971
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000972 config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000973 config.read_file(open('defaults.cfg'))
974 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
975 encoding='cp1250')
Georg Brandl116aa622007-08-15 14:28:22 +0000976
Georg Brandlbb27c122010-11-11 07:26:40 +0000977 .. versionadded:: 3.2
978 The *encoding* parameter. Previously, all files were read using the
979 default encoding for :func:`open`.
Georg Brandl116aa622007-08-15 14:28:22 +0000980
Georg Brandl116aa622007-08-15 14:28:22 +0000981
Georg Brandlbb27c122010-11-11 07:26:40 +0000982 .. method:: read_file(f, source=None)
Georg Brandl73753d32009-09-22 13:53:14 +0000983
Łukasz Langadaab1c82011-04-27 18:10:05 +0200984 Read and parse configuration data from *f* which must be an iterable
Łukasz Langaba702da2011-04-28 12:02:05 +0200985 yielding Unicode strings (for example files opened in text mode).
Georg Brandl116aa622007-08-15 14:28:22 +0000986
Georg Brandlbb27c122010-11-11 07:26:40 +0000987 Optional argument *source* specifies the name of the file being read. If
Fred Drake5a7c11f2010-11-13 05:24:17 +0000988 not given and *f* has a :attr:`name` attribute, that is used for
989 *source*; the default is ``'<???>'``.
Fred Drakea4923622010-08-09 12:52:45 +0000990
Georg Brandlbb27c122010-11-11 07:26:40 +0000991 .. versionadded:: 3.2
Łukasz Langa43ae6192011-04-27 18:13:42 +0200992 Replaces :meth:`readfp`.
993
Georg Brandlbb27c122010-11-11 07:26:40 +0000994 .. method:: read_string(string, source='<string>')
Fred Drakea4923622010-08-09 12:52:45 +0000995
Fred Drake5a7c11f2010-11-13 05:24:17 +0000996 Parse configuration data from a string.
Fred Drakea4923622010-08-09 12:52:45 +0000997
Fred Drake5a7c11f2010-11-13 05:24:17 +0000998 Optional argument *source* specifies a context-specific name of the
999 string passed. If not given, ``'<string>'`` is used. This should
1000 commonly be a filesystem path or a URL.
Fred Drakea4923622010-08-09 12:52:45 +00001001
Georg Brandlbb27c122010-11-11 07:26:40 +00001002 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +00001003
Fred Drakea4923622010-08-09 12:52:45 +00001004
Georg Brandlbb27c122010-11-11 07:26:40 +00001005 .. method:: read_dict(dictionary, source='<dict>')
Fred Drakea4923622010-08-09 12:52:45 +00001006
Łukasz Langa71b37a52010-12-17 21:56:32 +00001007 Load configuration from any object that provides a dict-like ``items()``
1008 method. Keys are section names, values are dictionaries with keys and
1009 values that should be present in the section. If the used dictionary
1010 type preserves order, sections and their keys will be added in order.
1011 Values are automatically converted to strings.
Fred Drakea4923622010-08-09 12:52:45 +00001012
Georg Brandlbb27c122010-11-11 07:26:40 +00001013 Optional argument *source* specifies a context-specific name of the
1014 dictionary passed. If not given, ``<dict>`` is used.
Georg Brandl116aa622007-08-15 14:28:22 +00001015
Łukasz Langa71b37a52010-12-17 21:56:32 +00001016 This method can be used to copy state between parsers.
1017
Georg Brandlbb27c122010-11-11 07:26:40 +00001018 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +00001019
Georg Brandl116aa622007-08-15 14:28:22 +00001020
Ezio Melottie927e252012-09-08 20:46:01 +03001021 .. method:: get(section, option, *, raw=False, vars=None[, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +00001022
Georg Brandlbb27c122010-11-11 07:26:40 +00001023 Get an *option* value for the named *section*. If *vars* is provided, it
1024 must be a dictionary. The *option* is looked up in *vars* (if provided),
1025 *section*, and in *DEFAULTSECT* in that order. If the key is not found
1026 and *fallback* is provided, it is used as a fallback value. ``None`` can
1027 be provided as a *fallback* value.
Georg Brandl470a1232010-07-29 14:17:12 +00001028
Georg Brandlbb27c122010-11-11 07:26:40 +00001029 All the ``'%'`` interpolations are expanded in the return values, unless
1030 the *raw* argument is true. Values for interpolation keys are looked up
1031 in the same manner as the option.
Georg Brandl116aa622007-08-15 14:28:22 +00001032
Georg Brandlbb27c122010-11-11 07:26:40 +00001033 .. versionchanged:: 3.2
1034 Arguments *raw*, *vars* and *fallback* are keyword only to protect
1035 users from trying to use the third argument as the *fallback* fallback
1036 (especially when using the mapping protocol).
Georg Brandl116aa622007-08-15 14:28:22 +00001037
Łukasz Langa26d513c2010-11-10 18:57:39 +00001038
Ezio Melottie927e252012-09-08 20:46:01 +03001039 .. method:: getint(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001040
Georg Brandlbb27c122010-11-11 07:26:40 +00001041 A convenience method which coerces the *option* in the specified *section*
1042 to an integer. See :meth:`get` for explanation of *raw*, *vars* and
1043 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001044
1045
Ezio Melottie927e252012-09-08 20:46:01 +03001046 .. method:: getfloat(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001047
Georg Brandlbb27c122010-11-11 07:26:40 +00001048 A convenience method which coerces the *option* in the specified *section*
1049 to a floating point number. See :meth:`get` for explanation of *raw*,
1050 *vars* and *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001051
1052
Ezio Melottie927e252012-09-08 20:46:01 +03001053 .. method:: getboolean(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001054
Georg Brandlbb27c122010-11-11 07:26:40 +00001055 A convenience method which coerces the *option* in the specified *section*
1056 to a Boolean value. Note that the accepted values for the option are
Fred Drake5a7c11f2010-11-13 05:24:17 +00001057 ``'1'``, ``'yes'``, ``'true'``, and ``'on'``, which cause this method to
1058 return ``True``, and ``'0'``, ``'no'``, ``'false'``, and ``'off'``, which
Georg Brandlbb27c122010-11-11 07:26:40 +00001059 cause it to return ``False``. These string values are checked in a
1060 case-insensitive manner. Any other value will cause it to raise
1061 :exc:`ValueError`. See :meth:`get` for explanation of *raw*, *vars* and
1062 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001063
1064
Ezio Melottie0add762012-09-14 06:32:35 +03001065 .. method:: items(raw=False, vars=None)
1066 items(section, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001067
Łukasz Langa71b37a52010-12-17 21:56:32 +00001068 When *section* is not given, return a list of *section_name*,
1069 *section_proxy* pairs, including DEFAULTSECT.
1070
1071 Otherwise, return a list of *name*, *value* pairs for the options in the
1072 given *section*. Optional arguments have the same meaning as for the
Georg Brandlbb27c122010-11-11 07:26:40 +00001073 :meth:`get` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001074
Łukasz Langa72547622011-05-09 18:49:42 +02001075 .. versionchanged:: 3.2
Łukasz Langa34cea142014-09-14 23:37:03 -07001076 Items present in *vars* no longer appear in the result. The previous
Łukasz Langa72547622011-05-09 18:49:42 +02001077 behaviour mixed actual parser options with variables provided for
1078 interpolation.
Georg Brandl116aa622007-08-15 14:28:22 +00001079
Georg Brandlbb27c122010-11-11 07:26:40 +00001080 .. method:: set(section, option, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001081
Georg Brandlbb27c122010-11-11 07:26:40 +00001082 If the given section exists, set the given option to the specified value;
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001083 otherwise raise :exc:`NoSectionError`. *option* and *value* must be
1084 strings; if not, :exc:`TypeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001085
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001086
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001087 .. method:: write(fileobject, space_around_delimiters=True)
1088
1089 Write a representation of the configuration to the specified :term:`file
1090 object`, which must be opened in text mode (accepting strings). This
1091 representation can be parsed by a future :meth:`read` call. If
1092 *space_around_delimiters* is true, delimiters between
1093 keys and values are surrounded by spaces.
1094
1095
1096 .. method:: remove_option(section, option)
1097
1098 Remove the specified *option* from the specified *section*. If the
1099 section does not exist, raise :exc:`NoSectionError`. If the option
1100 existed to be removed, return :const:`True`; otherwise return
1101 :const:`False`.
1102
1103
1104 .. method:: remove_section(section)
1105
1106 Remove the specified *section* from the configuration. If the section in
1107 fact existed, return ``True``. Otherwise return ``False``.
1108
1109
1110 .. method:: optionxform(option)
1111
1112 Transforms the option name *option* as found in an input file or as passed
1113 in by client code to the form that should be used in the internal
1114 structures. The default implementation returns a lower-case version of
1115 *option*; subclasses may override this or client code can set an attribute
1116 of this name on instances to affect this behavior.
1117
1118 You don't need to subclass the parser to use this method, you can also
1119 set it on an instance, to a function that takes a string argument and
1120 returns a string. Setting it to ``str``, for example, would make option
1121 names case sensitive::
1122
1123 cfgparser = ConfigParser()
1124 cfgparser.optionxform = str
1125
1126 Note that when reading configuration files, whitespace around the option
1127 names is stripped before :meth:`optionxform` is called.
1128
1129
1130 .. method:: readfp(fp, filename=None)
1131
1132 .. deprecated:: 3.2
1133 Use :meth:`read_file` instead.
1134
Łukasz Langaba702da2011-04-28 12:02:05 +02001135 .. versionchanged:: 3.2
1136 :meth:`readfp` now iterates on *f* instead of calling ``f.readline()``.
1137
1138 For existing code calling :meth:`readfp` with arguments which don't
1139 support iteration, the following generator may be used as a wrapper
1140 around the file-like object::
1141
1142 def readline_generator(f):
1143 line = f.readline()
1144 while line:
1145 yield line
1146 line = f.readline()
1147
1148 Instead of ``parser.readfp(f)`` use
1149 ``parser.read_file(readline_generator(f))``.
1150
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001151
1152.. data:: MAX_INTERPOLATION_DEPTH
1153
1154 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
1155 parameter is false. This is relevant only when the default *interpolation*
1156 is used.
1157
1158
1159.. _rawconfigparser-objects:
1160
1161RawConfigParser Objects
1162-----------------------
1163
Ezio Melottie927e252012-09-08 20:46:01 +03001164.. class:: RawConfigParser(defaults=None, dict_type=collections.OrderedDict, \
1165 allow_no_value=False, *, delimiters=('=', ':'), \
1166 comment_prefixes=('#', ';'), \
1167 inline_comment_prefixes=None, strict=True, \
1168 empty_lines_in_values=True, \
1169 default_section=configparser.DEFAULTSECT[, \
1170 interpolation])
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001171
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001172 Legacy variant of the :class:`ConfigParser` with interpolation disabled
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001173 by default and unsafe ``add_section`` and ``set`` methods.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001174
1175 .. note::
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001176 Consider using :class:`ConfigParser` instead which checks types of
Łukasz Langa34cea142014-09-14 23:37:03 -07001177 the values to be stored internally. If you don't want interpolation, you
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001178 can use ``ConfigParser(interpolation=None)``.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001179
1180
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001181 .. method:: add_section(section)
1182
1183 Add a section named *section* to the instance. If a section by the given
1184 name already exists, :exc:`DuplicateSectionError` is raised. If the
1185 *default section* name is passed, :exc:`ValueError` is raised.
1186
1187 Type of *section* is not checked which lets users create non-string named
Łukasz Langa34cea142014-09-14 23:37:03 -07001188 sections. This behaviour is unsupported and may cause internal errors.
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001189
1190
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001191 .. method:: set(section, option, value)
1192
1193 If the given section exists, set the given option to the specified value;
1194 otherwise raise :exc:`NoSectionError`. While it is possible to use
1195 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters
1196 set to true) for *internal* storage of non-string values, full
1197 functionality (including interpolation and output to files) can only be
1198 achieved using string values.
1199
1200 This method lets users assign non-string values to keys internally. This
1201 behaviour is unsupported and will cause errors when attempting to write
1202 to a file or get it in non-raw mode. **Use the mapping protocol API**
1203 which does not allow such assignments to take place.
1204
1205
Łukasz Langa26d513c2010-11-10 18:57:39 +00001206Exceptions
1207----------
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001208
Łukasz Langa26d513c2010-11-10 18:57:39 +00001209.. exception:: Error
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001210
Fred Drake5a7c11f2010-11-13 05:24:17 +00001211 Base class for all other :mod:`configparser` exceptions.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001212
Georg Brandl48310cd2009-01-03 21:18:54 +00001213
Łukasz Langa26d513c2010-11-10 18:57:39 +00001214.. exception:: NoSectionError
Georg Brandl48310cd2009-01-03 21:18:54 +00001215
Łukasz Langa26d513c2010-11-10 18:57:39 +00001216 Exception raised when a specified section is not found.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001217
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001218
Łukasz Langa26d513c2010-11-10 18:57:39 +00001219.. exception:: DuplicateSectionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001220
Łukasz Langa26d513c2010-11-10 18:57:39 +00001221 Exception raised if :meth:`add_section` is called with the name of a section
1222 that is already present or in strict parsers when a section if found more
1223 than once in a single input file, string or dictionary.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001224
Łukasz Langa26d513c2010-11-10 18:57:39 +00001225 .. versionadded:: 3.2
1226 Optional ``source`` and ``lineno`` attributes and arguments to
1227 :meth:`__init__` were added.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001228
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001229
Łukasz Langa26d513c2010-11-10 18:57:39 +00001230.. exception:: DuplicateOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001231
Łukasz Langa26d513c2010-11-10 18:57:39 +00001232 Exception raised by strict parsers if a single option appears twice during
1233 reading from a single file, string or dictionary. This catches misspellings
1234 and case sensitivity-related errors, e.g. a dictionary may have two keys
1235 representing the same case-insensitive configuration key.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001236
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001237
Łukasz Langa26d513c2010-11-10 18:57:39 +00001238.. exception:: NoOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001239
Łukasz Langa26d513c2010-11-10 18:57:39 +00001240 Exception raised when a specified option is not found in the specified
1241 section.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001242
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001243
Łukasz Langa26d513c2010-11-10 18:57:39 +00001244.. exception:: InterpolationError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001245
Łukasz Langa26d513c2010-11-10 18:57:39 +00001246 Base class for exceptions raised when problems occur performing string
1247 interpolation.
Georg Brandl48310cd2009-01-03 21:18:54 +00001248
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001249
Łukasz Langa26d513c2010-11-10 18:57:39 +00001250.. exception:: InterpolationDepthError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001251
Łukasz Langa26d513c2010-11-10 18:57:39 +00001252 Exception raised when string interpolation cannot be completed because the
Georg Brandlbb27c122010-11-11 07:26:40 +00001253 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
Łukasz Langa26d513c2010-11-10 18:57:39 +00001254 :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001255
Fred Drake03c44a32010-02-19 06:08:41 +00001256
Łukasz Langa26d513c2010-11-10 18:57:39 +00001257.. exception:: InterpolationMissingOptionError
Fred Drake03c44a32010-02-19 06:08:41 +00001258
Georg Brandlbb27c122010-11-11 07:26:40 +00001259 Exception raised when an option referenced from a value does not exist.
1260 Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001261
Fred Drake03c44a32010-02-19 06:08:41 +00001262
Łukasz Langa26d513c2010-11-10 18:57:39 +00001263.. exception:: InterpolationSyntaxError
Fred Drake03c44a32010-02-19 06:08:41 +00001264
Georg Brandlbb27c122010-11-11 07:26:40 +00001265 Exception raised when the source text into which substitutions are made does
1266 not conform to the required syntax. Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001267
Łukasz Langa26d513c2010-11-10 18:57:39 +00001268
1269.. exception:: MissingSectionHeaderError
1270
Georg Brandlbb27c122010-11-11 07:26:40 +00001271 Exception raised when attempting to parse a file which has no section
1272 headers.
Łukasz Langa26d513c2010-11-10 18:57:39 +00001273
1274
1275.. exception:: ParsingError
1276
1277 Exception raised when errors occur attempting to parse a file.
1278
1279 .. versionchanged:: 3.2
1280 The ``filename`` attribute and :meth:`__init__` argument were renamed to
1281 ``source`` for consistency.
1282
Georg Brandlbb27c122010-11-11 07:26:40 +00001283
1284.. rubric:: Footnotes
1285
1286.. [1] Config parsers allow for heavy customization. If you are interested in
1287 changing the behaviour outlined by the footnote reference, consult the
1288 `Customizing Parser Behaviour`_ section.