blob: bd6c36410edb4c72afe54c373fa2ff51792a934f [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
Fred Drake5a7c11f2010-11-13 05:24:17 +0000147Extracting Boolean values is not that simple, though. Passing the value
148to ``bool()`` would do no good since ``bool('False')`` is still
149``True``. This is why config parsers also provide :meth:`getboolean`.
150This method is case-insensitive and recognizes Boolean values from
151``'yes'``/``'no'``, ``'on'``/``'off'`` and ``'1'``/``'0'`` [1]_.
152For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000153
Łukasz Langa26d513c2010-11-10 18:57:39 +0000154.. doctest::
155
Georg Brandlbb27c122010-11-11 07:26:40 +0000156 >>> topsecret.getboolean('ForwardX11')
157 False
158 >>> config['bitbucket.org'].getboolean('ForwardX11')
159 True
160 >>> config.getboolean('bitbucket.org', 'Compression')
161 True
Łukasz Langa26d513c2010-11-10 18:57:39 +0000162
163Apart from :meth:`getboolean`, config parsers also provide equivalent
Fred Drake5a7c11f2010-11-13 05:24:17 +0000164:meth:`getint` and :meth:`getfloat` methods, but these are far less
165useful since conversion using :func:`int` and :func:`float` is
166sufficient for these types.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000167
Georg Brandlbb27c122010-11-11 07:26:40 +0000168
Łukasz Langa26d513c2010-11-10 18:57:39 +0000169Fallback Values
170---------------
171
Fred Drake5a7c11f2010-11-13 05:24:17 +0000172As with a dictionary, you can use a section's :meth:`get` method to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000173provide fallback values:
174
Łukasz Langa26d513c2010-11-10 18:57:39 +0000175.. doctest::
176
Georg Brandlbb27c122010-11-11 07:26:40 +0000177 >>> topsecret.get('Port')
178 '50022'
179 >>> topsecret.get('CompressionLevel')
180 '9'
181 >>> topsecret.get('Cipher')
182 >>> topsecret.get('Cipher', '3des-cbc')
183 '3des-cbc'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000184
Fred Drake5a7c11f2010-11-13 05:24:17 +0000185Please note that default values have precedence over fallback values.
186For instance, in our example the ``'CompressionLevel'`` key was
187specified only in the ``'DEFAULT'`` section. If we try to get it from
188the section ``'topsecret.server.com'``, we will always get the default,
189even if we specify a fallback:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000190
Łukasz Langa26d513c2010-11-10 18:57:39 +0000191.. doctest::
192
Georg Brandlbb27c122010-11-11 07:26:40 +0000193 >>> topsecret.get('CompressionLevel', '3')
194 '9'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000195
196One more thing to be aware of is that the parser-level :meth:`get` method
197provides a custom, more complex interface, maintained for backwards
Fred Drake5a7c11f2010-11-13 05:24:17 +0000198compatibility. When using this method, a fallback value can be provided via
199the ``fallback`` keyword-only argument:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000200
Łukasz Langa26d513c2010-11-10 18:57:39 +0000201.. doctest::
202
Georg Brandlbb27c122010-11-11 07:26:40 +0000203 >>> config.get('bitbucket.org', 'monster',
204 ... fallback='No such things as monsters')
205 'No such things as monsters'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000206
207The same ``fallback`` argument can be used with the :meth:`getint`,
208:meth:`getfloat` and :meth:`getboolean` methods, for example:
209
Łukasz Langa26d513c2010-11-10 18:57:39 +0000210.. doctest::
211
Georg Brandlbb27c122010-11-11 07:26:40 +0000212 >>> 'BatchMode' in topsecret
213 False
214 >>> topsecret.getboolean('BatchMode', fallback=True)
215 True
216 >>> config['DEFAULT']['BatchMode'] = 'no'
217 >>> topsecret.getboolean('BatchMode', fallback=True)
218 False
219
Łukasz Langa26d513c2010-11-10 18:57:39 +0000220
221Supported INI File Structure
222----------------------------
223
Georg Brandl96a60ae2010-07-28 13:13:46 +0000224A configuration file consists of sections, each led by a ``[section]`` header,
Fred Drakea4923622010-08-09 12:52:45 +0000225followed by key/value entries separated by a specific string (``=`` or ``:`` by
Georg Brandlbb27c122010-11-11 07:26:40 +0000226default [1]_). By default, section names are case sensitive but keys are not
Fred Drake5a7c11f2010-11-13 05:24:17 +0000227[1]_. Leading and trailing whitespace is removed from keys and values.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000228Values can be omitted, in which case the key/value delimiter may also be left
229out. Values can also span multiple lines, as long as they are indented deeper
230than the first line of the value. Depending on the parser's mode, blank lines
231may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000232
Fred Drake5a7c11f2010-11-13 05:24:17 +0000233Configuration files may include comments, prefixed by specific
234characters (``#`` and ``;`` by default [1]_). Comments may appear on
Łukasz Langab25a7912010-12-17 01:32:29 +0000235their own on an otherwise empty line, possibly indented. [1]_
Georg Brandl96a60ae2010-07-28 13:13:46 +0000236
Georg Brandlbb27c122010-11-11 07:26:40 +0000237For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000238
Georg Brandlbb27c122010-11-11 07:26:40 +0000239.. code-block:: ini
Georg Brandl116aa622007-08-15 14:28:22 +0000240
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000241 [Simple Values]
Łukasz Langab25a7912010-12-17 01:32:29 +0000242 key=value
243 spaces in keys=allowed
244 spaces in values=allowed as well
245 spaces around the delimiter = obviously
246 you can also use : to delimit keys from values
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000247
248 [All Values Are Strings]
249 values like this: 1000000
250 or this: 3.14159265359
251 are they treated as numbers? : no
252 integers, floats and booleans are held as: strings
253 can use the API to get converted values directly: true
Georg Brandl116aa622007-08-15 14:28:22 +0000254
Georg Brandl96a60ae2010-07-28 13:13:46 +0000255 [Multiline Values]
256 chorus: I'm a lumberjack, and I'm okay
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000257 I sleep all night and I work all day
Georg Brandl116aa622007-08-15 14:28:22 +0000258
Georg Brandl96a60ae2010-07-28 13:13:46 +0000259 [No Values]
260 key_without_value
261 empty string value here =
Georg Brandl116aa622007-08-15 14:28:22 +0000262
Łukasz Langab25a7912010-12-17 01:32:29 +0000263 [You can use comments]
264 # like this
265 ; or this
266
267 # By default only in an empty line.
268 # Inline comments can be harmful because they prevent users
269 # from using the delimiting characters as parts of values.
270 # That being said, this can be customized.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000271
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000272 [Sections Can Be Indented]
273 can_values_be_as_well = True
274 does_that_mean_anything_special = False
275 purpose = formatting for readability
276 multiline_values = are
277 handled just fine as
278 long as they are indented
279 deeper than the first line
280 of a value
281 # Did I mention we can indent comments, too?
Georg Brandl116aa622007-08-15 14:28:22 +0000282
Georg Brandl96a60ae2010-07-28 13:13:46 +0000283
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000284Interpolation of values
285-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000286
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000287On top of the core functionality, :class:`ConfigParser` supports
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000288interpolation. This means values can be preprocessed before returning them
289from ``get()`` calls.
290
291.. class:: BasicInterpolation()
292
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000293 The default implementation used by :class:`ConfigParser`. It enables
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000294 values to contain format strings which refer to other values in the same
295 section, or values in the special default section [1]_. Additional default
296 values can be provided on initialization.
297
298 For example:
299
300 .. code-block:: ini
301
302 [Paths]
303 home_dir: /Users
304 my_dir: %(home_dir)s/lumberjack
305 my_pictures: %(my_dir)s/Pictures
306
307
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000308 In the example above, :class:`ConfigParser` with *interpolation* set to
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000309 ``BasicInterpolation()`` would resolve ``%(home_dir)s`` to the value of
310 ``home_dir`` (``/Users`` in this case). ``%(my_dir)s`` in effect would
311 resolve to ``/Users/lumberjack``. All interpolations are done on demand so
312 keys used in the chain of references do not have to be specified in any
313 specific order in the configuration file.
314
315 With ``interpolation`` set to ``None``, the parser would simply return
316 ``%(my_dir)s/Pictures`` as the value of ``my_pictures`` and
317 ``%(home_dir)s/lumberjack`` as the value of ``my_dir``.
318
319.. class:: ExtendedInterpolation()
320
321 An alternative handler for interpolation which implements a more advanced
322 syntax, used for instance in ``zc.buildout``. Extended interpolation is
323 using ``${section:option}`` to denote a value from a foreign section.
324 Interpolation can span multiple levels. For convenience, if the ``section:``
325 part is omitted, interpolation defaults to the current section (and possibly
326 the default values from the special section).
327
328 For example, the configuration specified above with basic interpolation,
329 would look like this with extended interpolation:
330
331 .. code-block:: ini
332
333 [Paths]
334 home_dir: /Users
335 my_dir: ${home_dir}/lumberjack
336 my_pictures: ${my_dir}/Pictures
337
338 Values from other sections can be fetched as well:
339
340 .. code-block:: ini
341
342 [Common]
343 home_dir: /Users
344 library_dir: /Library
345 system_dir: /System
346 macports_dir: /opt/local
347
348 [Frameworks]
349 Python: 3.2
350 path: ${Common:system_dir}/Library/Frameworks/
351
352 [Arthur]
353 nickname: Two Sheds
354 last_name: Jackson
355 my_dir: ${Common:home_dir}/twosheds
356 my_pictures: ${my_dir}/Pictures
357 python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
Georg Brandlbb27c122010-11-11 07:26:40 +0000358
Łukasz Langa26d513c2010-11-10 18:57:39 +0000359Mapping Protocol Access
360-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000361
Łukasz Langa26d513c2010-11-10 18:57:39 +0000362.. versionadded:: 3.2
Georg Brandl96a60ae2010-07-28 13:13:46 +0000363
Łukasz Langa26d513c2010-11-10 18:57:39 +0000364Mapping protocol access is a generic name for functionality that enables using
Georg Brandlbb27c122010-11-11 07:26:40 +0000365custom objects as if they were dictionaries. In case of :mod:`configparser`,
Łukasz Langa26d513c2010-11-10 18:57:39 +0000366the mapping interface implementation is using the
367``parser['section']['option']`` notation.
368
369``parser['section']`` in particular returns a proxy for the section's data in
Georg Brandlbb27c122010-11-11 07:26:40 +0000370the parser. This means that the values are not copied but they are taken from
371the original parser on demand. What's even more important is that when values
Łukasz Langa26d513c2010-11-10 18:57:39 +0000372are changed on a section proxy, they are actually mutated in the original
373parser.
374
375:mod:`configparser` objects behave as close to actual dictionaries as possible.
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300376The mapping interface is complete and adheres to the
377:class:`~collections.abc.MutableMapping` ABC.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000378However, there are a few differences that should be taken into account:
379
Georg Brandlbb27c122010-11-11 07:26:40 +0000380* By default, all keys in sections are accessible in a case-insensitive manner
381 [1]_. E.g. ``for option in parser["section"]`` yields only ``optionxform``'ed
382 option key names. This means lowercased keys by default. At the same time,
Fred Drake5a7c11f2010-11-13 05:24:17 +0000383 for a section that holds the key ``'a'``, both expressions return ``True``::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000384
Georg Brandlbb27c122010-11-11 07:26:40 +0000385 "a" in parser["section"]
386 "A" in parser["section"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000387
Georg Brandlbb27c122010-11-11 07:26:40 +0000388* All sections include ``DEFAULTSECT`` values as well which means that
389 ``.clear()`` on a section may not leave the section visibly empty. This is
Łukasz Langa26d513c2010-11-10 18:57:39 +0000390 because default values cannot be deleted from the section (because technically
Georg Brandlbb27c122010-11-11 07:26:40 +0000391 they are not there). If they are overriden in the section, deleting causes
392 the default value to be visible again. Trying to delete a default value
393 causes a ``KeyError``.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000394
Łukasz Langa3a8479a2012-12-31 03:38:39 +0100395* ``DEFAULTSECT`` cannot be removed from the parser:
396
397 * trying to delete it raises ``ValueError``,
398
399 * ``parser.clear()`` leaves it intact,
400
401 * ``parser.popitem()`` never returns it.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000402
Łukasz Langa71b37a52010-12-17 21:56:32 +0000403* ``parser.get(section, option, **kwargs)`` - the second argument is **not**
404 a fallback value. Note however that the section-level ``get()`` methods are
405 compatible both with the mapping protocol and the classic configparser API.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000406
Łukasz Langa71b37a52010-12-17 21:56:32 +0000407* ``parser.items()`` is compatible with the mapping protocol (returns a list of
408 *section_name*, *section_proxy* pairs including the DEFAULTSECT). However,
409 this method can also be invoked with arguments: ``parser.items(section, raw,
410 vars)``. The latter call returns a list of *option*, *value* pairs for
411 a specified ``section``, with all interpolations expanded (unless
412 ``raw=True`` is provided).
Łukasz Langa26d513c2010-11-10 18:57:39 +0000413
414The mapping protocol is implemented on top of the existing legacy API so that
Łukasz Langa71b37a52010-12-17 21:56:32 +0000415subclasses overriding the original interface still should have mappings working
416as expected.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000417
Georg Brandlbb27c122010-11-11 07:26:40 +0000418
Łukasz Langa26d513c2010-11-10 18:57:39 +0000419Customizing Parser Behaviour
420----------------------------
421
422There are nearly as many INI format variants as there are applications using it.
423:mod:`configparser` goes a long way to provide support for the largest sensible
Georg Brandlbb27c122010-11-11 07:26:40 +0000424set of INI styles available. The default functionality is mainly dictated by
Łukasz Langa26d513c2010-11-10 18:57:39 +0000425historical background and it's very likely that you will want to customize some
426of the features.
427
Fred Drake5a7c11f2010-11-13 05:24:17 +0000428The most common way to change the way a specific config parser works is to use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000429the :meth:`__init__` options:
430
431* *defaults*, default value: ``None``
432
433 This option accepts a dictionary of key-value pairs which will be initially
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000434 put in the ``DEFAULT`` section. This makes for an elegant way to support
435 concise configuration files that don't specify values which are the same as
436 the documented default.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000437
Fred Drake5a7c11f2010-11-13 05:24:17 +0000438 Hint: if you want to specify default values for a specific section, use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000439 :meth:`read_dict` before you read the actual file.
440
441* *dict_type*, default value: :class:`collections.OrderedDict`
442
443 This option has a major impact on how the mapping protocol will behave and how
Fred Drake5a7c11f2010-11-13 05:24:17 +0000444 the written configuration files look. With the default ordered
Łukasz Langa26d513c2010-11-10 18:57:39 +0000445 dictionary, every section is stored in the order they were added to the
Georg Brandlbb27c122010-11-11 07:26:40 +0000446 parser. Same goes for options within sections.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000447
448 An alternative dictionary type can be used for example to sort sections and
Georg Brandlbb27c122010-11-11 07:26:40 +0000449 options on write-back. You can also use a regular dictionary for performance
Łukasz Langa26d513c2010-11-10 18:57:39 +0000450 reasons.
451
452 Please note: there are ways to add a set of key-value pairs in a single
Georg Brandlbb27c122010-11-11 07:26:40 +0000453 operation. When you use a regular dictionary in those operations, the order
454 of the keys may be random. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000455
Łukasz Langa26d513c2010-11-10 18:57:39 +0000456 .. doctest::
457
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000458 >>> parser = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000459 >>> parser.read_dict({'section1': {'key1': 'value1',
460 ... 'key2': 'value2',
461 ... 'key3': 'value3'},
462 ... 'section2': {'keyA': 'valueA',
463 ... 'keyB': 'valueB',
464 ... 'keyC': 'valueC'},
465 ... 'section3': {'foo': 'x',
466 ... 'bar': 'y',
467 ... 'baz': 'z'}
468 ... })
469 >>> parser.sections()
470 ['section3', 'section2', 'section1']
471 >>> [option for option in parser['section3']]
472 ['baz', 'foo', 'bar']
Łukasz Langa26d513c2010-11-10 18:57:39 +0000473
474 In these operations you need to use an ordered dictionary as well:
475
Łukasz Langa26d513c2010-11-10 18:57:39 +0000476 .. doctest::
477
Georg Brandlbb27c122010-11-11 07:26:40 +0000478 >>> from collections import OrderedDict
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000479 >>> parser = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000480 >>> parser.read_dict(
481 ... OrderedDict((
482 ... ('s1',
483 ... OrderedDict((
484 ... ('1', '2'),
485 ... ('3', '4'),
486 ... ('5', '6'),
487 ... ))
488 ... ),
489 ... ('s2',
490 ... OrderedDict((
491 ... ('a', 'b'),
492 ... ('c', 'd'),
493 ... ('e', 'f'),
494 ... ))
495 ... ),
496 ... ))
497 ... )
498 >>> parser.sections()
499 ['s1', 's2']
500 >>> [option for option in parser['s1']]
501 ['1', '3', '5']
502 >>> [option for option in parser['s2'].values()]
503 ['b', 'd', 'f']
Łukasz Langa26d513c2010-11-10 18:57:39 +0000504
505* *allow_no_value*, default value: ``False``
506
507 Some configuration files are known to include settings without values, but
508 which otherwise conform to the syntax supported by :mod:`configparser`. The
Fred Drake5a7c11f2010-11-13 05:24:17 +0000509 *allow_no_value* parameter to the constructor can be used to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000510 indicate that such values should be accepted:
511
Łukasz Langa26d513c2010-11-10 18:57:39 +0000512 .. doctest::
513
Georg Brandlbb27c122010-11-11 07:26:40 +0000514 >>> import configparser
Łukasz Langa26d513c2010-11-10 18:57:39 +0000515
Georg Brandlbb27c122010-11-11 07:26:40 +0000516 >>> sample_config = """
517 ... [mysqld]
518 ... user = mysql
519 ... pid-file = /var/run/mysqld/mysqld.pid
520 ... skip-external-locking
521 ... old_passwords = 1
522 ... skip-bdb
Łukasz Langab25a7912010-12-17 01:32:29 +0000523 ... # we don't need ACID today
524 ... skip-innodb
Georg Brandlbb27c122010-11-11 07:26:40 +0000525 ... """
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000526 >>> config = configparser.ConfigParser(allow_no_value=True)
Georg Brandlbb27c122010-11-11 07:26:40 +0000527 >>> config.read_string(sample_config)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000528
Georg Brandlbb27c122010-11-11 07:26:40 +0000529 >>> # Settings with values are treated as before:
530 >>> config["mysqld"]["user"]
531 'mysql'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000532
Georg Brandlbb27c122010-11-11 07:26:40 +0000533 >>> # Settings without values provide None:
534 >>> config["mysqld"]["skip-bdb"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000535
Georg Brandlbb27c122010-11-11 07:26:40 +0000536 >>> # Settings which aren't specified still raise an error:
537 >>> config["mysqld"]["does-not-exist"]
538 Traceback (most recent call last):
539 ...
540 KeyError: 'does-not-exist'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000541
542* *delimiters*, default value: ``('=', ':')``
543
544 Delimiters are substrings that delimit keys from values within a section. The
Ned Deily0995c472013-07-14 12:43:16 -0700545 first occurrence of a delimiting substring on a line is considered a delimiter.
Fred Drake5a7c11f2010-11-13 05:24:17 +0000546 This means values (but not keys) can contain the delimiters.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000547
548 See also the *space_around_delimiters* argument to
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000549 :meth:`ConfigParser.write`.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000550
Łukasz Langab25a7912010-12-17 01:32:29 +0000551* *comment_prefixes*, default value: ``('#', ';')``
Łukasz Langa26d513c2010-11-10 18:57:39 +0000552
Łukasz Langab25a7912010-12-17 01:32:29 +0000553* *inline_comment_prefixes*, default value: ``None``
554
555 Comment prefixes are strings that indicate the start of a valid comment within
556 a config file. *comment_prefixes* are used only on otherwise empty lines
557 (optionally indented) whereas *inline_comment_prefixes* can be used after
558 every valid value (e.g. section names, options and empty lines as well). By
559 default inline comments are disabled and ``'#'`` and ``';'`` are used as
560 prefixes for whole line comments.
561
562 .. versionchanged:: 3.2
563 In previous versions of :mod:`configparser` behaviour matched
564 ``comment_prefixes=('#',';')`` and ``inline_comment_prefixes=(';',)``.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000565
566 Please note that config parsers don't support escaping of comment prefixes so
Łukasz Langab25a7912010-12-17 01:32:29 +0000567 using *inline_comment_prefixes* may prevent users from specifying option
568 values with characters used as comment prefixes. When in doubt, avoid setting
569 *inline_comment_prefixes*. In any circumstances, the only way of storing
570 comment prefix characters at the beginning of a line in multiline values is to
571 interpolate the prefix, for example::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000572
Łukasz Langab25a7912010-12-17 01:32:29 +0000573 >>> from configparser import ConfigParser, ExtendedInterpolation
574 >>> parser = ConfigParser(interpolation=ExtendedInterpolation())
575 >>> # the default BasicInterpolation could be used as well
576 >>> parser.read_string("""
577 ... [DEFAULT]
578 ... hash = #
579 ...
580 ... [hashes]
581 ... shebang =
582 ... ${hash}!/usr/bin/env python
583 ... ${hash} -*- coding: utf-8 -*-
584 ...
585 ... extensions =
586 ... enabled_extension
587 ... another_extension
588 ... #disabled_by_comment
589 ... yet_another_extension
590 ...
591 ... interpolation not necessary = if # is not at line start
592 ... even in multiline values = line #1
593 ... line #2
594 ... line #3
595 ... """)
596 >>> print(parser['hashes']['shebang'])
Łukasz Langa26d513c2010-11-10 18:57:39 +0000597
Łukasz Langab25a7912010-12-17 01:32:29 +0000598 #!/usr/bin/env python
599 # -*- coding: utf-8 -*-
600 >>> print(parser['hashes']['extensions'])
601
602 enabled_extension
603 another_extension
604 yet_another_extension
605 >>> print(parser['hashes']['interpolation not necessary'])
606 if # is not at line start
607 >>> print(parser['hashes']['even in multiline values'])
608 line #1
609 line #2
610 line #3
611
612* *strict*, default value: ``True``
613
614 When set to ``True``, the parser will not allow for any section or option
Łukasz Langa26d513c2010-11-10 18:57:39 +0000615 duplicates while reading from a single source (using :meth:`read_file`,
Łukasz Langab25a7912010-12-17 01:32:29 +0000616 :meth:`read_string` or :meth:`read_dict`). It is recommended to use strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000617 parsers in new applications.
618
Łukasz Langab25a7912010-12-17 01:32:29 +0000619 .. versionchanged:: 3.2
620 In previous versions of :mod:`configparser` behaviour matched
621 ``strict=False``.
622
Łukasz Langa26d513c2010-11-10 18:57:39 +0000623* *empty_lines_in_values*, default value: ``True``
624
Fred Drake5a7c11f2010-11-13 05:24:17 +0000625 In config parsers, values can span multiple lines as long as they are
626 indented more than the key that holds them. By default parsers also let
627 empty lines to be parts of values. At the same time, keys can be arbitrarily
628 indented themselves to improve readability. In consequence, when
629 configuration files get big and complex, it is easy for the user to lose
630 track of the file structure. Take for instance:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000631
Georg Brandlbb27c122010-11-11 07:26:40 +0000632 .. code-block:: ini
Łukasz Langa26d513c2010-11-10 18:57:39 +0000633
Georg Brandlbb27c122010-11-11 07:26:40 +0000634 [Section]
635 key = multiline
636 value with a gotcha
Łukasz Langa26d513c2010-11-10 18:57:39 +0000637
Georg Brandlbb27c122010-11-11 07:26:40 +0000638 this = is still a part of the multiline value of 'key'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000639
Georg Brandlbb27c122010-11-11 07:26:40 +0000640 This can be especially problematic for the user to see if she's using a
641 proportional font to edit the file. That is why when your application does
642 not need values with empty lines, you should consider disallowing them. This
643 will make empty lines split keys every time. In the example above, it would
Łukasz Langa26d513c2010-11-10 18:57:39 +0000644 produce two keys, ``key`` and ``this``.
645
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000646* *default_section*, default value: ``configparser.DEFAULTSECT`` (that is:
647 ``"DEFAULT"``)
648
649 The convention of allowing a special section of default values for other
650 sections or interpolation purposes is a powerful concept of this library,
651 letting users create complex declarative configurations. This section is
652 normally called ``"DEFAULT"`` but this can be customized to point to any
653 other valid section name. Some typical values include: ``"general"`` or
654 ``"common"``. The name provided is used for recognizing default sections when
655 reading from any source and is used when writing configuration back to
656 a file. Its current value can be retrieved using the
657 ``parser_instance.default_section`` attribute and may be modified at runtime
658 (i.e. to convert files from one format to another).
659
660* *interpolation*, default value: ``configparser.BasicInterpolation``
661
662 Interpolation behaviour may be customized by providing a custom handler
663 through the *interpolation* argument. ``None`` can be used to turn off
664 interpolation completely, ``ExtendedInterpolation()`` provides a more
665 advanced variant inspired by ``zc.buildout``. More on the subject in the
666 `dedicated documentation section <#interpolation-of-values>`_.
Łukasz Langab25a7912010-12-17 01:32:29 +0000667 :class:`RawConfigParser` has a default value of ``None``.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000668
Łukasz Langa26d513c2010-11-10 18:57:39 +0000669
Fred Drake5a7c11f2010-11-13 05:24:17 +0000670More advanced customization may be achieved by overriding default values of
671these parser attributes. The defaults are defined on the classes, so they
672may be overriden by subclasses or by attribute assignment.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000673
Fred Drake5a7c11f2010-11-13 05:24:17 +0000674.. attribute:: BOOLEAN_STATES
Łukasz Langa26d513c2010-11-10 18:57:39 +0000675
676 By default when using :meth:`getboolean`, config parsers consider the
677 following values ``True``: ``'1'``, ``'yes'``, ``'true'``, ``'on'`` and the
Georg Brandlbb27c122010-11-11 07:26:40 +0000678 following values ``False``: ``'0'``, ``'no'``, ``'false'``, ``'off'``. You
679 can override this by specifying a custom dictionary of strings and their
Fred Drake5a7c11f2010-11-13 05:24:17 +0000680 Boolean outcomes. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000681
Łukasz Langa26d513c2010-11-10 18:57:39 +0000682 .. doctest::
683
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000684 >>> custom = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000685 >>> custom['section1'] = {'funky': 'nope'}
686 >>> custom['section1'].getboolean('funky')
687 Traceback (most recent call last):
688 ...
689 ValueError: Not a boolean: nope
690 >>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}
691 >>> custom['section1'].getboolean('funky')
692 False
Łukasz Langa26d513c2010-11-10 18:57:39 +0000693
Fred Drake5a7c11f2010-11-13 05:24:17 +0000694 Other typical Boolean pairs include ``accept``/``reject`` or
Łukasz Langa26d513c2010-11-10 18:57:39 +0000695 ``enabled``/``disabled``.
696
Fred Drake5a7c11f2010-11-13 05:24:17 +0000697.. method:: optionxform(option)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000698
Fred Drake5a7c11f2010-11-13 05:24:17 +0000699 This method transforms option names on every read, get, or set
700 operation. The default converts the name to lowercase. This also
701 means that when a configuration file gets written, all keys will be
702 lowercase. Override this method if that's unsuitable.
703 For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000704
Łukasz Langa26d513c2010-11-10 18:57:39 +0000705 .. doctest::
706
Georg Brandlbb27c122010-11-11 07:26:40 +0000707 >>> config = """
708 ... [Section1]
709 ... Key = Value
710 ...
711 ... [Section2]
712 ... AnotherKey = Value
713 ... """
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000714 >>> typical = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000715 >>> typical.read_string(config)
716 >>> list(typical['Section1'].keys())
717 ['key']
718 >>> list(typical['Section2'].keys())
719 ['anotherkey']
720 >>> custom = configparser.RawConfigParser()
721 >>> custom.optionxform = lambda option: option
722 >>> custom.read_string(config)
723 >>> list(custom['Section1'].keys())
724 ['Key']
725 >>> list(custom['Section2'].keys())
726 ['AnotherKey']
727
Łukasz Langa66c908e2011-01-28 11:57:30 +0000728.. attribute:: SECTCRE
729
730 A compiled regular expression used to parse section headers. The default
731 matches ``[section]`` to the name ``"section"``. Whitespace is considered part
732 of the section name, thus ``[ larch ]`` will be read as a section of name
733 ``" larch "``. Override this attribute if that's unsuitable. For example:
734
735 .. doctest::
736
737 >>> config = """
738 ... [Section 1]
739 ... option = value
740 ...
741 ... [ Section 2 ]
742 ... another = val
743 ... """
744 >>> typical = ConfigParser()
745 >>> typical.read_string(config)
746 >>> typical.sections()
747 ['Section 1', ' Section 2 ']
748 >>> custom = ConfigParser()
749 >>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]")
750 >>> custom.read_string(config)
751 >>> custom.sections()
752 ['Section 1', 'Section 2']
753
754 .. note::
755
756 While ConfigParser objects also use an ``OPTCRE`` attribute for recognizing
757 option lines, it's not recommended to override it because that would
758 interfere with constructor options *allow_no_value* and *delimiters*.
759
Łukasz Langa26d513c2010-11-10 18:57:39 +0000760
761Legacy API Examples
762-------------------
763
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000764Mainly because of backwards compatibility concerns, :mod:`configparser`
765provides also a legacy API with explicit ``get``/``set`` methods. While there
766are valid use cases for the methods outlined below, mapping protocol access is
767preferred for new projects. The legacy API is at times more advanced,
768low-level and downright counterintuitive.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000769
770An example of writing to a configuration file::
771
772 import configparser
773
774 config = configparser.RawConfigParser()
775
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000776 # Please note that using RawConfigParser's set functions, you can assign
777 # non-string values to keys internally, but will receive an error when
778 # attempting to write to a file or when you get it in non-raw mode. Setting
779 # values using the mapping protocol or ConfigParser's set() does not allow
780 # such assignments to take place.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000781 config.add_section('Section1')
R David Murray1a1883d2012-09-29 14:40:23 -0400782 config.set('Section1', 'an_int', '15')
783 config.set('Section1', 'a_bool', 'true')
784 config.set('Section1', 'a_float', '3.1415')
Łukasz Langa26d513c2010-11-10 18:57:39 +0000785 config.set('Section1', 'baz', 'fun')
786 config.set('Section1', 'bar', 'Python')
787 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
788
789 # Writing our configuration file to 'example.cfg'
790 with open('example.cfg', 'w') as configfile:
791 config.write(configfile)
792
793An example of reading the configuration file again::
794
795 import configparser
796
797 config = configparser.RawConfigParser()
798 config.read('example.cfg')
799
800 # getfloat() raises an exception if the value is not a float
801 # getint() and getboolean() also do this for their respective types
R David Murray1a1883d2012-09-29 14:40:23 -0400802 a_float = config.getfloat('Section1', 'a_float')
803 an_int = config.getint('Section1', 'an_int')
804 print(a_float + an_int)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000805
806 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
807 # This is because we are using a RawConfigParser().
R David Murray1a1883d2012-09-29 14:40:23 -0400808 if config.getboolean('Section1', 'a_bool'):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000809 print(config.get('Section1', 'foo'))
810
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000811To get interpolation, use :class:`ConfigParser`::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000812
813 import configparser
814
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000815 cfg = configparser.ConfigParser()
Łukasz Langa26d513c2010-11-10 18:57:39 +0000816 cfg.read('example.cfg')
817
Éric Araujo941afed2011-09-01 02:47:34 +0200818 # Set the optional *raw* argument of get() to True if you wish to disable
Łukasz Langa26d513c2010-11-10 18:57:39 +0000819 # interpolation in a single get operation.
820 print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!"
821 print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!"
822
Éric Araujo941afed2011-09-01 02:47:34 +0200823 # The optional *vars* argument is a dict with members that will take
Łukasz Langa26d513c2010-11-10 18:57:39 +0000824 # precedence in interpolation.
825 print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation',
826 'baz': 'evil'}))
827
Éric Araujo941afed2011-09-01 02:47:34 +0200828 # The optional *fallback* argument can be used to provide a fallback value
Łukasz Langa26d513c2010-11-10 18:57:39 +0000829 print(cfg.get('Section1', 'foo'))
830 # -> "Python is fun!"
831
832 print(cfg.get('Section1', 'foo', fallback='Monty is not.'))
833 # -> "Python is fun!"
834
835 print(cfg.get('Section1', 'monster', fallback='No such things as monsters.'))
836 # -> "No such things as monsters."
837
838 # A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError
839 # but we can also use:
840
841 print(cfg.get('Section1', 'monster', fallback=None))
842 # -> None
843
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000844Default values are available in both types of ConfigParsers. They are used in
845interpolation if an option used is not defined elsewhere. ::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000846
847 import configparser
848
849 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000850 config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'})
Łukasz Langa26d513c2010-11-10 18:57:39 +0000851 config.read('example.cfg')
852
853 print(config.get('Section1', 'foo')) # -> "Python is fun!"
854 config.remove_option('Section1', 'bar')
855 config.remove_option('Section1', 'baz')
856 print(config.get('Section1', 'foo')) # -> "Life is hard!"
857
Georg Brandlbb27c122010-11-11 07:26:40 +0000858
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000859.. _configparser-objects:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000860
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000861ConfigParser Objects
862--------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000863
Łukasz Langab25a7912010-12-17 01:32:29 +0000864.. 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 +0000865
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000866 The main configuration parser. When *defaults* is given, it is initialized
Georg Brandl96a60ae2010-07-28 13:13:46 +0000867 into the dictionary of intrinsic defaults. When *dict_type* is given, it
868 will be used to create the dictionary objects for the list of sections, for
869 the options within a section, and for the default values.
870
Fred Drake5a7c11f2010-11-13 05:24:17 +0000871 When *delimiters* is given, it is used as the set of substrings that
Georg Brandl96a60ae2010-07-28 13:13:46 +0000872 divide keys from values. When *comment_prefixes* is given, it will be used
Łukasz Langab25a7912010-12-17 01:32:29 +0000873 as the set of substrings that prefix comments in otherwise empty lines.
874 Comments can be indented. When *inline_comment_prefixes* is given, it will be
875 used as the set of substrings that prefix comments in non-empty lines.
876
Łukasz Langab25a7912010-12-17 01:32:29 +0000877 When *strict* is ``True`` (the default), the parser won't allow for
Fred Drakea4923622010-08-09 12:52:45 +0000878 any section or option duplicates while reading from a single source (file,
879 string or dictionary), raising :exc:`DuplicateSectionError` or
Fred Drake5a7c11f2010-11-13 05:24:17 +0000880 :exc:`DuplicateOptionError`. When *empty_lines_in_values* is ``False``
Fred Drakea4923622010-08-09 12:52:45 +0000881 (default: ``True``), each empty line marks the end of an option. Otherwise,
882 internal empty lines of a multiline option are kept as part of the value.
883 When *allow_no_value* is ``True`` (default: ``False``), options without
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000884 values are accepted; the value held for these is ``None`` and they are
885 serialized without the trailing delimiter.
Fred Drake03c44a32010-02-19 06:08:41 +0000886
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000887 When *default_section* is given, it specifies the name for the special
888 section holding default values for other sections and interpolation purposes
889 (normally named ``"DEFAULT"``). This value can be retrieved and changed on
890 runtime using the ``default_section`` instance attribute.
891
892 Interpolation behaviour may be customized by providing a custom handler
893 through the *interpolation* argument. ``None`` can be used to turn off
894 interpolation completely, ``ExtendedInterpolation()`` provides a more
895 advanced variant inspired by ``zc.buildout``. More on the subject in the
896 `dedicated documentation section <#interpolation-of-values>`_.
897
898 All option names used in interpolation will be passed through the
899 :meth:`optionxform` method just like any other option name reference. For
900 example, using the default implementation of :meth:`optionxform` (which
901 converts option names to lower case), the values ``foo %(bar)s`` and ``foo
902 %(BAR)s`` are equivalent.
Georg Brandl116aa622007-08-15 14:28:22 +0000903
Raymond Hettinger231b7f12009-03-03 00:23:19 +0000904 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +0000905 The default *dict_type* is :class:`collections.OrderedDict`.
906
Fred Drake03c44a32010-02-19 06:08:41 +0000907 .. versionchanged:: 3.2
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000908 *allow_no_value*, *delimiters*, *comment_prefixes*, *strict*,
909 *empty_lines_in_values*, *default_section* and *interpolation* were
910 added.
Georg Brandl116aa622007-08-15 14:28:22 +0000911
Fred Drake03c44a32010-02-19 06:08:41 +0000912
Georg Brandlbb27c122010-11-11 07:26:40 +0000913 .. method:: defaults()
Georg Brandl116aa622007-08-15 14:28:22 +0000914
Georg Brandlbb27c122010-11-11 07:26:40 +0000915 Return a dictionary containing the instance-wide defaults.
Georg Brandl116aa622007-08-15 14:28:22 +0000916
917
Georg Brandlbb27c122010-11-11 07:26:40 +0000918 .. method:: sections()
Georg Brandl116aa622007-08-15 14:28:22 +0000919
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000920 Return a list of the sections available; the *default section* is not
921 included in the list.
Georg Brandl116aa622007-08-15 14:28:22 +0000922
923
Georg Brandlbb27c122010-11-11 07:26:40 +0000924 .. method:: add_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000925
Georg Brandlbb27c122010-11-11 07:26:40 +0000926 Add a section named *section* to the instance. If a section by the given
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000927 name already exists, :exc:`DuplicateSectionError` is raised. If the
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000928 *default section* name is passed, :exc:`ValueError` is raised. The name
929 of the section must be a string; if not, :exc:`TypeError` is raised.
930
931 .. versionchanged:: 3.2
932 Non-string section names raise :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000933
Georg Brandl116aa622007-08-15 14:28:22 +0000934
Georg Brandlbb27c122010-11-11 07:26:40 +0000935 .. method:: has_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000936
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000937 Indicates whether the named *section* is present in the configuration.
938 The *default section* is not acknowledged.
Georg Brandl116aa622007-08-15 14:28:22 +0000939
Georg Brandl116aa622007-08-15 14:28:22 +0000940
Georg Brandlbb27c122010-11-11 07:26:40 +0000941 .. method:: options(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000942
Georg Brandlbb27c122010-11-11 07:26:40 +0000943 Return a list of options available in the specified *section*.
Georg Brandl116aa622007-08-15 14:28:22 +0000944
Georg Brandl116aa622007-08-15 14:28:22 +0000945
Georg Brandlbb27c122010-11-11 07:26:40 +0000946 .. method:: has_option(section, option)
Georg Brandl116aa622007-08-15 14:28:22 +0000947
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000948 If the given *section* exists, and contains the given *option*, return
Łukasz Langa71b37a52010-12-17 21:56:32 +0000949 :const:`True`; otherwise return :const:`False`. If the specified
950 *section* is :const:`None` or an empty string, DEFAULT is assumed.
Georg Brandl116aa622007-08-15 14:28:22 +0000951
Georg Brandl116aa622007-08-15 14:28:22 +0000952
Georg Brandlbb27c122010-11-11 07:26:40 +0000953 .. method:: read(filenames, encoding=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000954
Georg Brandlbb27c122010-11-11 07:26:40 +0000955 Attempt to read and parse a list of filenames, returning a list of
956 filenames which were successfully parsed. If *filenames* is a string, it
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000957 is treated as a single filename. If a file named in *filenames* cannot
958 be opened, that file will be ignored. This is designed so that you can
959 specify a list of potential configuration file locations (for example,
960 the current directory, the user's home directory, and some system-wide
961 directory), and all existing configuration files in the list will be
962 read. If none of the named files exist, the :class:`ConfigParser`
963 instance will contain an empty dataset. An application which requires
964 initial values to be loaded from a file should load the required file or
965 files using :meth:`read_file` before calling :meth:`read` for any
966 optional files::
Georg Brandl116aa622007-08-15 14:28:22 +0000967
Georg Brandlbb27c122010-11-11 07:26:40 +0000968 import configparser, os
Georg Brandl8dcaa732010-07-29 12:17:40 +0000969
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000970 config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000971 config.read_file(open('defaults.cfg'))
972 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
973 encoding='cp1250')
Georg Brandl116aa622007-08-15 14:28:22 +0000974
Georg Brandlbb27c122010-11-11 07:26:40 +0000975 .. versionadded:: 3.2
976 The *encoding* parameter. Previously, all files were read using the
977 default encoding for :func:`open`.
Georg Brandl116aa622007-08-15 14:28:22 +0000978
Georg Brandl116aa622007-08-15 14:28:22 +0000979
Georg Brandlbb27c122010-11-11 07:26:40 +0000980 .. method:: read_file(f, source=None)
Georg Brandl73753d32009-09-22 13:53:14 +0000981
Łukasz Langadaab1c82011-04-27 18:10:05 +0200982 Read and parse configuration data from *f* which must be an iterable
Łukasz Langaba702da2011-04-28 12:02:05 +0200983 yielding Unicode strings (for example files opened in text mode).
Georg Brandl116aa622007-08-15 14:28:22 +0000984
Georg Brandlbb27c122010-11-11 07:26:40 +0000985 Optional argument *source* specifies the name of the file being read. If
Fred Drake5a7c11f2010-11-13 05:24:17 +0000986 not given and *f* has a :attr:`name` attribute, that is used for
987 *source*; the default is ``'<???>'``.
Fred Drakea4923622010-08-09 12:52:45 +0000988
Georg Brandlbb27c122010-11-11 07:26:40 +0000989 .. versionadded:: 3.2
Łukasz Langa43ae6192011-04-27 18:13:42 +0200990 Replaces :meth:`readfp`.
991
Georg Brandlbb27c122010-11-11 07:26:40 +0000992 .. method:: read_string(string, source='<string>')
Fred Drakea4923622010-08-09 12:52:45 +0000993
Fred Drake5a7c11f2010-11-13 05:24:17 +0000994 Parse configuration data from a string.
Fred Drakea4923622010-08-09 12:52:45 +0000995
Fred Drake5a7c11f2010-11-13 05:24:17 +0000996 Optional argument *source* specifies a context-specific name of the
997 string passed. If not given, ``'<string>'`` is used. This should
998 commonly be a filesystem path or a URL.
Fred Drakea4923622010-08-09 12:52:45 +0000999
Georg Brandlbb27c122010-11-11 07:26:40 +00001000 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +00001001
Fred Drakea4923622010-08-09 12:52:45 +00001002
Georg Brandlbb27c122010-11-11 07:26:40 +00001003 .. method:: read_dict(dictionary, source='<dict>')
Fred Drakea4923622010-08-09 12:52:45 +00001004
Łukasz Langa71b37a52010-12-17 21:56:32 +00001005 Load configuration from any object that provides a dict-like ``items()``
1006 method. Keys are section names, values are dictionaries with keys and
1007 values that should be present in the section. If the used dictionary
1008 type preserves order, sections and their keys will be added in order.
1009 Values are automatically converted to strings.
Fred Drakea4923622010-08-09 12:52:45 +00001010
Georg Brandlbb27c122010-11-11 07:26:40 +00001011 Optional argument *source* specifies a context-specific name of the
1012 dictionary passed. If not given, ``<dict>`` is used.
Georg Brandl116aa622007-08-15 14:28:22 +00001013
Łukasz Langa71b37a52010-12-17 21:56:32 +00001014 This method can be used to copy state between parsers.
1015
Georg Brandlbb27c122010-11-11 07:26:40 +00001016 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +00001017
Georg Brandl116aa622007-08-15 14:28:22 +00001018
Ezio Melottie927e252012-09-08 20:46:01 +03001019 .. method:: get(section, option, *, raw=False, vars=None[, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +00001020
Georg Brandlbb27c122010-11-11 07:26:40 +00001021 Get an *option* value for the named *section*. If *vars* is provided, it
1022 must be a dictionary. The *option* is looked up in *vars* (if provided),
1023 *section*, and in *DEFAULTSECT* in that order. If the key is not found
1024 and *fallback* is provided, it is used as a fallback value. ``None`` can
1025 be provided as a *fallback* value.
Georg Brandl470a1232010-07-29 14:17:12 +00001026
Georg Brandlbb27c122010-11-11 07:26:40 +00001027 All the ``'%'`` interpolations are expanded in the return values, unless
1028 the *raw* argument is true. Values for interpolation keys are looked up
1029 in the same manner as the option.
Georg Brandl116aa622007-08-15 14:28:22 +00001030
Georg Brandlbb27c122010-11-11 07:26:40 +00001031 .. versionchanged:: 3.2
1032 Arguments *raw*, *vars* and *fallback* are keyword only to protect
1033 users from trying to use the third argument as the *fallback* fallback
1034 (especially when using the mapping protocol).
Georg Brandl116aa622007-08-15 14:28:22 +00001035
Łukasz Langa26d513c2010-11-10 18:57:39 +00001036
Ezio Melottie927e252012-09-08 20:46:01 +03001037 .. method:: getint(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001038
Georg Brandlbb27c122010-11-11 07:26:40 +00001039 A convenience method which coerces the *option* in the specified *section*
1040 to an integer. See :meth:`get` for explanation of *raw*, *vars* and
1041 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001042
1043
Ezio Melottie927e252012-09-08 20:46:01 +03001044 .. method:: getfloat(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001045
Georg Brandlbb27c122010-11-11 07:26:40 +00001046 A convenience method which coerces the *option* in the specified *section*
1047 to a floating point number. See :meth:`get` for explanation of *raw*,
1048 *vars* and *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001049
1050
Ezio Melottie927e252012-09-08 20:46:01 +03001051 .. method:: getboolean(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001052
Georg Brandlbb27c122010-11-11 07:26:40 +00001053 A convenience method which coerces the *option* in the specified *section*
1054 to a Boolean value. Note that the accepted values for the option are
Fred Drake5a7c11f2010-11-13 05:24:17 +00001055 ``'1'``, ``'yes'``, ``'true'``, and ``'on'``, which cause this method to
1056 return ``True``, and ``'0'``, ``'no'``, ``'false'``, and ``'off'``, which
Georg Brandlbb27c122010-11-11 07:26:40 +00001057 cause it to return ``False``. These string values are checked in a
1058 case-insensitive manner. Any other value will cause it to raise
1059 :exc:`ValueError`. See :meth:`get` for explanation of *raw*, *vars* and
1060 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001061
1062
Ezio Melottie0add762012-09-14 06:32:35 +03001063 .. method:: items(raw=False, vars=None)
1064 items(section, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001065
Łukasz Langa71b37a52010-12-17 21:56:32 +00001066 When *section* is not given, return a list of *section_name*,
1067 *section_proxy* pairs, including DEFAULTSECT.
1068
1069 Otherwise, return a list of *name*, *value* pairs for the options in the
1070 given *section*. Optional arguments have the same meaning as for the
Georg Brandlbb27c122010-11-11 07:26:40 +00001071 :meth:`get` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001072
Łukasz Langa72547622011-05-09 18:49:42 +02001073 .. versionchanged:: 3.2
Łukasz Langa72547622011-05-09 18:49:42 +02001074 Items present in *vars* no longer appear in the result. The previous
1075 behaviour mixed actual parser options with variables provided for
1076 interpolation.
Georg Brandl116aa622007-08-15 14:28:22 +00001077
Georg Brandlbb27c122010-11-11 07:26:40 +00001078 .. method:: set(section, option, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001079
Georg Brandlbb27c122010-11-11 07:26:40 +00001080 If the given section exists, set the given option to the specified value;
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001081 otherwise raise :exc:`NoSectionError`. *option* and *value* must be
1082 strings; if not, :exc:`TypeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001083
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001084
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001085 .. method:: write(fileobject, space_around_delimiters=True)
1086
1087 Write a representation of the configuration to the specified :term:`file
1088 object`, which must be opened in text mode (accepting strings). This
1089 representation can be parsed by a future :meth:`read` call. If
1090 *space_around_delimiters* is true, delimiters between
1091 keys and values are surrounded by spaces.
1092
1093
1094 .. method:: remove_option(section, option)
1095
1096 Remove the specified *option* from the specified *section*. If the
1097 section does not exist, raise :exc:`NoSectionError`. If the option
1098 existed to be removed, return :const:`True`; otherwise return
1099 :const:`False`.
1100
1101
1102 .. method:: remove_section(section)
1103
1104 Remove the specified *section* from the configuration. If the section in
1105 fact existed, return ``True``. Otherwise return ``False``.
1106
1107
1108 .. method:: optionxform(option)
1109
1110 Transforms the option name *option* as found in an input file or as passed
1111 in by client code to the form that should be used in the internal
1112 structures. The default implementation returns a lower-case version of
1113 *option*; subclasses may override this or client code can set an attribute
1114 of this name on instances to affect this behavior.
1115
1116 You don't need to subclass the parser to use this method, you can also
1117 set it on an instance, to a function that takes a string argument and
1118 returns a string. Setting it to ``str``, for example, would make option
1119 names case sensitive::
1120
1121 cfgparser = ConfigParser()
1122 cfgparser.optionxform = str
1123
1124 Note that when reading configuration files, whitespace around the option
1125 names is stripped before :meth:`optionxform` is called.
1126
1127
1128 .. method:: readfp(fp, filename=None)
1129
1130 .. deprecated:: 3.2
1131 Use :meth:`read_file` instead.
1132
Łukasz Langaba702da2011-04-28 12:02:05 +02001133 .. versionchanged:: 3.2
1134 :meth:`readfp` now iterates on *f* instead of calling ``f.readline()``.
1135
1136 For existing code calling :meth:`readfp` with arguments which don't
1137 support iteration, the following generator may be used as a wrapper
1138 around the file-like object::
1139
1140 def readline_generator(f):
1141 line = f.readline()
1142 while line:
1143 yield line
1144 line = f.readline()
1145
1146 Instead of ``parser.readfp(f)`` use
1147 ``parser.read_file(readline_generator(f))``.
1148
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001149
1150.. data:: MAX_INTERPOLATION_DEPTH
1151
1152 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
1153 parameter is false. This is relevant only when the default *interpolation*
1154 is used.
1155
1156
1157.. _rawconfigparser-objects:
1158
1159RawConfigParser Objects
1160-----------------------
1161
Ezio Melottie927e252012-09-08 20:46:01 +03001162.. class:: RawConfigParser(defaults=None, dict_type=collections.OrderedDict, \
1163 allow_no_value=False, *, delimiters=('=', ':'), \
1164 comment_prefixes=('#', ';'), \
1165 inline_comment_prefixes=None, strict=True, \
1166 empty_lines_in_values=True, \
1167 default_section=configparser.DEFAULTSECT[, \
1168 interpolation])
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001169
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001170 Legacy variant of the :class:`ConfigParser` with interpolation disabled
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001171 by default and unsafe ``add_section`` and ``set`` methods.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001172
1173 .. note::
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001174 Consider using :class:`ConfigParser` instead which checks types of
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001175 the values to be stored internally. If you don't want interpolation, you
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001176 can use ``ConfigParser(interpolation=None)``.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001177
1178
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001179 .. method:: add_section(section)
1180
1181 Add a section named *section* to the instance. If a section by the given
1182 name already exists, :exc:`DuplicateSectionError` is raised. If the
1183 *default section* name is passed, :exc:`ValueError` is raised.
1184
1185 Type of *section* is not checked which lets users create non-string named
1186 sections. This behaviour is unsupported and may cause internal errors.
1187
1188
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001189 .. method:: set(section, option, value)
1190
1191 If the given section exists, set the given option to the specified value;
1192 otherwise raise :exc:`NoSectionError`. While it is possible to use
1193 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters
1194 set to true) for *internal* storage of non-string values, full
1195 functionality (including interpolation and output to files) can only be
1196 achieved using string values.
1197
1198 This method lets users assign non-string values to keys internally. This
1199 behaviour is unsupported and will cause errors when attempting to write
1200 to a file or get it in non-raw mode. **Use the mapping protocol API**
1201 which does not allow such assignments to take place.
1202
1203
Łukasz Langa26d513c2010-11-10 18:57:39 +00001204Exceptions
1205----------
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001206
Łukasz Langa26d513c2010-11-10 18:57:39 +00001207.. exception:: Error
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001208
Fred Drake5a7c11f2010-11-13 05:24:17 +00001209 Base class for all other :mod:`configparser` exceptions.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001210
Georg Brandl48310cd2009-01-03 21:18:54 +00001211
Łukasz Langa26d513c2010-11-10 18:57:39 +00001212.. exception:: NoSectionError
Georg Brandl48310cd2009-01-03 21:18:54 +00001213
Łukasz Langa26d513c2010-11-10 18:57:39 +00001214 Exception raised when a specified section is not found.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001215
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001216
Łukasz Langa26d513c2010-11-10 18:57:39 +00001217.. exception:: DuplicateSectionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001218
Łukasz Langa26d513c2010-11-10 18:57:39 +00001219 Exception raised if :meth:`add_section` is called with the name of a section
1220 that is already present or in strict parsers when a section if found more
1221 than once in a single input file, string or dictionary.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001222
Łukasz Langa26d513c2010-11-10 18:57:39 +00001223 .. versionadded:: 3.2
1224 Optional ``source`` and ``lineno`` attributes and arguments to
1225 :meth:`__init__` were added.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001226
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001227
Łukasz Langa26d513c2010-11-10 18:57:39 +00001228.. exception:: DuplicateOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001229
Łukasz Langa26d513c2010-11-10 18:57:39 +00001230 Exception raised by strict parsers if a single option appears twice during
1231 reading from a single file, string or dictionary. This catches misspellings
1232 and case sensitivity-related errors, e.g. a dictionary may have two keys
1233 representing the same case-insensitive configuration key.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001234
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001235
Łukasz Langa26d513c2010-11-10 18:57:39 +00001236.. exception:: NoOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001237
Łukasz Langa26d513c2010-11-10 18:57:39 +00001238 Exception raised when a specified option is not found in the specified
1239 section.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001240
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001241
Łukasz Langa26d513c2010-11-10 18:57:39 +00001242.. exception:: InterpolationError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001243
Łukasz Langa26d513c2010-11-10 18:57:39 +00001244 Base class for exceptions raised when problems occur performing string
1245 interpolation.
Georg Brandl48310cd2009-01-03 21:18:54 +00001246
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001247
Łukasz Langa26d513c2010-11-10 18:57:39 +00001248.. exception:: InterpolationDepthError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001249
Łukasz Langa26d513c2010-11-10 18:57:39 +00001250 Exception raised when string interpolation cannot be completed because the
Georg Brandlbb27c122010-11-11 07:26:40 +00001251 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
Łukasz Langa26d513c2010-11-10 18:57:39 +00001252 :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001253
Fred Drake03c44a32010-02-19 06:08:41 +00001254
Łukasz Langa26d513c2010-11-10 18:57:39 +00001255.. exception:: InterpolationMissingOptionError
Fred Drake03c44a32010-02-19 06:08:41 +00001256
Georg Brandlbb27c122010-11-11 07:26:40 +00001257 Exception raised when an option referenced from a value does not exist.
1258 Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001259
Fred Drake03c44a32010-02-19 06:08:41 +00001260
Łukasz Langa26d513c2010-11-10 18:57:39 +00001261.. exception:: InterpolationSyntaxError
Fred Drake03c44a32010-02-19 06:08:41 +00001262
Georg Brandlbb27c122010-11-11 07:26:40 +00001263 Exception raised when the source text into which substitutions are made does
1264 not conform to the required syntax. Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001265
Łukasz Langa26d513c2010-11-10 18:57:39 +00001266
1267.. exception:: MissingSectionHeaderError
1268
Georg Brandlbb27c122010-11-11 07:26:40 +00001269 Exception raised when attempting to parse a file which has no section
1270 headers.
Łukasz Langa26d513c2010-11-10 18:57:39 +00001271
1272
1273.. exception:: ParsingError
1274
1275 Exception raised when errors occur attempting to parse a file.
1276
1277 .. versionchanged:: 3.2
1278 The ``filename`` attribute and :meth:`__init__` argument were renamed to
1279 ``source`` for consistency.
1280
Georg Brandlbb27c122010-11-11 07:26:40 +00001281
1282.. rubric:: Footnotes
1283
1284.. [1] Config parsers allow for heavy customization. If you are interested in
1285 changing the behaviour outlined by the footnote reference, consult the
1286 `Customizing Parser Behaviour`_ section.