blob: 0b8212c16437096f29336a62670e6907034da4c5 [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
Georg Brandl116aa622007-08-15 14:28:22 +000014.. index::
15 pair: .ini; file
16 pair: configuration; file
17 single: ini file
18 single: Windows ini file
19
Łukasz Langa7f64c8a2010-12-16 01:16:22 +000020This module provides the :class:`ConfigParser` class which implements a basic
21configuration language which provides a structure similar to what's found in
22Microsoft Windows INI files. You can use this to write Python programs which
23can be customized by end users easily.
Georg Brandl116aa622007-08-15 14:28:22 +000024
Georg Brandle720c0a2009-04-27 16:20:50 +000025.. note::
Georg Brandl116aa622007-08-15 14:28:22 +000026
Georg Brandle720c0a2009-04-27 16:20:50 +000027 This library does *not* interpret or write the value-type prefixes used in
28 the Windows Registry extended version of INI syntax.
Georg Brandl116aa622007-08-15 14:28:22 +000029
Łukasz Langa26d513c2010-11-10 18:57:39 +000030.. seealso::
31
32 Module :mod:`shlex`
33 Support for a creating Unix shell-like mini-languages which can be used
34 as an alternate format for application configuration files.
35
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000036 Module :mod:`json`
37 The json module implements a subset of JavaScript syntax which can also
38 be used for this purpose.
39
Georg Brandlbb27c122010-11-11 07:26:40 +000040
Łukasz Langa26d513c2010-11-10 18:57:39 +000041Quick Start
42-----------
43
Georg Brandlbb27c122010-11-11 07:26:40 +000044Let's take a very basic configuration file that looks like this:
Łukasz Langa26d513c2010-11-10 18:57:39 +000045
Georg Brandlbb27c122010-11-11 07:26:40 +000046.. code-block:: ini
Łukasz Langa26d513c2010-11-10 18:57:39 +000047
Georg Brandlbb27c122010-11-11 07:26:40 +000048 [DEFAULT]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000049 ServerAliveInterval = 45
50 Compression = yes
51 CompressionLevel = 9
52 ForwardX11 = yes
Łukasz Langa26d513c2010-11-10 18:57:39 +000053
Georg Brandlbb27c122010-11-11 07:26:40 +000054 [bitbucket.org]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000055 User = hg
Łukasz Langa26d513c2010-11-10 18:57:39 +000056
Georg Brandlbb27c122010-11-11 07:26:40 +000057 [topsecret.server.com]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000058 Port = 50022
59 ForwardX11 = no
Łukasz Langa26d513c2010-11-10 18:57:39 +000060
Fred Drake5a7c11f2010-11-13 05:24:17 +000061The structure of INI files is described `in the following section
62<#supported-ini-file-structure>`_. Essentially, the file
Łukasz Langa26d513c2010-11-10 18:57:39 +000063consists of sections, each of which contains keys with values.
Georg Brandlbb27c122010-11-11 07:26:40 +000064:mod:`configparser` classes can read and write such files. Let's start by
Łukasz Langa26d513c2010-11-10 18:57:39 +000065creating the above configuration file programatically.
66
Łukasz Langa26d513c2010-11-10 18:57:39 +000067.. doctest::
68
Georg Brandlbb27c122010-11-11 07:26:40 +000069 >>> import configparser
Łukasz Langa7f64c8a2010-12-16 01:16:22 +000070 >>> config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +000071 >>> config['DEFAULT'] = {'ServerAliveInterval': '45',
72 ... 'Compression': 'yes',
73 ... 'CompressionLevel': '9'}
74 >>> config['bitbucket.org'] = {}
75 >>> config['bitbucket.org']['User'] = 'hg'
76 >>> config['topsecret.server.com'] = {}
77 >>> topsecret = config['topsecret.server.com']
78 >>> topsecret['Port'] = '50022' # mutates the parser
79 >>> topsecret['ForwardX11'] = 'no' # same here
80 >>> config['DEFAULT']['ForwardX11'] = 'yes'
81 >>> with open('example.ini', 'w') as configfile:
82 ... config.write(configfile)
83 ...
Łukasz Langa26d513c2010-11-10 18:57:39 +000084
Fred Drake5a7c11f2010-11-13 05:24:17 +000085As you can see, we can treat a config parser much like a dictionary.
86There are differences, `outlined later <#mapping-protocol-access>`_, but
87the behavior is very close to what you would expect from a dictionary.
Łukasz Langa26d513c2010-11-10 18:57:39 +000088
Fred Drake5a7c11f2010-11-13 05:24:17 +000089Now that we have created and saved a configuration file, let's read it
90back and explore the data it holds.
Łukasz Langa26d513c2010-11-10 18:57:39 +000091
Łukasz Langa26d513c2010-11-10 18:57:39 +000092.. doctest::
93
Georg Brandlbb27c122010-11-11 07:26:40 +000094 >>> import configparser
Łukasz Langa7f64c8a2010-12-16 01:16:22 +000095 >>> config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +000096 >>> config.sections()
97 []
98 >>> config.read('example.ini')
99 ['example.ini']
100 >>> config.sections()
101 ['bitbucket.org', 'topsecret.server.com']
102 >>> 'bitbucket.org' in config
103 True
104 >>> 'bytebong.com' in config
105 False
106 >>> config['bitbucket.org']['User']
107 'hg'
108 >>> config['DEFAULT']['Compression']
109 'yes'
110 >>> topsecret = config['topsecret.server.com']
111 >>> topsecret['ForwardX11']
112 'no'
113 >>> topsecret['Port']
114 '50022'
115 >>> for key in config['bitbucket.org']: print(key)
116 ...
117 user
118 compressionlevel
119 serveraliveinterval
120 compression
121 forwardx11
122 >>> config['bitbucket.org']['ForwardX11']
123 'yes'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000124
Fred Drake5a7c11f2010-11-13 05:24:17 +0000125As we can see above, the API is pretty straightforward. The only bit of magic
Łukasz Langa26d513c2010-11-10 18:57:39 +0000126involves the ``DEFAULT`` section which provides default values for all other
Fred Drake5a7c11f2010-11-13 05:24:17 +0000127sections [1]_. Note also that keys in sections are
128case-insensitive and stored in lowercase [1]_.
Georg Brandlbb27c122010-11-11 07:26:40 +0000129
Łukasz Langa26d513c2010-11-10 18:57:39 +0000130
131Supported Datatypes
132-------------------
133
134Config parsers do not guess datatypes of values in configuration files, always
Georg Brandlbb27c122010-11-11 07:26:40 +0000135storing them internally as strings. This means that if you need other
136datatypes, you should convert on your own:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000137
Łukasz Langa26d513c2010-11-10 18:57:39 +0000138.. doctest::
139
Georg Brandlbb27c122010-11-11 07:26:40 +0000140 >>> int(topsecret['Port'])
141 50022
142 >>> float(topsecret['CompressionLevel'])
143 9.0
Łukasz Langa26d513c2010-11-10 18:57:39 +0000144
Fred Drake5a7c11f2010-11-13 05:24:17 +0000145Extracting Boolean values is not that simple, though. Passing the value
146to ``bool()`` would do no good since ``bool('False')`` is still
147``True``. This is why config parsers also provide :meth:`getboolean`.
148This method is case-insensitive and recognizes Boolean values from
149``'yes'``/``'no'``, ``'on'``/``'off'`` and ``'1'``/``'0'`` [1]_.
150For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000151
Łukasz Langa26d513c2010-11-10 18:57:39 +0000152.. doctest::
153
Georg Brandlbb27c122010-11-11 07:26:40 +0000154 >>> topsecret.getboolean('ForwardX11')
155 False
156 >>> config['bitbucket.org'].getboolean('ForwardX11')
157 True
158 >>> config.getboolean('bitbucket.org', 'Compression')
159 True
Łukasz Langa26d513c2010-11-10 18:57:39 +0000160
161Apart from :meth:`getboolean`, config parsers also provide equivalent
Fred Drake5a7c11f2010-11-13 05:24:17 +0000162:meth:`getint` and :meth:`getfloat` methods, but these are far less
163useful since conversion using :func:`int` and :func:`float` is
164sufficient for these types.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000165
Georg Brandlbb27c122010-11-11 07:26:40 +0000166
Łukasz Langa26d513c2010-11-10 18:57:39 +0000167Fallback Values
168---------------
169
Fred Drake5a7c11f2010-11-13 05:24:17 +0000170As with a dictionary, you can use a section's :meth:`get` method to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000171provide fallback values:
172
Łukasz Langa26d513c2010-11-10 18:57:39 +0000173.. doctest::
174
Georg Brandlbb27c122010-11-11 07:26:40 +0000175 >>> topsecret.get('Port')
176 '50022'
177 >>> topsecret.get('CompressionLevel')
178 '9'
179 >>> topsecret.get('Cipher')
180 >>> topsecret.get('Cipher', '3des-cbc')
181 '3des-cbc'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000182
Fred Drake5a7c11f2010-11-13 05:24:17 +0000183Please note that default values have precedence over fallback values.
184For instance, in our example the ``'CompressionLevel'`` key was
185specified only in the ``'DEFAULT'`` section. If we try to get it from
186the section ``'topsecret.server.com'``, we will always get the default,
187even if we specify a fallback:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000188
Łukasz Langa26d513c2010-11-10 18:57:39 +0000189.. doctest::
190
Georg Brandlbb27c122010-11-11 07:26:40 +0000191 >>> topsecret.get('CompressionLevel', '3')
192 '9'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000193
194One more thing to be aware of is that the parser-level :meth:`get` method
195provides a custom, more complex interface, maintained for backwards
Fred Drake5a7c11f2010-11-13 05:24:17 +0000196compatibility. When using this method, a fallback value can be provided via
197the ``fallback`` keyword-only argument:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000198
Łukasz Langa26d513c2010-11-10 18:57:39 +0000199.. doctest::
200
Georg Brandlbb27c122010-11-11 07:26:40 +0000201 >>> config.get('bitbucket.org', 'monster',
202 ... fallback='No such things as monsters')
203 'No such things as monsters'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000204
205The same ``fallback`` argument can be used with the :meth:`getint`,
206:meth:`getfloat` and :meth:`getboolean` methods, for example:
207
Łukasz Langa26d513c2010-11-10 18:57:39 +0000208.. doctest::
209
Georg Brandlbb27c122010-11-11 07:26:40 +0000210 >>> 'BatchMode' in topsecret
211 False
212 >>> topsecret.getboolean('BatchMode', fallback=True)
213 True
214 >>> config['DEFAULT']['BatchMode'] = 'no'
215 >>> topsecret.getboolean('BatchMode', fallback=True)
216 False
217
Łukasz Langa26d513c2010-11-10 18:57:39 +0000218
219Supported INI File Structure
220----------------------------
221
Georg Brandl96a60ae2010-07-28 13:13:46 +0000222A configuration file consists of sections, each led by a ``[section]`` header,
Fred Drakea4923622010-08-09 12:52:45 +0000223followed by key/value entries separated by a specific string (``=`` or ``:`` by
Georg Brandlbb27c122010-11-11 07:26:40 +0000224default [1]_). By default, section names are case sensitive but keys are not
Fred Drake5a7c11f2010-11-13 05:24:17 +0000225[1]_. Leading and trailing whitespace is removed from keys and values.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000226Values can be omitted, in which case the key/value delimiter may also be left
227out. Values can also span multiple lines, as long as they are indented deeper
228than the first line of the value. Depending on the parser's mode, blank lines
229may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000230
Fred Drake5a7c11f2010-11-13 05:24:17 +0000231Configuration files may include comments, prefixed by specific
232characters (``#`` and ``;`` by default [1]_). Comments may appear on
Łukasz Langab25a7912010-12-17 01:32:29 +0000233their own on an otherwise empty line, possibly indented. [1]_
Georg Brandl96a60ae2010-07-28 13:13:46 +0000234
Georg Brandlbb27c122010-11-11 07:26:40 +0000235For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000236
Georg Brandlbb27c122010-11-11 07:26:40 +0000237.. code-block:: ini
Georg Brandl116aa622007-08-15 14:28:22 +0000238
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000239 [Simple Values]
Łukasz Langab25a7912010-12-17 01:32:29 +0000240 key=value
241 spaces in keys=allowed
242 spaces in values=allowed as well
243 spaces around the delimiter = obviously
244 you can also use : to delimit keys from values
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000245
246 [All Values Are Strings]
247 values like this: 1000000
248 or this: 3.14159265359
249 are they treated as numbers? : no
250 integers, floats and booleans are held as: strings
251 can use the API to get converted values directly: true
Georg Brandl116aa622007-08-15 14:28:22 +0000252
Georg Brandl96a60ae2010-07-28 13:13:46 +0000253 [Multiline Values]
254 chorus: I'm a lumberjack, and I'm okay
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000255 I sleep all night and I work all day
Georg Brandl116aa622007-08-15 14:28:22 +0000256
Georg Brandl96a60ae2010-07-28 13:13:46 +0000257 [No Values]
258 key_without_value
259 empty string value here =
Georg Brandl116aa622007-08-15 14:28:22 +0000260
Łukasz Langab25a7912010-12-17 01:32:29 +0000261 [You can use comments]
262 # like this
263 ; or this
264
265 # By default only in an empty line.
266 # Inline comments can be harmful because they prevent users
267 # from using the delimiting characters as parts of values.
268 # That being said, this can be customized.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000269
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000270 [Sections Can Be Indented]
271 can_values_be_as_well = True
272 does_that_mean_anything_special = False
273 purpose = formatting for readability
274 multiline_values = are
275 handled just fine as
276 long as they are indented
277 deeper than the first line
278 of a value
279 # Did I mention we can indent comments, too?
Georg Brandl116aa622007-08-15 14:28:22 +0000280
Georg Brandl96a60ae2010-07-28 13:13:46 +0000281
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000282Interpolation of values
283-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000284
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000285On top of the core functionality, :class:`ConfigParser` supports
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000286interpolation. This means values can be preprocessed before returning them
287from ``get()`` calls.
288
289.. class:: BasicInterpolation()
290
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000291 The default implementation used by :class:`ConfigParser`. It enables
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000292 values to contain format strings which refer to other values in the same
293 section, or values in the special default section [1]_. Additional default
294 values can be provided on initialization.
295
296 For example:
297
298 .. code-block:: ini
299
300 [Paths]
301 home_dir: /Users
302 my_dir: %(home_dir)s/lumberjack
303 my_pictures: %(my_dir)s/Pictures
304
305
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000306 In the example above, :class:`ConfigParser` with *interpolation* set to
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000307 ``BasicInterpolation()`` would resolve ``%(home_dir)s`` to the value of
308 ``home_dir`` (``/Users`` in this case). ``%(my_dir)s`` in effect would
309 resolve to ``/Users/lumberjack``. All interpolations are done on demand so
310 keys used in the chain of references do not have to be specified in any
311 specific order in the configuration file.
312
313 With ``interpolation`` set to ``None``, the parser would simply return
314 ``%(my_dir)s/Pictures`` as the value of ``my_pictures`` and
315 ``%(home_dir)s/lumberjack`` as the value of ``my_dir``.
316
317.. class:: ExtendedInterpolation()
318
319 An alternative handler for interpolation which implements a more advanced
320 syntax, used for instance in ``zc.buildout``. Extended interpolation is
321 using ``${section:option}`` to denote a value from a foreign section.
322 Interpolation can span multiple levels. For convenience, if the ``section:``
323 part is omitted, interpolation defaults to the current section (and possibly
324 the default values from the special section).
325
326 For example, the configuration specified above with basic interpolation,
327 would look like this with extended interpolation:
328
329 .. code-block:: ini
330
331 [Paths]
332 home_dir: /Users
333 my_dir: ${home_dir}/lumberjack
334 my_pictures: ${my_dir}/Pictures
335
336 Values from other sections can be fetched as well:
337
338 .. code-block:: ini
339
340 [Common]
341 home_dir: /Users
342 library_dir: /Library
343 system_dir: /System
344 macports_dir: /opt/local
345
346 [Frameworks]
347 Python: 3.2
348 path: ${Common:system_dir}/Library/Frameworks/
349
350 [Arthur]
351 nickname: Two Sheds
352 last_name: Jackson
353 my_dir: ${Common:home_dir}/twosheds
354 my_pictures: ${my_dir}/Pictures
355 python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
Georg Brandlbb27c122010-11-11 07:26:40 +0000356
Łukasz Langa26d513c2010-11-10 18:57:39 +0000357Mapping Protocol Access
358-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000359
Łukasz Langa26d513c2010-11-10 18:57:39 +0000360.. versionadded:: 3.2
Georg Brandl96a60ae2010-07-28 13:13:46 +0000361
Łukasz Langa26d513c2010-11-10 18:57:39 +0000362Mapping protocol access is a generic name for functionality that enables using
Georg Brandlbb27c122010-11-11 07:26:40 +0000363custom objects as if they were dictionaries. In case of :mod:`configparser`,
Łukasz Langa26d513c2010-11-10 18:57:39 +0000364the mapping interface implementation is using the
365``parser['section']['option']`` notation.
366
367``parser['section']`` in particular returns a proxy for the section's data in
Georg Brandlbb27c122010-11-11 07:26:40 +0000368the parser. This means that the values are not copied but they are taken from
369the original parser on demand. What's even more important is that when values
Łukasz Langa26d513c2010-11-10 18:57:39 +0000370are changed on a section proxy, they are actually mutated in the original
371parser.
372
373:mod:`configparser` objects behave as close to actual dictionaries as possible.
374The mapping interface is complete and adheres to the ``MutableMapping`` ABC.
375However, there are a few differences that should be taken into account:
376
Georg Brandlbb27c122010-11-11 07:26:40 +0000377* By default, all keys in sections are accessible in a case-insensitive manner
378 [1]_. E.g. ``for option in parser["section"]`` yields only ``optionxform``'ed
379 option key names. This means lowercased keys by default. At the same time,
Fred Drake5a7c11f2010-11-13 05:24:17 +0000380 for a section that holds the key ``'a'``, both expressions return ``True``::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000381
Georg Brandlbb27c122010-11-11 07:26:40 +0000382 "a" in parser["section"]
383 "A" in parser["section"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000384
Georg Brandlbb27c122010-11-11 07:26:40 +0000385* All sections include ``DEFAULTSECT`` values as well which means that
386 ``.clear()`` on a section may not leave the section visibly empty. This is
Łukasz Langa26d513c2010-11-10 18:57:39 +0000387 because default values cannot be deleted from the section (because technically
Georg Brandlbb27c122010-11-11 07:26:40 +0000388 they are not there). If they are overriden in the section, deleting causes
389 the default value to be visible again. Trying to delete a default value
390 causes a ``KeyError``.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000391
Łukasz Langa3a8479a2012-12-31 03:38:39 +0100392* ``DEFAULTSECT`` cannot be removed from the parser:
393
394 * trying to delete it raises ``ValueError``,
395
396 * ``parser.clear()`` leaves it intact,
397
398 * ``parser.popitem()`` never returns it.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000399
Łukasz Langa71b37a52010-12-17 21:56:32 +0000400* ``parser.get(section, option, **kwargs)`` - the second argument is **not**
401 a fallback value. Note however that the section-level ``get()`` methods are
402 compatible both with the mapping protocol and the classic configparser API.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000403
Łukasz Langa71b37a52010-12-17 21:56:32 +0000404* ``parser.items()`` is compatible with the mapping protocol (returns a list of
405 *section_name*, *section_proxy* pairs including the DEFAULTSECT). However,
406 this method can also be invoked with arguments: ``parser.items(section, raw,
407 vars)``. The latter call returns a list of *option*, *value* pairs for
408 a specified ``section``, with all interpolations expanded (unless
409 ``raw=True`` is provided).
Łukasz Langa26d513c2010-11-10 18:57:39 +0000410
411The mapping protocol is implemented on top of the existing legacy API so that
Łukasz Langa71b37a52010-12-17 21:56:32 +0000412subclasses overriding the original interface still should have mappings working
413as expected.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000414
Georg Brandlbb27c122010-11-11 07:26:40 +0000415
Łukasz Langa26d513c2010-11-10 18:57:39 +0000416Customizing Parser Behaviour
417----------------------------
418
419There are nearly as many INI format variants as there are applications using it.
420:mod:`configparser` goes a long way to provide support for the largest sensible
Georg Brandlbb27c122010-11-11 07:26:40 +0000421set of INI styles available. The default functionality is mainly dictated by
Łukasz Langa26d513c2010-11-10 18:57:39 +0000422historical background and it's very likely that you will want to customize some
423of the features.
424
Fred Drake5a7c11f2010-11-13 05:24:17 +0000425The most common way to change the way a specific config parser works is to use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000426the :meth:`__init__` options:
427
428* *defaults*, default value: ``None``
429
430 This option accepts a dictionary of key-value pairs which will be initially
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000431 put in the ``DEFAULT`` section. This makes for an elegant way to support
432 concise configuration files that don't specify values which are the same as
433 the documented default.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000434
Fred Drake5a7c11f2010-11-13 05:24:17 +0000435 Hint: if you want to specify default values for a specific section, use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000436 :meth:`read_dict` before you read the actual file.
437
438* *dict_type*, default value: :class:`collections.OrderedDict`
439
440 This option has a major impact on how the mapping protocol will behave and how
Fred Drake5a7c11f2010-11-13 05:24:17 +0000441 the written configuration files look. With the default ordered
Łukasz Langa26d513c2010-11-10 18:57:39 +0000442 dictionary, every section is stored in the order they were added to the
Georg Brandlbb27c122010-11-11 07:26:40 +0000443 parser. Same goes for options within sections.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000444
445 An alternative dictionary type can be used for example to sort sections and
Georg Brandlbb27c122010-11-11 07:26:40 +0000446 options on write-back. You can also use a regular dictionary for performance
Łukasz Langa26d513c2010-11-10 18:57:39 +0000447 reasons.
448
449 Please note: there are ways to add a set of key-value pairs in a single
Georg Brandlbb27c122010-11-11 07:26:40 +0000450 operation. When you use a regular dictionary in those operations, the order
451 of the keys may be random. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000452
Łukasz Langa26d513c2010-11-10 18:57:39 +0000453 .. doctest::
454
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000455 >>> parser = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000456 >>> parser.read_dict({'section1': {'key1': 'value1',
457 ... 'key2': 'value2',
458 ... 'key3': 'value3'},
459 ... 'section2': {'keyA': 'valueA',
460 ... 'keyB': 'valueB',
461 ... 'keyC': 'valueC'},
462 ... 'section3': {'foo': 'x',
463 ... 'bar': 'y',
464 ... 'baz': 'z'}
465 ... })
466 >>> parser.sections()
467 ['section3', 'section2', 'section1']
468 >>> [option for option in parser['section3']]
469 ['baz', 'foo', 'bar']
Łukasz Langa26d513c2010-11-10 18:57:39 +0000470
471 In these operations you need to use an ordered dictionary as well:
472
Łukasz Langa26d513c2010-11-10 18:57:39 +0000473 .. doctest::
474
Georg Brandlbb27c122010-11-11 07:26:40 +0000475 >>> from collections import OrderedDict
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000476 >>> parser = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000477 >>> parser.read_dict(
478 ... OrderedDict((
479 ... ('s1',
480 ... OrderedDict((
481 ... ('1', '2'),
482 ... ('3', '4'),
483 ... ('5', '6'),
484 ... ))
485 ... ),
486 ... ('s2',
487 ... OrderedDict((
488 ... ('a', 'b'),
489 ... ('c', 'd'),
490 ... ('e', 'f'),
491 ... ))
492 ... ),
493 ... ))
494 ... )
495 >>> parser.sections()
496 ['s1', 's2']
497 >>> [option for option in parser['s1']]
498 ['1', '3', '5']
499 >>> [option for option in parser['s2'].values()]
500 ['b', 'd', 'f']
Łukasz Langa26d513c2010-11-10 18:57:39 +0000501
502* *allow_no_value*, default value: ``False``
503
504 Some configuration files are known to include settings without values, but
505 which otherwise conform to the syntax supported by :mod:`configparser`. The
Fred Drake5a7c11f2010-11-13 05:24:17 +0000506 *allow_no_value* parameter to the constructor can be used to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000507 indicate that such values should be accepted:
508
Łukasz Langa26d513c2010-11-10 18:57:39 +0000509 .. doctest::
510
Georg Brandlbb27c122010-11-11 07:26:40 +0000511 >>> import configparser
Łukasz Langa26d513c2010-11-10 18:57:39 +0000512
Georg Brandlbb27c122010-11-11 07:26:40 +0000513 >>> sample_config = """
514 ... [mysqld]
515 ... user = mysql
516 ... pid-file = /var/run/mysqld/mysqld.pid
517 ... skip-external-locking
518 ... old_passwords = 1
519 ... skip-bdb
Łukasz Langab25a7912010-12-17 01:32:29 +0000520 ... # we don't need ACID today
521 ... skip-innodb
Georg Brandlbb27c122010-11-11 07:26:40 +0000522 ... """
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000523 >>> config = configparser.ConfigParser(allow_no_value=True)
Georg Brandlbb27c122010-11-11 07:26:40 +0000524 >>> config.read_string(sample_config)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000525
Georg Brandlbb27c122010-11-11 07:26:40 +0000526 >>> # Settings with values are treated as before:
527 >>> config["mysqld"]["user"]
528 'mysql'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000529
Georg Brandlbb27c122010-11-11 07:26:40 +0000530 >>> # Settings without values provide None:
531 >>> config["mysqld"]["skip-bdb"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000532
Georg Brandlbb27c122010-11-11 07:26:40 +0000533 >>> # Settings which aren't specified still raise an error:
534 >>> config["mysqld"]["does-not-exist"]
535 Traceback (most recent call last):
536 ...
537 KeyError: 'does-not-exist'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000538
539* *delimiters*, default value: ``('=', ':')``
540
541 Delimiters are substrings that delimit keys from values within a section. The
542 first occurence of a delimiting substring on a line is considered a delimiter.
Fred Drake5a7c11f2010-11-13 05:24:17 +0000543 This means values (but not keys) can contain the delimiters.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000544
545 See also the *space_around_delimiters* argument to
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000546 :meth:`ConfigParser.write`.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000547
Łukasz Langab25a7912010-12-17 01:32:29 +0000548* *comment_prefixes*, default value: ``('#', ';')``
Łukasz Langa26d513c2010-11-10 18:57:39 +0000549
Łukasz Langab25a7912010-12-17 01:32:29 +0000550* *inline_comment_prefixes*, default value: ``None``
551
552 Comment prefixes are strings that indicate the start of a valid comment within
553 a config file. *comment_prefixes* are used only on otherwise empty lines
554 (optionally indented) whereas *inline_comment_prefixes* can be used after
555 every valid value (e.g. section names, options and empty lines as well). By
556 default inline comments are disabled and ``'#'`` and ``';'`` are used as
557 prefixes for whole line comments.
558
559 .. versionchanged:: 3.2
560 In previous versions of :mod:`configparser` behaviour matched
561 ``comment_prefixes=('#',';')`` and ``inline_comment_prefixes=(';',)``.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000562
563 Please note that config parsers don't support escaping of comment prefixes so
Łukasz Langab25a7912010-12-17 01:32:29 +0000564 using *inline_comment_prefixes* may prevent users from specifying option
565 values with characters used as comment prefixes. When in doubt, avoid setting
566 *inline_comment_prefixes*. In any circumstances, the only way of storing
567 comment prefix characters at the beginning of a line in multiline values is to
568 interpolate the prefix, for example::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000569
Łukasz Langab25a7912010-12-17 01:32:29 +0000570 >>> from configparser import ConfigParser, ExtendedInterpolation
571 >>> parser = ConfigParser(interpolation=ExtendedInterpolation())
572 >>> # the default BasicInterpolation could be used as well
573 >>> parser.read_string("""
574 ... [DEFAULT]
575 ... hash = #
576 ...
577 ... [hashes]
578 ... shebang =
579 ... ${hash}!/usr/bin/env python
580 ... ${hash} -*- coding: utf-8 -*-
581 ...
582 ... extensions =
583 ... enabled_extension
584 ... another_extension
585 ... #disabled_by_comment
586 ... yet_another_extension
587 ...
588 ... interpolation not necessary = if # is not at line start
589 ... even in multiline values = line #1
590 ... line #2
591 ... line #3
592 ... """)
593 >>> print(parser['hashes']['shebang'])
Łukasz Langa26d513c2010-11-10 18:57:39 +0000594
Łukasz Langab25a7912010-12-17 01:32:29 +0000595 #!/usr/bin/env python
596 # -*- coding: utf-8 -*-
597 >>> print(parser['hashes']['extensions'])
598
599 enabled_extension
600 another_extension
601 yet_another_extension
602 >>> print(parser['hashes']['interpolation not necessary'])
603 if # is not at line start
604 >>> print(parser['hashes']['even in multiline values'])
605 line #1
606 line #2
607 line #3
608
609* *strict*, default value: ``True``
610
611 When set to ``True``, the parser will not allow for any section or option
Łukasz Langa26d513c2010-11-10 18:57:39 +0000612 duplicates while reading from a single source (using :meth:`read_file`,
Łukasz Langab25a7912010-12-17 01:32:29 +0000613 :meth:`read_string` or :meth:`read_dict`). It is recommended to use strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000614 parsers in new applications.
615
Łukasz Langab25a7912010-12-17 01:32:29 +0000616 .. versionchanged:: 3.2
617 In previous versions of :mod:`configparser` behaviour matched
618 ``strict=False``.
619
Łukasz Langa26d513c2010-11-10 18:57:39 +0000620* *empty_lines_in_values*, default value: ``True``
621
Fred Drake5a7c11f2010-11-13 05:24:17 +0000622 In config parsers, values can span multiple lines as long as they are
623 indented more than the key that holds them. By default parsers also let
624 empty lines to be parts of values. At the same time, keys can be arbitrarily
625 indented themselves to improve readability. In consequence, when
626 configuration files get big and complex, it is easy for the user to lose
627 track of the file structure. Take for instance:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000628
Georg Brandlbb27c122010-11-11 07:26:40 +0000629 .. code-block:: ini
Łukasz Langa26d513c2010-11-10 18:57:39 +0000630
Georg Brandlbb27c122010-11-11 07:26:40 +0000631 [Section]
632 key = multiline
633 value with a gotcha
Łukasz Langa26d513c2010-11-10 18:57:39 +0000634
Georg Brandlbb27c122010-11-11 07:26:40 +0000635 this = is still a part of the multiline value of 'key'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000636
Georg Brandlbb27c122010-11-11 07:26:40 +0000637 This can be especially problematic for the user to see if she's using a
638 proportional font to edit the file. That is why when your application does
639 not need values with empty lines, you should consider disallowing them. This
640 will make empty lines split keys every time. In the example above, it would
Łukasz Langa26d513c2010-11-10 18:57:39 +0000641 produce two keys, ``key`` and ``this``.
642
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000643* *default_section*, default value: ``configparser.DEFAULTSECT`` (that is:
644 ``"DEFAULT"``)
645
646 The convention of allowing a special section of default values for other
647 sections or interpolation purposes is a powerful concept of this library,
648 letting users create complex declarative configurations. This section is
649 normally called ``"DEFAULT"`` but this can be customized to point to any
650 other valid section name. Some typical values include: ``"general"`` or
651 ``"common"``. The name provided is used for recognizing default sections when
652 reading from any source and is used when writing configuration back to
653 a file. Its current value can be retrieved using the
654 ``parser_instance.default_section`` attribute and may be modified at runtime
655 (i.e. to convert files from one format to another).
656
657* *interpolation*, default value: ``configparser.BasicInterpolation``
658
659 Interpolation behaviour may be customized by providing a custom handler
660 through the *interpolation* argument. ``None`` can be used to turn off
661 interpolation completely, ``ExtendedInterpolation()`` provides a more
662 advanced variant inspired by ``zc.buildout``. More on the subject in the
663 `dedicated documentation section <#interpolation-of-values>`_.
Łukasz Langab25a7912010-12-17 01:32:29 +0000664 :class:`RawConfigParser` has a default value of ``None``.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000665
Łukasz Langa26d513c2010-11-10 18:57:39 +0000666
Fred Drake5a7c11f2010-11-13 05:24:17 +0000667More advanced customization may be achieved by overriding default values of
668these parser attributes. The defaults are defined on the classes, so they
669may be overriden by subclasses or by attribute assignment.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000670
Fred Drake5a7c11f2010-11-13 05:24:17 +0000671.. attribute:: BOOLEAN_STATES
Łukasz Langa26d513c2010-11-10 18:57:39 +0000672
673 By default when using :meth:`getboolean`, config parsers consider the
674 following values ``True``: ``'1'``, ``'yes'``, ``'true'``, ``'on'`` and the
Georg Brandlbb27c122010-11-11 07:26:40 +0000675 following values ``False``: ``'0'``, ``'no'``, ``'false'``, ``'off'``. You
676 can override this by specifying a custom dictionary of strings and their
Fred Drake5a7c11f2010-11-13 05:24:17 +0000677 Boolean outcomes. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000678
Łukasz Langa26d513c2010-11-10 18:57:39 +0000679 .. doctest::
680
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000681 >>> custom = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000682 >>> custom['section1'] = {'funky': 'nope'}
683 >>> custom['section1'].getboolean('funky')
684 Traceback (most recent call last):
685 ...
686 ValueError: Not a boolean: nope
687 >>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}
688 >>> custom['section1'].getboolean('funky')
689 False
Łukasz Langa26d513c2010-11-10 18:57:39 +0000690
Fred Drake5a7c11f2010-11-13 05:24:17 +0000691 Other typical Boolean pairs include ``accept``/``reject`` or
Łukasz Langa26d513c2010-11-10 18:57:39 +0000692 ``enabled``/``disabled``.
693
Fred Drake5a7c11f2010-11-13 05:24:17 +0000694.. method:: optionxform(option)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000695
Fred Drake5a7c11f2010-11-13 05:24:17 +0000696 This method transforms option names on every read, get, or set
697 operation. The default converts the name to lowercase. This also
698 means that when a configuration file gets written, all keys will be
699 lowercase. Override this method if that's unsuitable.
700 For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000701
Łukasz Langa26d513c2010-11-10 18:57:39 +0000702 .. doctest::
703
Georg Brandlbb27c122010-11-11 07:26:40 +0000704 >>> config = """
705 ... [Section1]
706 ... Key = Value
707 ...
708 ... [Section2]
709 ... AnotherKey = Value
710 ... """
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000711 >>> typical = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000712 >>> typical.read_string(config)
713 >>> list(typical['Section1'].keys())
714 ['key']
715 >>> list(typical['Section2'].keys())
716 ['anotherkey']
717 >>> custom = configparser.RawConfigParser()
718 >>> custom.optionxform = lambda option: option
719 >>> custom.read_string(config)
720 >>> list(custom['Section1'].keys())
721 ['Key']
722 >>> list(custom['Section2'].keys())
723 ['AnotherKey']
724
Łukasz Langa66c908e2011-01-28 11:57:30 +0000725.. attribute:: SECTCRE
726
727 A compiled regular expression used to parse section headers. The default
728 matches ``[section]`` to the name ``"section"``. Whitespace is considered part
729 of the section name, thus ``[ larch ]`` will be read as a section of name
730 ``" larch "``. Override this attribute if that's unsuitable. For example:
731
732 .. doctest::
733
734 >>> config = """
735 ... [Section 1]
736 ... option = value
737 ...
738 ... [ Section 2 ]
739 ... another = val
740 ... """
741 >>> typical = ConfigParser()
742 >>> typical.read_string(config)
743 >>> typical.sections()
744 ['Section 1', ' Section 2 ']
745 >>> custom = ConfigParser()
746 >>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]")
747 >>> custom.read_string(config)
748 >>> custom.sections()
749 ['Section 1', 'Section 2']
750
751 .. note::
752
753 While ConfigParser objects also use an ``OPTCRE`` attribute for recognizing
754 option lines, it's not recommended to override it because that would
755 interfere with constructor options *allow_no_value* and *delimiters*.
756
Łukasz Langa26d513c2010-11-10 18:57:39 +0000757
758Legacy API Examples
759-------------------
760
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000761Mainly because of backwards compatibility concerns, :mod:`configparser`
762provides also a legacy API with explicit ``get``/``set`` methods. While there
763are valid use cases for the methods outlined below, mapping protocol access is
764preferred for new projects. The legacy API is at times more advanced,
765low-level and downright counterintuitive.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000766
767An example of writing to a configuration file::
768
769 import configparser
770
771 config = configparser.RawConfigParser()
772
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000773 # Please note that using RawConfigParser's set functions, you can assign
774 # non-string values to keys internally, but will receive an error when
775 # attempting to write to a file or when you get it in non-raw mode. Setting
776 # values using the mapping protocol or ConfigParser's set() does not allow
777 # such assignments to take place.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000778 config.add_section('Section1')
R David Murray1a1883d2012-09-29 14:40:23 -0400779 config.set('Section1', 'an_int', '15')
780 config.set('Section1', 'a_bool', 'true')
781 config.set('Section1', 'a_float', '3.1415')
Łukasz Langa26d513c2010-11-10 18:57:39 +0000782 config.set('Section1', 'baz', 'fun')
783 config.set('Section1', 'bar', 'Python')
784 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
785
786 # Writing our configuration file to 'example.cfg'
787 with open('example.cfg', 'w') as configfile:
788 config.write(configfile)
789
790An example of reading the configuration file again::
791
792 import configparser
793
794 config = configparser.RawConfigParser()
795 config.read('example.cfg')
796
797 # getfloat() raises an exception if the value is not a float
798 # getint() and getboolean() also do this for their respective types
R David Murray1a1883d2012-09-29 14:40:23 -0400799 a_float = config.getfloat('Section1', 'a_float')
800 an_int = config.getint('Section1', 'an_int')
801 print(a_float + an_int)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000802
803 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
804 # This is because we are using a RawConfigParser().
R David Murray1a1883d2012-09-29 14:40:23 -0400805 if config.getboolean('Section1', 'a_bool'):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000806 print(config.get('Section1', 'foo'))
807
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000808To get interpolation, use :class:`ConfigParser`::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000809
810 import configparser
811
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000812 cfg = configparser.ConfigParser()
Łukasz Langa26d513c2010-11-10 18:57:39 +0000813 cfg.read('example.cfg')
814
Éric Araujo941afed2011-09-01 02:47:34 +0200815 # Set the optional *raw* argument of get() to True if you wish to disable
Łukasz Langa26d513c2010-11-10 18:57:39 +0000816 # interpolation in a single get operation.
817 print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!"
818 print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!"
819
Éric Araujo941afed2011-09-01 02:47:34 +0200820 # The optional *vars* argument is a dict with members that will take
Łukasz Langa26d513c2010-11-10 18:57:39 +0000821 # precedence in interpolation.
822 print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation',
823 'baz': 'evil'}))
824
Éric Araujo941afed2011-09-01 02:47:34 +0200825 # The optional *fallback* argument can be used to provide a fallback value
Łukasz Langa26d513c2010-11-10 18:57:39 +0000826 print(cfg.get('Section1', 'foo'))
827 # -> "Python is fun!"
828
829 print(cfg.get('Section1', 'foo', fallback='Monty is not.'))
830 # -> "Python is fun!"
831
832 print(cfg.get('Section1', 'monster', fallback='No such things as monsters.'))
833 # -> "No such things as monsters."
834
835 # A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError
836 # but we can also use:
837
838 print(cfg.get('Section1', 'monster', fallback=None))
839 # -> None
840
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000841Default values are available in both types of ConfigParsers. They are used in
842interpolation if an option used is not defined elsewhere. ::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000843
844 import configparser
845
846 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000847 config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'})
Łukasz Langa26d513c2010-11-10 18:57:39 +0000848 config.read('example.cfg')
849
850 print(config.get('Section1', 'foo')) # -> "Python is fun!"
851 config.remove_option('Section1', 'bar')
852 config.remove_option('Section1', 'baz')
853 print(config.get('Section1', 'foo')) # -> "Life is hard!"
854
Georg Brandlbb27c122010-11-11 07:26:40 +0000855
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000856.. _configparser-objects:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000857
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000858ConfigParser Objects
859--------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000860
Łukasz Langab25a7912010-12-17 01:32:29 +0000861.. 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 +0000862
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000863 The main configuration parser. When *defaults* is given, it is initialized
Georg Brandl96a60ae2010-07-28 13:13:46 +0000864 into the dictionary of intrinsic defaults. When *dict_type* is given, it
865 will be used to create the dictionary objects for the list of sections, for
866 the options within a section, and for the default values.
867
Fred Drake5a7c11f2010-11-13 05:24:17 +0000868 When *delimiters* is given, it is used as the set of substrings that
Georg Brandl96a60ae2010-07-28 13:13:46 +0000869 divide keys from values. When *comment_prefixes* is given, it will be used
Łukasz Langab25a7912010-12-17 01:32:29 +0000870 as the set of substrings that prefix comments in otherwise empty lines.
871 Comments can be indented. When *inline_comment_prefixes* is given, it will be
872 used as the set of substrings that prefix comments in non-empty lines.
873
Łukasz Langab25a7912010-12-17 01:32:29 +0000874 When *strict* is ``True`` (the default), the parser won't allow for
Fred Drakea4923622010-08-09 12:52:45 +0000875 any section or option duplicates while reading from a single source (file,
876 string or dictionary), raising :exc:`DuplicateSectionError` or
Fred Drake5a7c11f2010-11-13 05:24:17 +0000877 :exc:`DuplicateOptionError`. When *empty_lines_in_values* is ``False``
Fred Drakea4923622010-08-09 12:52:45 +0000878 (default: ``True``), each empty line marks the end of an option. Otherwise,
879 internal empty lines of a multiline option are kept as part of the value.
880 When *allow_no_value* is ``True`` (default: ``False``), options without
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000881 values are accepted; the value held for these is ``None`` and they are
882 serialized without the trailing delimiter.
Fred Drake03c44a32010-02-19 06:08:41 +0000883
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000884 When *default_section* is given, it specifies the name for the special
885 section holding default values for other sections and interpolation purposes
886 (normally named ``"DEFAULT"``). This value can be retrieved and changed on
887 runtime using the ``default_section`` instance attribute.
888
889 Interpolation behaviour may be customized by providing a custom handler
890 through the *interpolation* argument. ``None`` can be used to turn off
891 interpolation completely, ``ExtendedInterpolation()`` provides a more
892 advanced variant inspired by ``zc.buildout``. More on the subject in the
893 `dedicated documentation section <#interpolation-of-values>`_.
894
895 All option names used in interpolation will be passed through the
896 :meth:`optionxform` method just like any other option name reference. For
897 example, using the default implementation of :meth:`optionxform` (which
898 converts option names to lower case), the values ``foo %(bar)s`` and ``foo
899 %(BAR)s`` are equivalent.
Georg Brandl116aa622007-08-15 14:28:22 +0000900
Raymond Hettinger231b7f12009-03-03 00:23:19 +0000901 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +0000902 The default *dict_type* is :class:`collections.OrderedDict`.
903
Fred Drake03c44a32010-02-19 06:08:41 +0000904 .. versionchanged:: 3.2
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000905 *allow_no_value*, *delimiters*, *comment_prefixes*, *strict*,
906 *empty_lines_in_values*, *default_section* and *interpolation* were
907 added.
Georg Brandl116aa622007-08-15 14:28:22 +0000908
Fred Drake03c44a32010-02-19 06:08:41 +0000909
Georg Brandlbb27c122010-11-11 07:26:40 +0000910 .. method:: defaults()
Georg Brandl116aa622007-08-15 14:28:22 +0000911
Georg Brandlbb27c122010-11-11 07:26:40 +0000912 Return a dictionary containing the instance-wide defaults.
Georg Brandl116aa622007-08-15 14:28:22 +0000913
914
Georg Brandlbb27c122010-11-11 07:26:40 +0000915 .. method:: sections()
Georg Brandl116aa622007-08-15 14:28:22 +0000916
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000917 Return a list of the sections available; the *default section* is not
918 included in the list.
Georg Brandl116aa622007-08-15 14:28:22 +0000919
920
Georg Brandlbb27c122010-11-11 07:26:40 +0000921 .. method:: add_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000922
Georg Brandlbb27c122010-11-11 07:26:40 +0000923 Add a section named *section* to the instance. If a section by the given
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000924 name already exists, :exc:`DuplicateSectionError` is raised. If the
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000925 *default section* name is passed, :exc:`ValueError` is raised. The name
926 of the section must be a string; if not, :exc:`TypeError` is raised.
927
928 .. versionchanged:: 3.2
929 Non-string section names raise :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000930
Georg Brandl116aa622007-08-15 14:28:22 +0000931
Georg Brandlbb27c122010-11-11 07:26:40 +0000932 .. method:: has_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000933
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000934 Indicates whether the named *section* is present in the configuration.
935 The *default section* is not acknowledged.
Georg Brandl116aa622007-08-15 14:28:22 +0000936
Georg Brandl116aa622007-08-15 14:28:22 +0000937
Georg Brandlbb27c122010-11-11 07:26:40 +0000938 .. method:: options(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000939
Georg Brandlbb27c122010-11-11 07:26:40 +0000940 Return a list of options available in the specified *section*.
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:: has_option(section, option)
Georg Brandl116aa622007-08-15 14:28:22 +0000944
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000945 If the given *section* exists, and contains the given *option*, return
Łukasz Langa71b37a52010-12-17 21:56:32 +0000946 :const:`True`; otherwise return :const:`False`. If the specified
947 *section* is :const:`None` or an empty string, DEFAULT is assumed.
Georg Brandl116aa622007-08-15 14:28:22 +0000948
Georg Brandl116aa622007-08-15 14:28:22 +0000949
Georg Brandlbb27c122010-11-11 07:26:40 +0000950 .. method:: read(filenames, encoding=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000951
Georg Brandlbb27c122010-11-11 07:26:40 +0000952 Attempt to read and parse a list of filenames, returning a list of
953 filenames which were successfully parsed. If *filenames* is a string, it
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000954 is treated as a single filename. If a file named in *filenames* cannot
955 be opened, that file will be ignored. This is designed so that you can
956 specify a list of potential configuration file locations (for example,
957 the current directory, the user's home directory, and some system-wide
958 directory), and all existing configuration files in the list will be
959 read. If none of the named files exist, the :class:`ConfigParser`
960 instance will contain an empty dataset. An application which requires
961 initial values to be loaded from a file should load the required file or
962 files using :meth:`read_file` before calling :meth:`read` for any
963 optional files::
Georg Brandl116aa622007-08-15 14:28:22 +0000964
Georg Brandlbb27c122010-11-11 07:26:40 +0000965 import configparser, os
Georg Brandl8dcaa732010-07-29 12:17:40 +0000966
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000967 config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000968 config.read_file(open('defaults.cfg'))
969 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
970 encoding='cp1250')
Georg Brandl116aa622007-08-15 14:28:22 +0000971
Georg Brandlbb27c122010-11-11 07:26:40 +0000972 .. versionadded:: 3.2
973 The *encoding* parameter. Previously, all files were read using the
974 default encoding for :func:`open`.
Georg Brandl116aa622007-08-15 14:28:22 +0000975
Georg Brandl116aa622007-08-15 14:28:22 +0000976
Georg Brandlbb27c122010-11-11 07:26:40 +0000977 .. method:: read_file(f, source=None)
Georg Brandl73753d32009-09-22 13:53:14 +0000978
Łukasz Langadaab1c82011-04-27 18:10:05 +0200979 Read and parse configuration data from *f* which must be an iterable
Łukasz Langaba702da2011-04-28 12:02:05 +0200980 yielding Unicode strings (for example files opened in text mode).
Georg Brandl116aa622007-08-15 14:28:22 +0000981
Georg Brandlbb27c122010-11-11 07:26:40 +0000982 Optional argument *source* specifies the name of the file being read. If
Fred Drake5a7c11f2010-11-13 05:24:17 +0000983 not given and *f* has a :attr:`name` attribute, that is used for
984 *source*; the default is ``'<???>'``.
Fred Drakea4923622010-08-09 12:52:45 +0000985
Georg Brandlbb27c122010-11-11 07:26:40 +0000986 .. versionadded:: 3.2
Łukasz Langa43ae6192011-04-27 18:13:42 +0200987 Replaces :meth:`readfp`.
988
Georg Brandlbb27c122010-11-11 07:26:40 +0000989 .. method:: read_string(string, source='<string>')
Fred Drakea4923622010-08-09 12:52:45 +0000990
Fred Drake5a7c11f2010-11-13 05:24:17 +0000991 Parse configuration data from a string.
Fred Drakea4923622010-08-09 12:52:45 +0000992
Fred Drake5a7c11f2010-11-13 05:24:17 +0000993 Optional argument *source* specifies a context-specific name of the
994 string passed. If not given, ``'<string>'`` is used. This should
995 commonly be a filesystem path or a URL.
Fred Drakea4923622010-08-09 12:52:45 +0000996
Georg Brandlbb27c122010-11-11 07:26:40 +0000997 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +0000998
Fred Drakea4923622010-08-09 12:52:45 +0000999
Georg Brandlbb27c122010-11-11 07:26:40 +00001000 .. method:: read_dict(dictionary, source='<dict>')
Fred Drakea4923622010-08-09 12:52:45 +00001001
Łukasz Langa71b37a52010-12-17 21:56:32 +00001002 Load configuration from any object that provides a dict-like ``items()``
1003 method. Keys are section names, values are dictionaries with keys and
1004 values that should be present in the section. If the used dictionary
1005 type preserves order, sections and their keys will be added in order.
1006 Values are automatically converted to strings.
Fred Drakea4923622010-08-09 12:52:45 +00001007
Georg Brandlbb27c122010-11-11 07:26:40 +00001008 Optional argument *source* specifies a context-specific name of the
1009 dictionary passed. If not given, ``<dict>`` is used.
Georg Brandl116aa622007-08-15 14:28:22 +00001010
Łukasz Langa71b37a52010-12-17 21:56:32 +00001011 This method can be used to copy state between parsers.
1012
Georg Brandlbb27c122010-11-11 07:26:40 +00001013 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +00001014
Georg Brandl116aa622007-08-15 14:28:22 +00001015
Ezio Melottie927e252012-09-08 20:46:01 +03001016 .. method:: get(section, option, *, raw=False, vars=None[, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +00001017
Georg Brandlbb27c122010-11-11 07:26:40 +00001018 Get an *option* value for the named *section*. If *vars* is provided, it
1019 must be a dictionary. The *option* is looked up in *vars* (if provided),
1020 *section*, and in *DEFAULTSECT* in that order. If the key is not found
1021 and *fallback* is provided, it is used as a fallback value. ``None`` can
1022 be provided as a *fallback* value.
Georg Brandl470a1232010-07-29 14:17:12 +00001023
Georg Brandlbb27c122010-11-11 07:26:40 +00001024 All the ``'%'`` interpolations are expanded in the return values, unless
1025 the *raw* argument is true. Values for interpolation keys are looked up
1026 in the same manner as the option.
Georg Brandl116aa622007-08-15 14:28:22 +00001027
Georg Brandlbb27c122010-11-11 07:26:40 +00001028 .. versionchanged:: 3.2
1029 Arguments *raw*, *vars* and *fallback* are keyword only to protect
1030 users from trying to use the third argument as the *fallback* fallback
1031 (especially when using the mapping protocol).
Georg Brandl116aa622007-08-15 14:28:22 +00001032
Łukasz Langa26d513c2010-11-10 18:57:39 +00001033
Ezio Melottie927e252012-09-08 20:46:01 +03001034 .. method:: getint(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001035
Georg Brandlbb27c122010-11-11 07:26:40 +00001036 A convenience method which coerces the *option* in the specified *section*
1037 to an integer. See :meth:`get` for explanation of *raw*, *vars* and
1038 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001039
1040
Ezio Melottie927e252012-09-08 20:46:01 +03001041 .. method:: getfloat(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001042
Georg Brandlbb27c122010-11-11 07:26:40 +00001043 A convenience method which coerces the *option* in the specified *section*
1044 to a floating point number. See :meth:`get` for explanation of *raw*,
1045 *vars* and *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001046
1047
Ezio Melottie927e252012-09-08 20:46:01 +03001048 .. method:: getboolean(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001049
Georg Brandlbb27c122010-11-11 07:26:40 +00001050 A convenience method which coerces the *option* in the specified *section*
1051 to a Boolean value. Note that the accepted values for the option are
Fred Drake5a7c11f2010-11-13 05:24:17 +00001052 ``'1'``, ``'yes'``, ``'true'``, and ``'on'``, which cause this method to
1053 return ``True``, and ``'0'``, ``'no'``, ``'false'``, and ``'off'``, which
Georg Brandlbb27c122010-11-11 07:26:40 +00001054 cause it to return ``False``. These string values are checked in a
1055 case-insensitive manner. Any other value will cause it to raise
1056 :exc:`ValueError`. See :meth:`get` for explanation of *raw*, *vars* and
1057 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001058
1059
Ezio Melottie0add762012-09-14 06:32:35 +03001060 .. method:: items(raw=False, vars=None)
1061 items(section, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001062
Łukasz Langa71b37a52010-12-17 21:56:32 +00001063 When *section* is not given, return a list of *section_name*,
1064 *section_proxy* pairs, including DEFAULTSECT.
1065
1066 Otherwise, return a list of *name*, *value* pairs for the options in the
1067 given *section*. Optional arguments have the same meaning as for the
Georg Brandlbb27c122010-11-11 07:26:40 +00001068 :meth:`get` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001069
Łukasz Langa72547622011-05-09 18:49:42 +02001070 .. versionchanged:: 3.2
Łukasz Langa72547622011-05-09 18:49:42 +02001071 Items present in *vars* no longer appear in the result. The previous
1072 behaviour mixed actual parser options with variables provided for
1073 interpolation.
Georg Brandl116aa622007-08-15 14:28:22 +00001074
Georg Brandlbb27c122010-11-11 07:26:40 +00001075 .. method:: set(section, option, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001076
Georg Brandlbb27c122010-11-11 07:26:40 +00001077 If the given section exists, set the given option to the specified value;
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001078 otherwise raise :exc:`NoSectionError`. *option* and *value* must be
1079 strings; if not, :exc:`TypeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001080
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001081
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001082 .. method:: write(fileobject, space_around_delimiters=True)
1083
1084 Write a representation of the configuration to the specified :term:`file
1085 object`, which must be opened in text mode (accepting strings). This
1086 representation can be parsed by a future :meth:`read` call. If
1087 *space_around_delimiters* is true, delimiters between
1088 keys and values are surrounded by spaces.
1089
1090
1091 .. method:: remove_option(section, option)
1092
1093 Remove the specified *option* from the specified *section*. If the
1094 section does not exist, raise :exc:`NoSectionError`. If the option
1095 existed to be removed, return :const:`True`; otherwise return
1096 :const:`False`.
1097
1098
1099 .. method:: remove_section(section)
1100
1101 Remove the specified *section* from the configuration. If the section in
1102 fact existed, return ``True``. Otherwise return ``False``.
1103
1104
1105 .. method:: optionxform(option)
1106
1107 Transforms the option name *option* as found in an input file or as passed
1108 in by client code to the form that should be used in the internal
1109 structures. The default implementation returns a lower-case version of
1110 *option*; subclasses may override this or client code can set an attribute
1111 of this name on instances to affect this behavior.
1112
1113 You don't need to subclass the parser to use this method, you can also
1114 set it on an instance, to a function that takes a string argument and
1115 returns a string. Setting it to ``str``, for example, would make option
1116 names case sensitive::
1117
1118 cfgparser = ConfigParser()
1119 cfgparser.optionxform = str
1120
1121 Note that when reading configuration files, whitespace around the option
1122 names is stripped before :meth:`optionxform` is called.
1123
1124
1125 .. method:: readfp(fp, filename=None)
1126
1127 .. deprecated:: 3.2
1128 Use :meth:`read_file` instead.
1129
Łukasz Langaba702da2011-04-28 12:02:05 +02001130 .. versionchanged:: 3.2
1131 :meth:`readfp` now iterates on *f* instead of calling ``f.readline()``.
1132
1133 For existing code calling :meth:`readfp` with arguments which don't
1134 support iteration, the following generator may be used as a wrapper
1135 around the file-like object::
1136
1137 def readline_generator(f):
1138 line = f.readline()
1139 while line:
1140 yield line
1141 line = f.readline()
1142
1143 Instead of ``parser.readfp(f)`` use
1144 ``parser.read_file(readline_generator(f))``.
1145
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001146
1147.. data:: MAX_INTERPOLATION_DEPTH
1148
1149 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
1150 parameter is false. This is relevant only when the default *interpolation*
1151 is used.
1152
1153
1154.. _rawconfigparser-objects:
1155
1156RawConfigParser Objects
1157-----------------------
1158
Ezio Melottie927e252012-09-08 20:46:01 +03001159.. class:: RawConfigParser(defaults=None, dict_type=collections.OrderedDict, \
1160 allow_no_value=False, *, delimiters=('=', ':'), \
1161 comment_prefixes=('#', ';'), \
1162 inline_comment_prefixes=None, strict=True, \
1163 empty_lines_in_values=True, \
1164 default_section=configparser.DEFAULTSECT[, \
1165 interpolation])
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001166
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001167 Legacy variant of the :class:`ConfigParser` with interpolation disabled
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001168 by default and unsafe ``add_section`` and ``set`` methods.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001169
1170 .. note::
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001171 Consider using :class:`ConfigParser` instead which checks types of
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001172 the values to be stored internally. If you don't want interpolation, you
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001173 can use ``ConfigParser(interpolation=None)``.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001174
1175
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001176 .. method:: add_section(section)
1177
1178 Add a section named *section* to the instance. If a section by the given
1179 name already exists, :exc:`DuplicateSectionError` is raised. If the
1180 *default section* name is passed, :exc:`ValueError` is raised.
1181
1182 Type of *section* is not checked which lets users create non-string named
1183 sections. This behaviour is unsupported and may cause internal errors.
1184
1185
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001186 .. method:: set(section, option, value)
1187
1188 If the given section exists, set the given option to the specified value;
1189 otherwise raise :exc:`NoSectionError`. While it is possible to use
1190 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters
1191 set to true) for *internal* storage of non-string values, full
1192 functionality (including interpolation and output to files) can only be
1193 achieved using string values.
1194
1195 This method lets users assign non-string values to keys internally. This
1196 behaviour is unsupported and will cause errors when attempting to write
1197 to a file or get it in non-raw mode. **Use the mapping protocol API**
1198 which does not allow such assignments to take place.
1199
1200
Łukasz Langa26d513c2010-11-10 18:57:39 +00001201Exceptions
1202----------
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001203
Łukasz Langa26d513c2010-11-10 18:57:39 +00001204.. exception:: Error
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001205
Fred Drake5a7c11f2010-11-13 05:24:17 +00001206 Base class for all other :mod:`configparser` exceptions.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001207
Georg Brandl48310cd2009-01-03 21:18:54 +00001208
Łukasz Langa26d513c2010-11-10 18:57:39 +00001209.. exception:: NoSectionError
Georg Brandl48310cd2009-01-03 21:18:54 +00001210
Łukasz Langa26d513c2010-11-10 18:57:39 +00001211 Exception raised when a specified section is not found.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001212
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001213
Łukasz Langa26d513c2010-11-10 18:57:39 +00001214.. exception:: DuplicateSectionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001215
Łukasz Langa26d513c2010-11-10 18:57:39 +00001216 Exception raised if :meth:`add_section` is called with the name of a section
1217 that is already present or in strict parsers when a section if found more
1218 than once in a single input file, string or dictionary.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001219
Łukasz Langa26d513c2010-11-10 18:57:39 +00001220 .. versionadded:: 3.2
1221 Optional ``source`` and ``lineno`` attributes and arguments to
1222 :meth:`__init__` were added.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001223
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001224
Łukasz Langa26d513c2010-11-10 18:57:39 +00001225.. exception:: DuplicateOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001226
Łukasz Langa26d513c2010-11-10 18:57:39 +00001227 Exception raised by strict parsers if a single option appears twice during
1228 reading from a single file, string or dictionary. This catches misspellings
1229 and case sensitivity-related errors, e.g. a dictionary may have two keys
1230 representing the same case-insensitive configuration key.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001231
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001232
Łukasz Langa26d513c2010-11-10 18:57:39 +00001233.. exception:: NoOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001234
Łukasz Langa26d513c2010-11-10 18:57:39 +00001235 Exception raised when a specified option is not found in the specified
1236 section.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001237
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001238
Łukasz Langa26d513c2010-11-10 18:57:39 +00001239.. exception:: InterpolationError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001240
Łukasz Langa26d513c2010-11-10 18:57:39 +00001241 Base class for exceptions raised when problems occur performing string
1242 interpolation.
Georg Brandl48310cd2009-01-03 21:18:54 +00001243
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001244
Łukasz Langa26d513c2010-11-10 18:57:39 +00001245.. exception:: InterpolationDepthError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001246
Łukasz Langa26d513c2010-11-10 18:57:39 +00001247 Exception raised when string interpolation cannot be completed because the
Georg Brandlbb27c122010-11-11 07:26:40 +00001248 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
Łukasz Langa26d513c2010-11-10 18:57:39 +00001249 :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001250
Fred Drake03c44a32010-02-19 06:08:41 +00001251
Łukasz Langa26d513c2010-11-10 18:57:39 +00001252.. exception:: InterpolationMissingOptionError
Fred Drake03c44a32010-02-19 06:08:41 +00001253
Georg Brandlbb27c122010-11-11 07:26:40 +00001254 Exception raised when an option referenced from a value does not exist.
1255 Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001256
Fred Drake03c44a32010-02-19 06:08:41 +00001257
Łukasz Langa26d513c2010-11-10 18:57:39 +00001258.. exception:: InterpolationSyntaxError
Fred Drake03c44a32010-02-19 06:08:41 +00001259
Georg Brandlbb27c122010-11-11 07:26:40 +00001260 Exception raised when the source text into which substitutions are made does
1261 not conform to the required syntax. Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001262
Łukasz Langa26d513c2010-11-10 18:57:39 +00001263
1264.. exception:: MissingSectionHeaderError
1265
Georg Brandlbb27c122010-11-11 07:26:40 +00001266 Exception raised when attempting to parse a file which has no section
1267 headers.
Łukasz Langa26d513c2010-11-10 18:57:39 +00001268
1269
1270.. exception:: ParsingError
1271
1272 Exception raised when errors occur attempting to parse a file.
1273
1274 .. versionchanged:: 3.2
1275 The ``filename`` attribute and :meth:`__init__` argument were renamed to
1276 ``source`` for consistency.
1277
Georg Brandlbb27c122010-11-11 07:26:40 +00001278
1279.. rubric:: Footnotes
1280
1281.. [1] Config parsers allow for heavy customization. If you are interested in
1282 changing the behaviour outlined by the footnote reference, consult the
1283 `Customizing Parser Behaviour`_ section.