blob: c9187a3441a7f54bd2a9fd40093570c0336dc34a [file] [log] [blame]
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00001:mod:`configparser` --- Configuration file parser
Georg Brandl116aa622007-08-15 14:28:22 +00002=================================================
3
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00004.. module:: configparser
Georg Brandl116aa622007-08-15 14:28:22 +00005 :synopsis: Configuration file parser.
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. moduleauthor:: Ken Manheimer <klm@zope.com>
8.. moduleauthor:: Barry Warsaw <bwarsaw@python.org>
9.. moduleauthor:: Eric S. Raymond <esr@thyrsus.com>
Łukasz Langa26d513c2010-11-10 18:57:39 +000010.. moduleauthor:: Łukasz Langa <lukasz@langa.pl>
Georg Brandl116aa622007-08-15 14:28:22 +000011.. sectionauthor:: Christopher G. Petrilli <petrilli@amber.org>
Łukasz Langa26d513c2010-11-10 18:57:39 +000012.. sectionauthor:: Łukasz Langa <lukasz@langa.pl>
Georg Brandl116aa622007-08-15 14:28:22 +000013
Andrew Kuchling2e3743c2014-03-19 16:23:01 -040014**Source code:** :source:`Lib/configparser.py`
15
Georg Brandl116aa622007-08-15 14:28:22 +000016.. index::
17 pair: .ini; file
18 pair: configuration; file
19 single: ini file
20 single: Windows ini file
21
Łukasz Langa7f64c8a2010-12-16 01:16:22 +000022This module provides the :class:`ConfigParser` class which implements a basic
23configuration language which provides a structure similar to what's found in
24Microsoft Windows INI files. You can use this to write Python programs which
25can be customized by end users easily.
Georg Brandl116aa622007-08-15 14:28:22 +000026
Georg Brandle720c0a2009-04-27 16:20:50 +000027.. note::
Georg Brandl116aa622007-08-15 14:28:22 +000028
Georg Brandle720c0a2009-04-27 16:20:50 +000029 This library does *not* interpret or write the value-type prefixes used in
30 the Windows Registry extended version of INI syntax.
Georg Brandl116aa622007-08-15 14:28:22 +000031
Łukasz Langa26d513c2010-11-10 18:57:39 +000032.. seealso::
33
34 Module :mod:`shlex`
35 Support for a creating Unix shell-like mini-languages which can be used
36 as an alternate format for application configuration files.
37
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000038 Module :mod:`json`
39 The json module implements a subset of JavaScript syntax which can also
40 be used for this purpose.
41
Georg Brandlbb27c122010-11-11 07:26:40 +000042
Łukasz Langa26d513c2010-11-10 18:57:39 +000043Quick Start
44-----------
45
Georg Brandlbb27c122010-11-11 07:26:40 +000046Let's take a very basic configuration file that looks like this:
Łukasz Langa26d513c2010-11-10 18:57:39 +000047
Georg Brandlbb27c122010-11-11 07:26:40 +000048.. code-block:: ini
Łukasz Langa26d513c2010-11-10 18:57:39 +000049
Georg Brandlbb27c122010-11-11 07:26:40 +000050 [DEFAULT]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000051 ServerAliveInterval = 45
52 Compression = yes
53 CompressionLevel = 9
54 ForwardX11 = yes
Łukasz Langa26d513c2010-11-10 18:57:39 +000055
Georg Brandlbb27c122010-11-11 07:26:40 +000056 [bitbucket.org]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000057 User = hg
Łukasz Langa26d513c2010-11-10 18:57:39 +000058
Georg Brandlbb27c122010-11-11 07:26:40 +000059 [topsecret.server.com]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000060 Port = 50022
61 ForwardX11 = no
Łukasz Langa26d513c2010-11-10 18:57:39 +000062
Fred Drake5a7c11f2010-11-13 05:24:17 +000063The structure of INI files is described `in the following section
64<#supported-ini-file-structure>`_. Essentially, the file
Łukasz Langa26d513c2010-11-10 18:57:39 +000065consists of sections, each of which contains keys with values.
Georg Brandlbb27c122010-11-11 07:26:40 +000066:mod:`configparser` classes can read and write such files. Let's start by
Łukasz Langa26d513c2010-11-10 18:57:39 +000067creating the above configuration file programatically.
68
Łukasz Langa26d513c2010-11-10 18:57:39 +000069.. doctest::
70
Georg Brandlbb27c122010-11-11 07:26:40 +000071 >>> import configparser
Łukasz Langa7f64c8a2010-12-16 01:16:22 +000072 >>> config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +000073 >>> config['DEFAULT'] = {'ServerAliveInterval': '45',
74 ... 'Compression': 'yes',
75 ... 'CompressionLevel': '9'}
76 >>> config['bitbucket.org'] = {}
77 >>> config['bitbucket.org']['User'] = 'hg'
78 >>> config['topsecret.server.com'] = {}
79 >>> topsecret = config['topsecret.server.com']
80 >>> topsecret['Port'] = '50022' # mutates the parser
81 >>> topsecret['ForwardX11'] = 'no' # same here
82 >>> config['DEFAULT']['ForwardX11'] = 'yes'
83 >>> with open('example.ini', 'w') as configfile:
84 ... config.write(configfile)
85 ...
Łukasz Langa26d513c2010-11-10 18:57:39 +000086
Fred Drake5a7c11f2010-11-13 05:24:17 +000087As you can see, we can treat a config parser much like a dictionary.
88There are differences, `outlined later <#mapping-protocol-access>`_, but
89the behavior is very close to what you would expect from a dictionary.
Łukasz Langa26d513c2010-11-10 18:57:39 +000090
Fred Drake5a7c11f2010-11-13 05:24:17 +000091Now that we have created and saved a configuration file, let's read it
92back and explore the data it holds.
Łukasz Langa26d513c2010-11-10 18:57:39 +000093
Łukasz Langa26d513c2010-11-10 18:57:39 +000094.. doctest::
95
Georg Brandlbb27c122010-11-11 07:26:40 +000096 >>> import configparser
Łukasz Langa7f64c8a2010-12-16 01:16:22 +000097 >>> config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +000098 >>> config.sections()
99 []
100 >>> config.read('example.ini')
101 ['example.ini']
102 >>> config.sections()
103 ['bitbucket.org', 'topsecret.server.com']
104 >>> 'bitbucket.org' in config
105 True
106 >>> 'bytebong.com' in config
107 False
108 >>> config['bitbucket.org']['User']
109 'hg'
110 >>> config['DEFAULT']['Compression']
111 'yes'
112 >>> topsecret = config['topsecret.server.com']
113 >>> topsecret['ForwardX11']
114 'no'
115 >>> topsecret['Port']
116 '50022'
117 >>> for key in config['bitbucket.org']: print(key)
118 ...
119 user
120 compressionlevel
121 serveraliveinterval
122 compression
123 forwardx11
124 >>> config['bitbucket.org']['ForwardX11']
125 'yes'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000126
Fred Drake5a7c11f2010-11-13 05:24:17 +0000127As we can see above, the API is pretty straightforward. The only bit of magic
Łukasz Langa26d513c2010-11-10 18:57:39 +0000128involves the ``DEFAULT`` section which provides default values for all other
Fred Drake5a7c11f2010-11-13 05:24:17 +0000129sections [1]_. Note also that keys in sections are
130case-insensitive and stored in lowercase [1]_.
Georg Brandlbb27c122010-11-11 07:26:40 +0000131
Łukasz Langa26d513c2010-11-10 18:57:39 +0000132
133Supported Datatypes
134-------------------
135
136Config parsers do not guess datatypes of values in configuration files, always
Georg Brandlbb27c122010-11-11 07:26:40 +0000137storing them internally as strings. This means that if you need other
138datatypes, you should convert on your own:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000139
Łukasz Langa26d513c2010-11-10 18:57:39 +0000140.. doctest::
141
Georg Brandlbb27c122010-11-11 07:26:40 +0000142 >>> int(topsecret['Port'])
143 50022
144 >>> float(topsecret['CompressionLevel'])
145 9.0
Łukasz Langa26d513c2010-11-10 18:57:39 +0000146
Łukasz Langa34cea142014-09-14 23:37:03 -0700147Since this task is so common, config parsers provide a range of handy getter
148methods to handle integers, floats and booleans. The last one is the most
149interesting because simply passing the value to ``bool()`` would do no good
150since ``bool('False')`` is still ``True``. This is why config parsers also
151provide :meth:`getboolean`. This method is case-insensitive and recognizes
152Boolean values from ``'yes'``/``'no'``, ``'on'``/``'off'``,
153``'true'``/``'false'`` and ``'1'``/``'0'`` [1]_. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000154
Łukasz Langa26d513c2010-11-10 18:57:39 +0000155.. doctest::
156
Georg Brandlbb27c122010-11-11 07:26:40 +0000157 >>> topsecret.getboolean('ForwardX11')
158 False
159 >>> config['bitbucket.org'].getboolean('ForwardX11')
160 True
161 >>> config.getboolean('bitbucket.org', 'Compression')
162 True
Łukasz Langa26d513c2010-11-10 18:57:39 +0000163
164Apart from :meth:`getboolean`, config parsers also provide equivalent
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700165:meth:`getint` and :meth:`getfloat` methods. You can register your own
166converters and customize the provided ones. [1]_
Georg Brandlbb27c122010-11-11 07:26:40 +0000167
Łukasz Langa26d513c2010-11-10 18:57:39 +0000168Fallback Values
169---------------
170
Fred Drake5a7c11f2010-11-13 05:24:17 +0000171As with a dictionary, you can use a section's :meth:`get` method to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000172provide fallback values:
173
Łukasz Langa26d513c2010-11-10 18:57:39 +0000174.. doctest::
175
Georg Brandlbb27c122010-11-11 07:26:40 +0000176 >>> topsecret.get('Port')
177 '50022'
178 >>> topsecret.get('CompressionLevel')
179 '9'
180 >>> topsecret.get('Cipher')
181 >>> topsecret.get('Cipher', '3des-cbc')
182 '3des-cbc'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000183
Fred Drake5a7c11f2010-11-13 05:24:17 +0000184Please note that default values have precedence over fallback values.
185For instance, in our example the ``'CompressionLevel'`` key was
186specified only in the ``'DEFAULT'`` section. If we try to get it from
187the section ``'topsecret.server.com'``, we will always get the default,
188even if we specify a fallback:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000189
Łukasz Langa26d513c2010-11-10 18:57:39 +0000190.. doctest::
191
Georg Brandlbb27c122010-11-11 07:26:40 +0000192 >>> topsecret.get('CompressionLevel', '3')
193 '9'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000194
195One more thing to be aware of is that the parser-level :meth:`get` method
196provides a custom, more complex interface, maintained for backwards
Fred Drake5a7c11f2010-11-13 05:24:17 +0000197compatibility. When using this method, a fallback value can be provided via
198the ``fallback`` keyword-only argument:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000199
Łukasz Langa26d513c2010-11-10 18:57:39 +0000200.. doctest::
201
Georg Brandlbb27c122010-11-11 07:26:40 +0000202 >>> config.get('bitbucket.org', 'monster',
203 ... fallback='No such things as monsters')
204 'No such things as monsters'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000205
206The same ``fallback`` argument can be used with the :meth:`getint`,
207:meth:`getfloat` and :meth:`getboolean` methods, for example:
208
Łukasz Langa26d513c2010-11-10 18:57:39 +0000209.. doctest::
210
Georg Brandlbb27c122010-11-11 07:26:40 +0000211 >>> 'BatchMode' in topsecret
212 False
213 >>> topsecret.getboolean('BatchMode', fallback=True)
214 True
215 >>> config['DEFAULT']['BatchMode'] = 'no'
216 >>> topsecret.getboolean('BatchMode', fallback=True)
217 False
218
Łukasz Langa26d513c2010-11-10 18:57:39 +0000219
220Supported INI File Structure
221----------------------------
222
Georg Brandl96a60ae2010-07-28 13:13:46 +0000223A configuration file consists of sections, each led by a ``[section]`` header,
Fred Drakea4923622010-08-09 12:52:45 +0000224followed by key/value entries separated by a specific string (``=`` or ``:`` by
Georg Brandlbb27c122010-11-11 07:26:40 +0000225default [1]_). By default, section names are case sensitive but keys are not
Fred Drake5a7c11f2010-11-13 05:24:17 +0000226[1]_. Leading and trailing whitespace is removed from keys and values.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000227Values can be omitted, in which case the key/value delimiter may also be left
228out. Values can also span multiple lines, as long as they are indented deeper
229than the first line of the value. Depending on the parser's mode, blank lines
230may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000231
Fred Drake5a7c11f2010-11-13 05:24:17 +0000232Configuration files may include comments, prefixed by specific
233characters (``#`` and ``;`` by default [1]_). Comments may appear on
Łukasz Langab25a7912010-12-17 01:32:29 +0000234their own on an otherwise empty line, possibly indented. [1]_
Georg Brandl96a60ae2010-07-28 13:13:46 +0000235
Georg Brandlbb27c122010-11-11 07:26:40 +0000236For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000237
Georg Brandlbb27c122010-11-11 07:26:40 +0000238.. code-block:: ini
Georg Brandl116aa622007-08-15 14:28:22 +0000239
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000240 [Simple Values]
Łukasz Langab25a7912010-12-17 01:32:29 +0000241 key=value
242 spaces in keys=allowed
243 spaces in values=allowed as well
244 spaces around the delimiter = obviously
245 you can also use : to delimit keys from values
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000246
247 [All Values Are Strings]
248 values like this: 1000000
249 or this: 3.14159265359
250 are they treated as numbers? : no
251 integers, floats and booleans are held as: strings
252 can use the API to get converted values directly: true
Georg Brandl116aa622007-08-15 14:28:22 +0000253
Georg Brandl96a60ae2010-07-28 13:13:46 +0000254 [Multiline Values]
255 chorus: I'm a lumberjack, and I'm okay
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000256 I sleep all night and I work all day
Georg Brandl116aa622007-08-15 14:28:22 +0000257
Georg Brandl96a60ae2010-07-28 13:13:46 +0000258 [No Values]
259 key_without_value
260 empty string value here =
Georg Brandl116aa622007-08-15 14:28:22 +0000261
Łukasz Langab25a7912010-12-17 01:32:29 +0000262 [You can use comments]
263 # like this
264 ; or this
265
266 # By default only in an empty line.
267 # Inline comments can be harmful because they prevent users
268 # from using the delimiting characters as parts of values.
269 # That being said, this can be customized.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000270
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000271 [Sections Can Be Indented]
272 can_values_be_as_well = True
273 does_that_mean_anything_special = False
274 purpose = formatting for readability
275 multiline_values = are
276 handled just fine as
277 long as they are indented
278 deeper than the first line
279 of a value
280 # Did I mention we can indent comments, too?
Georg Brandl116aa622007-08-15 14:28:22 +0000281
Georg Brandl96a60ae2010-07-28 13:13:46 +0000282
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000283Interpolation of values
284-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000285
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000286On top of the core functionality, :class:`ConfigParser` supports
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000287interpolation. This means values can be preprocessed before returning them
288from ``get()`` calls.
289
290.. class:: BasicInterpolation()
291
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000292 The default implementation used by :class:`ConfigParser`. It enables
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000293 values to contain format strings which refer to other values in the same
294 section, or values in the special default section [1]_. Additional default
295 values can be provided on initialization.
296
297 For example:
298
299 .. code-block:: ini
300
301 [Paths]
302 home_dir: /Users
303 my_dir: %(home_dir)s/lumberjack
304 my_pictures: %(my_dir)s/Pictures
305
306
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000307 In the example above, :class:`ConfigParser` with *interpolation* set to
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000308 ``BasicInterpolation()`` would resolve ``%(home_dir)s`` to the value of
309 ``home_dir`` (``/Users`` in this case). ``%(my_dir)s`` in effect would
310 resolve to ``/Users/lumberjack``. All interpolations are done on demand so
311 keys used in the chain of references do not have to be specified in any
312 specific order in the configuration file.
313
314 With ``interpolation`` set to ``None``, the parser would simply return
315 ``%(my_dir)s/Pictures`` as the value of ``my_pictures`` and
316 ``%(home_dir)s/lumberjack`` as the value of ``my_dir``.
317
318.. class:: ExtendedInterpolation()
319
320 An alternative handler for interpolation which implements a more advanced
Łukasz Langa34cea142014-09-14 23:37:03 -0700321 syntax, used for instance in ``zc.buildout``. Extended interpolation is
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000322 using ``${section:option}`` to denote a value from a foreign section.
Łukasz Langa34cea142014-09-14 23:37:03 -0700323 Interpolation can span multiple levels. For convenience, if the
324 ``section:`` part is omitted, interpolation defaults to the current section
325 (and possibly the default values from the special section).
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000326
327 For example, the configuration specified above with basic interpolation,
328 would look like this with extended interpolation:
329
330 .. code-block:: ini
331
332 [Paths]
333 home_dir: /Users
334 my_dir: ${home_dir}/lumberjack
335 my_pictures: ${my_dir}/Pictures
336
337 Values from other sections can be fetched as well:
338
339 .. code-block:: ini
340
341 [Common]
342 home_dir: /Users
343 library_dir: /Library
344 system_dir: /System
345 macports_dir: /opt/local
346
347 [Frameworks]
348 Python: 3.2
349 path: ${Common:system_dir}/Library/Frameworks/
350
351 [Arthur]
352 nickname: Two Sheds
353 last_name: Jackson
354 my_dir: ${Common:home_dir}/twosheds
355 my_pictures: ${my_dir}/Pictures
356 python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
Georg Brandlbb27c122010-11-11 07:26:40 +0000357
Łukasz Langa26d513c2010-11-10 18:57:39 +0000358Mapping Protocol Access
359-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000360
Łukasz Langa26d513c2010-11-10 18:57:39 +0000361.. versionadded:: 3.2
Georg Brandl96a60ae2010-07-28 13:13:46 +0000362
Łukasz Langa26d513c2010-11-10 18:57:39 +0000363Mapping protocol access is a generic name for functionality that enables using
Georg Brandlbb27c122010-11-11 07:26:40 +0000364custom objects as if they were dictionaries. In case of :mod:`configparser`,
Łukasz Langa26d513c2010-11-10 18:57:39 +0000365the mapping interface implementation is using the
366``parser['section']['option']`` notation.
367
368``parser['section']`` in particular returns a proxy for the section's data in
Georg Brandlbb27c122010-11-11 07:26:40 +0000369the parser. This means that the values are not copied but they are taken from
370the original parser on demand. What's even more important is that when values
Łukasz Langa26d513c2010-11-10 18:57:39 +0000371are changed on a section proxy, they are actually mutated in the original
372parser.
373
374:mod:`configparser` objects behave as close to actual dictionaries as possible.
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300375The mapping interface is complete and adheres to the
376:class:`~collections.abc.MutableMapping` ABC.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000377However, there are a few differences that should be taken into account:
378
Georg Brandlbb27c122010-11-11 07:26:40 +0000379* By default, all keys in sections are accessible in a case-insensitive manner
380 [1]_. E.g. ``for option in parser["section"]`` yields only ``optionxform``'ed
381 option key names. This means lowercased keys by default. At the same time,
Fred Drake5a7c11f2010-11-13 05:24:17 +0000382 for a section that holds the key ``'a'``, both expressions return ``True``::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000383
Georg Brandlbb27c122010-11-11 07:26:40 +0000384 "a" in parser["section"]
385 "A" in parser["section"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000386
Georg Brandlbb27c122010-11-11 07:26:40 +0000387* All sections include ``DEFAULTSECT`` values as well which means that
388 ``.clear()`` on a section may not leave the section visibly empty. This is
Łukasz Langa26d513c2010-11-10 18:57:39 +0000389 because default values cannot be deleted from the section (because technically
Donald Stufft8b852f12014-05-20 12:58:38 -0400390 they are not there). If they are overridden in the section, deleting causes
Georg Brandlbb27c122010-11-11 07:26:40 +0000391 the default value to be visible again. Trying to delete a default value
392 causes a ``KeyError``.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000393
Łukasz Langa3a8479a2012-12-31 03:38:39 +0100394* ``DEFAULTSECT`` cannot be removed from the parser:
395
396 * trying to delete it raises ``ValueError``,
397
398 * ``parser.clear()`` leaves it intact,
399
400 * ``parser.popitem()`` never returns it.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000401
Łukasz Langa71b37a52010-12-17 21:56:32 +0000402* ``parser.get(section, option, **kwargs)`` - the second argument is **not**
Łukasz Langa34cea142014-09-14 23:37:03 -0700403 a fallback value. Note however that the section-level ``get()`` methods are
Łukasz Langa71b37a52010-12-17 21:56:32 +0000404 compatible both with the mapping protocol and the classic configparser API.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000405
Łukasz Langa71b37a52010-12-17 21:56:32 +0000406* ``parser.items()`` is compatible with the mapping protocol (returns a list of
407 *section_name*, *section_proxy* pairs including the DEFAULTSECT). However,
408 this method can also be invoked with arguments: ``parser.items(section, raw,
Łukasz Langa34cea142014-09-14 23:37:03 -0700409 vars)``. The latter call returns a list of *option*, *value* pairs for
Łukasz Langa71b37a52010-12-17 21:56:32 +0000410 a specified ``section``, with all interpolations expanded (unless
411 ``raw=True`` is provided).
Łukasz Langa26d513c2010-11-10 18:57:39 +0000412
413The mapping protocol is implemented on top of the existing legacy API so that
Łukasz Langa71b37a52010-12-17 21:56:32 +0000414subclasses overriding the original interface still should have mappings working
415as expected.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000416
Georg Brandlbb27c122010-11-11 07:26:40 +0000417
Łukasz Langa26d513c2010-11-10 18:57:39 +0000418Customizing Parser Behaviour
419----------------------------
420
421There are nearly as many INI format variants as there are applications using it.
422:mod:`configparser` goes a long way to provide support for the largest sensible
Georg Brandlbb27c122010-11-11 07:26:40 +0000423set of INI styles available. The default functionality is mainly dictated by
Łukasz Langa26d513c2010-11-10 18:57:39 +0000424historical background and it's very likely that you will want to customize some
425of the features.
426
Fred Drake5a7c11f2010-11-13 05:24:17 +0000427The most common way to change the way a specific config parser works is to use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000428the :meth:`__init__` options:
429
430* *defaults*, default value: ``None``
431
432 This option accepts a dictionary of key-value pairs which will be initially
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000433 put in the ``DEFAULT`` section. This makes for an elegant way to support
434 concise configuration files that don't specify values which are the same as
435 the documented default.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000436
Fred Drake5a7c11f2010-11-13 05:24:17 +0000437 Hint: if you want to specify default values for a specific section, use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000438 :meth:`read_dict` before you read the actual file.
439
440* *dict_type*, default value: :class:`collections.OrderedDict`
441
442 This option has a major impact on how the mapping protocol will behave and how
Fred Drake5a7c11f2010-11-13 05:24:17 +0000443 the written configuration files look. With the default ordered
Łukasz Langa26d513c2010-11-10 18:57:39 +0000444 dictionary, every section is stored in the order they were added to the
Georg Brandlbb27c122010-11-11 07:26:40 +0000445 parser. Same goes for options within sections.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000446
447 An alternative dictionary type can be used for example to sort sections and
Georg Brandlbb27c122010-11-11 07:26:40 +0000448 options on write-back. You can also use a regular dictionary for performance
Łukasz Langa26d513c2010-11-10 18:57:39 +0000449 reasons.
450
451 Please note: there are ways to add a set of key-value pairs in a single
Georg Brandlbb27c122010-11-11 07:26:40 +0000452 operation. When you use a regular dictionary in those operations, the order
453 of the keys may be random. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000454
Łukasz Langa26d513c2010-11-10 18:57:39 +0000455 .. doctest::
456
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000457 >>> parser = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000458 >>> parser.read_dict({'section1': {'key1': 'value1',
459 ... 'key2': 'value2',
460 ... 'key3': 'value3'},
461 ... 'section2': {'keyA': 'valueA',
462 ... 'keyB': 'valueB',
463 ... 'keyC': 'valueC'},
464 ... 'section3': {'foo': 'x',
465 ... 'bar': 'y',
466 ... 'baz': 'z'}
467 ... })
468 >>> parser.sections()
469 ['section3', 'section2', 'section1']
470 >>> [option for option in parser['section3']]
471 ['baz', 'foo', 'bar']
Łukasz Langa26d513c2010-11-10 18:57:39 +0000472
473 In these operations you need to use an ordered dictionary as well:
474
Łukasz Langa26d513c2010-11-10 18:57:39 +0000475 .. doctest::
476
Georg Brandlbb27c122010-11-11 07:26:40 +0000477 >>> from collections import OrderedDict
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000478 >>> parser = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000479 >>> parser.read_dict(
480 ... OrderedDict((
481 ... ('s1',
482 ... OrderedDict((
483 ... ('1', '2'),
484 ... ('3', '4'),
485 ... ('5', '6'),
486 ... ))
487 ... ),
488 ... ('s2',
489 ... OrderedDict((
490 ... ('a', 'b'),
491 ... ('c', 'd'),
492 ... ('e', 'f'),
493 ... ))
494 ... ),
495 ... ))
496 ... )
497 >>> parser.sections()
498 ['s1', 's2']
499 >>> [option for option in parser['s1']]
500 ['1', '3', '5']
501 >>> [option for option in parser['s2'].values()]
502 ['b', 'd', 'f']
Łukasz Langa26d513c2010-11-10 18:57:39 +0000503
504* *allow_no_value*, default value: ``False``
505
506 Some configuration files are known to include settings without values, but
507 which otherwise conform to the syntax supported by :mod:`configparser`. The
Fred Drake5a7c11f2010-11-13 05:24:17 +0000508 *allow_no_value* parameter to the constructor can be used to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000509 indicate that such values should be accepted:
510
Łukasz Langa26d513c2010-11-10 18:57:39 +0000511 .. doctest::
512
Georg Brandlbb27c122010-11-11 07:26:40 +0000513 >>> import configparser
Łukasz Langa26d513c2010-11-10 18:57:39 +0000514
Georg Brandlbb27c122010-11-11 07:26:40 +0000515 >>> sample_config = """
516 ... [mysqld]
517 ... user = mysql
518 ... pid-file = /var/run/mysqld/mysqld.pid
519 ... skip-external-locking
520 ... old_passwords = 1
521 ... skip-bdb
Łukasz Langab25a7912010-12-17 01:32:29 +0000522 ... # we don't need ACID today
523 ... skip-innodb
Georg Brandlbb27c122010-11-11 07:26:40 +0000524 ... """
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000525 >>> config = configparser.ConfigParser(allow_no_value=True)
Georg Brandlbb27c122010-11-11 07:26:40 +0000526 >>> config.read_string(sample_config)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000527
Georg Brandlbb27c122010-11-11 07:26:40 +0000528 >>> # Settings with values are treated as before:
529 >>> config["mysqld"]["user"]
530 'mysql'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000531
Georg Brandlbb27c122010-11-11 07:26:40 +0000532 >>> # Settings without values provide None:
533 >>> config["mysqld"]["skip-bdb"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000534
Georg Brandlbb27c122010-11-11 07:26:40 +0000535 >>> # Settings which aren't specified still raise an error:
536 >>> config["mysqld"]["does-not-exist"]
537 Traceback (most recent call last):
538 ...
539 KeyError: 'does-not-exist'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000540
541* *delimiters*, default value: ``('=', ':')``
542
Łukasz Langa34cea142014-09-14 23:37:03 -0700543 Delimiters are substrings that delimit keys from values within a section.
544 The first occurrence of a delimiting substring on a line is considered
545 a delimiter. This means values (but not keys) can contain the delimiters.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000546
547 See also the *space_around_delimiters* argument to
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000548 :meth:`ConfigParser.write`.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000549
Łukasz Langab25a7912010-12-17 01:32:29 +0000550* *comment_prefixes*, default value: ``('#', ';')``
Łukasz Langa26d513c2010-11-10 18:57:39 +0000551
Łukasz Langab25a7912010-12-17 01:32:29 +0000552* *inline_comment_prefixes*, default value: ``None``
553
554 Comment prefixes are strings that indicate the start of a valid comment within
555 a config file. *comment_prefixes* are used only on otherwise empty lines
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700556 (optionally indented) whereas *inline_comment_prefixes* can be used after
557 every valid value (e.g. section names, options and empty lines as well). By
558 default inline comments are disabled and ``'#'`` and ``';'`` are used as
559 prefixes for whole line comments.
Łukasz Langab25a7912010-12-17 01:32:29 +0000560
561 .. versionchanged:: 3.2
562 In previous versions of :mod:`configparser` behaviour matched
563 ``comment_prefixes=('#',';')`` and ``inline_comment_prefixes=(';',)``.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000564
565 Please note that config parsers don't support escaping of comment prefixes so
Łukasz Langab25a7912010-12-17 01:32:29 +0000566 using *inline_comment_prefixes* may prevent users from specifying option
Łukasz Langa34cea142014-09-14 23:37:03 -0700567 values with characters used as comment prefixes. When in doubt, avoid
568 setting *inline_comment_prefixes*. In any circumstances, the only way of
569 storing comment prefix characters at the beginning of a line in multiline
570 values is to interpolate the prefix, for example::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000571
Łukasz Langab25a7912010-12-17 01:32:29 +0000572 >>> from configparser import ConfigParser, ExtendedInterpolation
573 >>> parser = ConfigParser(interpolation=ExtendedInterpolation())
574 >>> # the default BasicInterpolation could be used as well
575 >>> parser.read_string("""
576 ... [DEFAULT]
577 ... hash = #
578 ...
579 ... [hashes]
580 ... shebang =
581 ... ${hash}!/usr/bin/env python
582 ... ${hash} -*- coding: utf-8 -*-
583 ...
584 ... extensions =
585 ... enabled_extension
586 ... another_extension
587 ... #disabled_by_comment
588 ... yet_another_extension
589 ...
590 ... interpolation not necessary = if # is not at line start
591 ... even in multiline values = line #1
592 ... line #2
593 ... line #3
594 ... """)
595 >>> print(parser['hashes']['shebang'])
Łukasz Langa26d513c2010-11-10 18:57:39 +0000596
Łukasz Langab25a7912010-12-17 01:32:29 +0000597 #!/usr/bin/env python
598 # -*- coding: utf-8 -*-
599 >>> print(parser['hashes']['extensions'])
600
601 enabled_extension
602 another_extension
603 yet_another_extension
604 >>> print(parser['hashes']['interpolation not necessary'])
605 if # is not at line start
606 >>> print(parser['hashes']['even in multiline values'])
607 line #1
608 line #2
609 line #3
610
611* *strict*, default value: ``True``
612
613 When set to ``True``, the parser will not allow for any section or option
Łukasz Langa26d513c2010-11-10 18:57:39 +0000614 duplicates while reading from a single source (using :meth:`read_file`,
Łukasz Langa34cea142014-09-14 23:37:03 -0700615 :meth:`read_string` or :meth:`read_dict`). It is recommended to use strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000616 parsers in new applications.
617
Łukasz Langab25a7912010-12-17 01:32:29 +0000618 .. versionchanged:: 3.2
619 In previous versions of :mod:`configparser` behaviour matched
620 ``strict=False``.
621
Łukasz Langa26d513c2010-11-10 18:57:39 +0000622* *empty_lines_in_values*, default value: ``True``
623
Fred Drake5a7c11f2010-11-13 05:24:17 +0000624 In config parsers, values can span multiple lines as long as they are
625 indented more than the key that holds them. By default parsers also let
626 empty lines to be parts of values. At the same time, keys can be arbitrarily
627 indented themselves to improve readability. In consequence, when
628 configuration files get big and complex, it is easy for the user to lose
629 track of the file structure. Take for instance:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000630
Georg Brandlbb27c122010-11-11 07:26:40 +0000631 .. code-block:: ini
Łukasz Langa26d513c2010-11-10 18:57:39 +0000632
Georg Brandlbb27c122010-11-11 07:26:40 +0000633 [Section]
634 key = multiline
635 value with a gotcha
Łukasz Langa26d513c2010-11-10 18:57:39 +0000636
Georg Brandlbb27c122010-11-11 07:26:40 +0000637 this = is still a part of the multiline value of 'key'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000638
Georg Brandlbb27c122010-11-11 07:26:40 +0000639 This can be especially problematic for the user to see if she's using a
640 proportional font to edit the file. That is why when your application does
641 not need values with empty lines, you should consider disallowing them. This
642 will make empty lines split keys every time. In the example above, it would
Łukasz Langa26d513c2010-11-10 18:57:39 +0000643 produce two keys, ``key`` and ``this``.
644
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000645* *default_section*, default value: ``configparser.DEFAULTSECT`` (that is:
646 ``"DEFAULT"``)
647
648 The convention of allowing a special section of default values for other
649 sections or interpolation purposes is a powerful concept of this library,
Łukasz Langa34cea142014-09-14 23:37:03 -0700650 letting users create complex declarative configurations. This section is
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000651 normally called ``"DEFAULT"`` but this can be customized to point to any
Łukasz Langa34cea142014-09-14 23:37:03 -0700652 other valid section name. Some typical values include: ``"general"`` or
653 ``"common"``. The name provided is used for recognizing default sections
654 when reading from any source and is used when writing configuration back to
655 a file. Its current value can be retrieved using the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000656 ``parser_instance.default_section`` attribute and may be modified at runtime
657 (i.e. to convert files from one format to another).
658
659* *interpolation*, default value: ``configparser.BasicInterpolation``
660
661 Interpolation behaviour may be customized by providing a custom handler
662 through the *interpolation* argument. ``None`` can be used to turn off
663 interpolation completely, ``ExtendedInterpolation()`` provides a more
Łukasz Langa34cea142014-09-14 23:37:03 -0700664 advanced variant inspired by ``zc.buildout``. More on the subject in the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000665 `dedicated documentation section <#interpolation-of-values>`_.
Łukasz Langab25a7912010-12-17 01:32:29 +0000666 :class:`RawConfigParser` has a default value of ``None``.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000667
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700668* *converters*, default value: not set
669
670 Config parsers provide option value getters that perform type conversion. By
671 default :meth:`getint`, :meth:`getfloat`, and :meth:`getboolean` are
672 implemented. Should other getters be desirable, users may define them in
673 a subclass or pass a dictionary where each key is a name of the converter and
674 each value is a callable implementing said conversion. For instance, passing
675 ``{'decimal': decimal.Decimal}`` would add :meth:`getdecimal` on both the
676 parser object and all section proxies. In other words, it will be possible
677 to write both ``parser_instance.getdecimal('section', 'key', fallback=0)``
678 and ``parser_instance['section'].getdecimal('key', 0)``.
679
680 If the converter needs to access the state of the parser, it can be
681 implemented as a method on a config parser subclass. If the name of this
682 method starts with ``get``, it will be available on all section proxies, in
683 the dict-compatible form (see the ``getdecimal()`` example above).
Łukasz Langa26d513c2010-11-10 18:57:39 +0000684
Fred Drake5a7c11f2010-11-13 05:24:17 +0000685More advanced customization may be achieved by overriding default values of
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700686these parser attributes. The defaults are defined on the classes, so they may
687be overridden by subclasses or by attribute assignment.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000688
Fred Drake5a7c11f2010-11-13 05:24:17 +0000689.. attribute:: BOOLEAN_STATES
Łukasz Langa26d513c2010-11-10 18:57:39 +0000690
691 By default when using :meth:`getboolean`, config parsers consider the
692 following values ``True``: ``'1'``, ``'yes'``, ``'true'``, ``'on'`` and the
Georg Brandlbb27c122010-11-11 07:26:40 +0000693 following values ``False``: ``'0'``, ``'no'``, ``'false'``, ``'off'``. You
694 can override this by specifying a custom dictionary of strings and their
Fred Drake5a7c11f2010-11-13 05:24:17 +0000695 Boolean outcomes. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000696
Łukasz Langa26d513c2010-11-10 18:57:39 +0000697 .. doctest::
698
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000699 >>> custom = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000700 >>> custom['section1'] = {'funky': 'nope'}
701 >>> custom['section1'].getboolean('funky')
702 Traceback (most recent call last):
703 ...
704 ValueError: Not a boolean: nope
705 >>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}
706 >>> custom['section1'].getboolean('funky')
707 False
Łukasz Langa26d513c2010-11-10 18:57:39 +0000708
Fred Drake5a7c11f2010-11-13 05:24:17 +0000709 Other typical Boolean pairs include ``accept``/``reject`` or
Łukasz Langa26d513c2010-11-10 18:57:39 +0000710 ``enabled``/``disabled``.
711
Fred Drake5a7c11f2010-11-13 05:24:17 +0000712.. method:: optionxform(option)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000713
Fred Drake5a7c11f2010-11-13 05:24:17 +0000714 This method transforms option names on every read, get, or set
715 operation. The default converts the name to lowercase. This also
716 means that when a configuration file gets written, all keys will be
717 lowercase. Override this method if that's unsuitable.
718 For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000719
Łukasz Langa26d513c2010-11-10 18:57:39 +0000720 .. doctest::
721
Georg Brandlbb27c122010-11-11 07:26:40 +0000722 >>> config = """
723 ... [Section1]
724 ... Key = Value
725 ...
726 ... [Section2]
727 ... AnotherKey = Value
728 ... """
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000729 >>> typical = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000730 >>> typical.read_string(config)
731 >>> list(typical['Section1'].keys())
732 ['key']
733 >>> list(typical['Section2'].keys())
734 ['anotherkey']
735 >>> custom = configparser.RawConfigParser()
736 >>> custom.optionxform = lambda option: option
737 >>> custom.read_string(config)
738 >>> list(custom['Section1'].keys())
739 ['Key']
740 >>> list(custom['Section2'].keys())
741 ['AnotherKey']
742
Łukasz Langa66c908e2011-01-28 11:57:30 +0000743.. attribute:: SECTCRE
744
Łukasz Langa34cea142014-09-14 23:37:03 -0700745 A compiled regular expression used to parse section headers. The default
746 matches ``[section]`` to the name ``"section"``. Whitespace is considered
747 part of the section name, thus ``[ larch ]`` will be read as a section of
748 name ``" larch "``. Override this attribute if that's unsuitable. For
749 example:
Łukasz Langa66c908e2011-01-28 11:57:30 +0000750
751 .. doctest::
752
753 >>> config = """
754 ... [Section 1]
755 ... option = value
756 ...
757 ... [ Section 2 ]
758 ... another = val
759 ... """
760 >>> typical = ConfigParser()
761 >>> typical.read_string(config)
762 >>> typical.sections()
763 ['Section 1', ' Section 2 ']
764 >>> custom = ConfigParser()
765 >>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]")
766 >>> custom.read_string(config)
767 >>> custom.sections()
768 ['Section 1', 'Section 2']
769
770 .. note::
771
772 While ConfigParser objects also use an ``OPTCRE`` attribute for recognizing
773 option lines, it's not recommended to override it because that would
774 interfere with constructor options *allow_no_value* and *delimiters*.
775
Łukasz Langa26d513c2010-11-10 18:57:39 +0000776
777Legacy API Examples
778-------------------
779
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000780Mainly because of backwards compatibility concerns, :mod:`configparser`
781provides also a legacy API with explicit ``get``/``set`` methods. While there
782are valid use cases for the methods outlined below, mapping protocol access is
783preferred for new projects. The legacy API is at times more advanced,
784low-level and downright counterintuitive.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000785
786An example of writing to a configuration file::
787
788 import configparser
789
790 config = configparser.RawConfigParser()
791
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000792 # Please note that using RawConfigParser's set functions, you can assign
793 # non-string values to keys internally, but will receive an error when
794 # attempting to write to a file or when you get it in non-raw mode. Setting
795 # values using the mapping protocol or ConfigParser's set() does not allow
796 # such assignments to take place.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000797 config.add_section('Section1')
R David Murray1a1883d2012-09-29 14:40:23 -0400798 config.set('Section1', 'an_int', '15')
799 config.set('Section1', 'a_bool', 'true')
800 config.set('Section1', 'a_float', '3.1415')
Łukasz Langa26d513c2010-11-10 18:57:39 +0000801 config.set('Section1', 'baz', 'fun')
802 config.set('Section1', 'bar', 'Python')
803 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
804
805 # Writing our configuration file to 'example.cfg'
806 with open('example.cfg', 'w') as configfile:
807 config.write(configfile)
808
809An example of reading the configuration file again::
810
811 import configparser
812
813 config = configparser.RawConfigParser()
814 config.read('example.cfg')
815
816 # getfloat() raises an exception if the value is not a float
817 # getint() and getboolean() also do this for their respective types
R David Murray1a1883d2012-09-29 14:40:23 -0400818 a_float = config.getfloat('Section1', 'a_float')
819 an_int = config.getint('Section1', 'an_int')
820 print(a_float + an_int)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000821
822 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
823 # This is because we are using a RawConfigParser().
R David Murray1a1883d2012-09-29 14:40:23 -0400824 if config.getboolean('Section1', 'a_bool'):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000825 print(config.get('Section1', 'foo'))
826
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000827To get interpolation, use :class:`ConfigParser`::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000828
829 import configparser
830
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000831 cfg = configparser.ConfigParser()
Łukasz Langa26d513c2010-11-10 18:57:39 +0000832 cfg.read('example.cfg')
833
Éric Araujo941afed2011-09-01 02:47:34 +0200834 # Set the optional *raw* argument of get() to True if you wish to disable
Łukasz Langa26d513c2010-11-10 18:57:39 +0000835 # interpolation in a single get operation.
836 print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!"
837 print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!"
838
Éric Araujo941afed2011-09-01 02:47:34 +0200839 # The optional *vars* argument is a dict with members that will take
Łukasz Langa26d513c2010-11-10 18:57:39 +0000840 # precedence in interpolation.
841 print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation',
842 'baz': 'evil'}))
843
Éric Araujo941afed2011-09-01 02:47:34 +0200844 # The optional *fallback* argument can be used to provide a fallback value
Łukasz Langa26d513c2010-11-10 18:57:39 +0000845 print(cfg.get('Section1', 'foo'))
846 # -> "Python is fun!"
847
848 print(cfg.get('Section1', 'foo', fallback='Monty is not.'))
849 # -> "Python is fun!"
850
851 print(cfg.get('Section1', 'monster', fallback='No such things as monsters.'))
852 # -> "No such things as monsters."
853
854 # A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError
855 # but we can also use:
856
857 print(cfg.get('Section1', 'monster', fallback=None))
858 # -> None
859
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000860Default values are available in both types of ConfigParsers. They are used in
861interpolation if an option used is not defined elsewhere. ::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000862
863 import configparser
864
865 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000866 config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'})
Łukasz Langa26d513c2010-11-10 18:57:39 +0000867 config.read('example.cfg')
868
869 print(config.get('Section1', 'foo')) # -> "Python is fun!"
870 config.remove_option('Section1', 'bar')
871 config.remove_option('Section1', 'baz')
872 print(config.get('Section1', 'foo')) # -> "Life is hard!"
873
Georg Brandlbb27c122010-11-11 07:26:40 +0000874
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000875.. _configparser-objects:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000876
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000877ConfigParser Objects
878--------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000879
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700880.. 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(), converters={})
Georg Brandl116aa622007-08-15 14:28:22 +0000881
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000882 The main configuration parser. When *defaults* is given, it is initialized
Georg Brandl96a60ae2010-07-28 13:13:46 +0000883 into the dictionary of intrinsic defaults. When *dict_type* is given, it
884 will be used to create the dictionary objects for the list of sections, for
885 the options within a section, and for the default values.
886
Fred Drake5a7c11f2010-11-13 05:24:17 +0000887 When *delimiters* is given, it is used as the set of substrings that
Georg Brandl96a60ae2010-07-28 13:13:46 +0000888 divide keys from values. When *comment_prefixes* is given, it will be used
Łukasz Langab25a7912010-12-17 01:32:29 +0000889 as the set of substrings that prefix comments in otherwise empty lines.
Łukasz Langa34cea142014-09-14 23:37:03 -0700890 Comments can be indented. When *inline_comment_prefixes* is given, it will
891 be used as the set of substrings that prefix comments in non-empty lines.
Łukasz Langab25a7912010-12-17 01:32:29 +0000892
Łukasz Langab25a7912010-12-17 01:32:29 +0000893 When *strict* is ``True`` (the default), the parser won't allow for
Fred Drakea4923622010-08-09 12:52:45 +0000894 any section or option duplicates while reading from a single source (file,
895 string or dictionary), raising :exc:`DuplicateSectionError` or
Fred Drake5a7c11f2010-11-13 05:24:17 +0000896 :exc:`DuplicateOptionError`. When *empty_lines_in_values* is ``False``
Fred Drakea4923622010-08-09 12:52:45 +0000897 (default: ``True``), each empty line marks the end of an option. Otherwise,
898 internal empty lines of a multiline option are kept as part of the value.
899 When *allow_no_value* is ``True`` (default: ``False``), options without
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000900 values are accepted; the value held for these is ``None`` and they are
901 serialized without the trailing delimiter.
Fred Drake03c44a32010-02-19 06:08:41 +0000902
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000903 When *default_section* is given, it specifies the name for the special
904 section holding default values for other sections and interpolation purposes
Łukasz Langa34cea142014-09-14 23:37:03 -0700905 (normally named ``"DEFAULT"``). This value can be retrieved and changed on
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000906 runtime using the ``default_section`` instance attribute.
907
908 Interpolation behaviour may be customized by providing a custom handler
909 through the *interpolation* argument. ``None`` can be used to turn off
910 interpolation completely, ``ExtendedInterpolation()`` provides a more
Łukasz Langa34cea142014-09-14 23:37:03 -0700911 advanced variant inspired by ``zc.buildout``. More on the subject in the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000912 `dedicated documentation section <#interpolation-of-values>`_.
913
914 All option names used in interpolation will be passed through the
915 :meth:`optionxform` method just like any other option name reference. For
916 example, using the default implementation of :meth:`optionxform` (which
917 converts option names to lower case), the values ``foo %(bar)s`` and ``foo
918 %(BAR)s`` are equivalent.
Georg Brandl116aa622007-08-15 14:28:22 +0000919
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700920 When *converters* is given, it should be a dictionary where each key
921 represents the name of a type converter and each value is a callable
922 implementing the conversion from string to the desired datatype. Every
923 converter gets its own corresponding :meth:`get*()` method on the parser
924 object and section proxies.
925
Raymond Hettinger231b7f12009-03-03 00:23:19 +0000926 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +0000927 The default *dict_type* is :class:`collections.OrderedDict`.
928
Fred Drake03c44a32010-02-19 06:08:41 +0000929 .. versionchanged:: 3.2
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000930 *allow_no_value*, *delimiters*, *comment_prefixes*, *strict*,
931 *empty_lines_in_values*, *default_section* and *interpolation* were
932 added.
Georg Brandl116aa622007-08-15 14:28:22 +0000933
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700934 .. versionchanged:: 3.5
935 The *converters* argument was added.
936
Fred Drake03c44a32010-02-19 06:08:41 +0000937
Georg Brandlbb27c122010-11-11 07:26:40 +0000938 .. method:: defaults()
Georg Brandl116aa622007-08-15 14:28:22 +0000939
Georg Brandlbb27c122010-11-11 07:26:40 +0000940 Return a dictionary containing the instance-wide defaults.
Georg Brandl116aa622007-08-15 14:28:22 +0000941
942
Georg Brandlbb27c122010-11-11 07:26:40 +0000943 .. method:: sections()
Georg Brandl116aa622007-08-15 14:28:22 +0000944
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000945 Return a list of the sections available; the *default section* is not
946 included in the list.
Georg Brandl116aa622007-08-15 14:28:22 +0000947
948
Georg Brandlbb27c122010-11-11 07:26:40 +0000949 .. method:: add_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000950
Georg Brandlbb27c122010-11-11 07:26:40 +0000951 Add a section named *section* to the instance. If a section by the given
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000952 name already exists, :exc:`DuplicateSectionError` is raised. If the
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000953 *default section* name is passed, :exc:`ValueError` is raised. The name
954 of the section must be a string; if not, :exc:`TypeError` is raised.
955
956 .. versionchanged:: 3.2
957 Non-string section names raise :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000958
Georg Brandl116aa622007-08-15 14:28:22 +0000959
Georg Brandlbb27c122010-11-11 07:26:40 +0000960 .. method:: has_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000961
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000962 Indicates whether the named *section* is present in the configuration.
963 The *default section* is not acknowledged.
Georg Brandl116aa622007-08-15 14:28:22 +0000964
Georg Brandl116aa622007-08-15 14:28:22 +0000965
Georg Brandlbb27c122010-11-11 07:26:40 +0000966 .. method:: options(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000967
Georg Brandlbb27c122010-11-11 07:26:40 +0000968 Return a list of options available in the specified *section*.
Georg Brandl116aa622007-08-15 14:28:22 +0000969
Georg Brandl116aa622007-08-15 14:28:22 +0000970
Georg Brandlbb27c122010-11-11 07:26:40 +0000971 .. method:: has_option(section, option)
Georg Brandl116aa622007-08-15 14:28:22 +0000972
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000973 If the given *section* exists, and contains the given *option*, return
Łukasz Langa34cea142014-09-14 23:37:03 -0700974 :const:`True`; otherwise return :const:`False`. If the specified
Łukasz Langa71b37a52010-12-17 21:56:32 +0000975 *section* is :const:`None` or an empty string, DEFAULT is assumed.
Georg Brandl116aa622007-08-15 14:28:22 +0000976
Georg Brandl116aa622007-08-15 14:28:22 +0000977
Georg Brandlbb27c122010-11-11 07:26:40 +0000978 .. method:: read(filenames, encoding=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000979
Georg Brandlbb27c122010-11-11 07:26:40 +0000980 Attempt to read and parse a list of filenames, returning a list of
981 filenames which were successfully parsed. If *filenames* is a string, it
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000982 is treated as a single filename. If a file named in *filenames* cannot
983 be opened, that file will be ignored. This is designed so that you can
984 specify a list of potential configuration file locations (for example,
985 the current directory, the user's home directory, and some system-wide
986 directory), and all existing configuration files in the list will be
987 read. If none of the named files exist, the :class:`ConfigParser`
988 instance will contain an empty dataset. An application which requires
989 initial values to be loaded from a file should load the required file or
990 files using :meth:`read_file` before calling :meth:`read` for any
991 optional files::
Georg Brandl116aa622007-08-15 14:28:22 +0000992
Georg Brandlbb27c122010-11-11 07:26:40 +0000993 import configparser, os
Georg Brandl8dcaa732010-07-29 12:17:40 +0000994
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000995 config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000996 config.read_file(open('defaults.cfg'))
997 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
998 encoding='cp1250')
Georg Brandl116aa622007-08-15 14:28:22 +0000999
Georg Brandlbb27c122010-11-11 07:26:40 +00001000 .. versionadded:: 3.2
1001 The *encoding* parameter. Previously, all files were read using the
1002 default encoding for :func:`open`.
Georg Brandl116aa622007-08-15 14:28:22 +00001003
Georg Brandl116aa622007-08-15 14:28:22 +00001004
Georg Brandlbb27c122010-11-11 07:26:40 +00001005 .. method:: read_file(f, source=None)
Georg Brandl73753d32009-09-22 13:53:14 +00001006
Łukasz Langadaab1c82011-04-27 18:10:05 +02001007 Read and parse configuration data from *f* which must be an iterable
Łukasz Langaba702da2011-04-28 12:02:05 +02001008 yielding Unicode strings (for example files opened in text mode).
Georg Brandl116aa622007-08-15 14:28:22 +00001009
Georg Brandlbb27c122010-11-11 07:26:40 +00001010 Optional argument *source* specifies the name of the file being read. If
Fred Drake5a7c11f2010-11-13 05:24:17 +00001011 not given and *f* has a :attr:`name` attribute, that is used for
1012 *source*; the default is ``'<???>'``.
Fred Drakea4923622010-08-09 12:52:45 +00001013
Georg Brandlbb27c122010-11-11 07:26:40 +00001014 .. versionadded:: 3.2
Łukasz Langa43ae6192011-04-27 18:13:42 +02001015 Replaces :meth:`readfp`.
1016
Georg Brandlbb27c122010-11-11 07:26:40 +00001017 .. method:: read_string(string, source='<string>')
Fred Drakea4923622010-08-09 12:52:45 +00001018
Fred Drake5a7c11f2010-11-13 05:24:17 +00001019 Parse configuration data from a string.
Fred Drakea4923622010-08-09 12:52:45 +00001020
Fred Drake5a7c11f2010-11-13 05:24:17 +00001021 Optional argument *source* specifies a context-specific name of the
1022 string passed. If not given, ``'<string>'`` is used. This should
1023 commonly be a filesystem path or a URL.
Fred Drakea4923622010-08-09 12:52:45 +00001024
Georg Brandlbb27c122010-11-11 07:26:40 +00001025 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +00001026
Fred Drakea4923622010-08-09 12:52:45 +00001027
Georg Brandlbb27c122010-11-11 07:26:40 +00001028 .. method:: read_dict(dictionary, source='<dict>')
Fred Drakea4923622010-08-09 12:52:45 +00001029
Łukasz Langa71b37a52010-12-17 21:56:32 +00001030 Load configuration from any object that provides a dict-like ``items()``
1031 method. Keys are section names, values are dictionaries with keys and
1032 values that should be present in the section. If the used dictionary
1033 type preserves order, sections and their keys will be added in order.
1034 Values are automatically converted to strings.
Fred Drakea4923622010-08-09 12:52:45 +00001035
Georg Brandlbb27c122010-11-11 07:26:40 +00001036 Optional argument *source* specifies a context-specific name of the
1037 dictionary passed. If not given, ``<dict>`` is used.
Georg Brandl116aa622007-08-15 14:28:22 +00001038
Łukasz Langa71b37a52010-12-17 21:56:32 +00001039 This method can be used to copy state between parsers.
1040
Georg Brandlbb27c122010-11-11 07:26:40 +00001041 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +00001042
Georg Brandl116aa622007-08-15 14:28:22 +00001043
Ezio Melottie927e252012-09-08 20:46:01 +03001044 .. method:: get(section, option, *, raw=False, vars=None[, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +00001045
Georg Brandlbb27c122010-11-11 07:26:40 +00001046 Get an *option* value for the named *section*. If *vars* is provided, it
1047 must be a dictionary. The *option* is looked up in *vars* (if provided),
1048 *section*, and in *DEFAULTSECT* in that order. If the key is not found
1049 and *fallback* is provided, it is used as a fallback value. ``None`` can
1050 be provided as a *fallback* value.
Georg Brandl470a1232010-07-29 14:17:12 +00001051
Georg Brandlbb27c122010-11-11 07:26:40 +00001052 All the ``'%'`` interpolations are expanded in the return values, unless
1053 the *raw* argument is true. Values for interpolation keys are looked up
1054 in the same manner as the option.
Georg Brandl116aa622007-08-15 14:28:22 +00001055
Georg Brandlbb27c122010-11-11 07:26:40 +00001056 .. versionchanged:: 3.2
1057 Arguments *raw*, *vars* and *fallback* are keyword only to protect
1058 users from trying to use the third argument as the *fallback* fallback
1059 (especially when using the mapping protocol).
Georg Brandl116aa622007-08-15 14:28:22 +00001060
Łukasz Langa26d513c2010-11-10 18:57:39 +00001061
Ezio Melottie927e252012-09-08 20:46:01 +03001062 .. method:: getint(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001063
Georg Brandlbb27c122010-11-11 07:26:40 +00001064 A convenience method which coerces the *option* in the specified *section*
1065 to an integer. See :meth:`get` for explanation of *raw*, *vars* and
1066 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001067
1068
Ezio Melottie927e252012-09-08 20:46:01 +03001069 .. method:: getfloat(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001070
Georg Brandlbb27c122010-11-11 07:26:40 +00001071 A convenience method which coerces the *option* in the specified *section*
1072 to a floating point number. See :meth:`get` for explanation of *raw*,
1073 *vars* and *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001074
1075
Ezio Melottie927e252012-09-08 20:46:01 +03001076 .. method:: getboolean(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001077
Georg Brandlbb27c122010-11-11 07:26:40 +00001078 A convenience method which coerces the *option* in the specified *section*
1079 to a Boolean value. Note that the accepted values for the option are
Fred Drake5a7c11f2010-11-13 05:24:17 +00001080 ``'1'``, ``'yes'``, ``'true'``, and ``'on'``, which cause this method to
1081 return ``True``, and ``'0'``, ``'no'``, ``'false'``, and ``'off'``, which
Georg Brandlbb27c122010-11-11 07:26:40 +00001082 cause it to return ``False``. These string values are checked in a
1083 case-insensitive manner. Any other value will cause it to raise
1084 :exc:`ValueError`. See :meth:`get` for explanation of *raw*, *vars* and
1085 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001086
1087
Ezio Melottie0add762012-09-14 06:32:35 +03001088 .. method:: items(raw=False, vars=None)
1089 items(section, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001090
Łukasz Langa71b37a52010-12-17 21:56:32 +00001091 When *section* is not given, return a list of *section_name*,
1092 *section_proxy* pairs, including DEFAULTSECT.
1093
1094 Otherwise, return a list of *name*, *value* pairs for the options in the
1095 given *section*. Optional arguments have the same meaning as for the
Georg Brandlbb27c122010-11-11 07:26:40 +00001096 :meth:`get` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001097
Łukasz Langa72547622011-05-09 18:49:42 +02001098 .. versionchanged:: 3.2
Łukasz Langa34cea142014-09-14 23:37:03 -07001099 Items present in *vars* no longer appear in the result. The previous
Łukasz Langa72547622011-05-09 18:49:42 +02001100 behaviour mixed actual parser options with variables provided for
1101 interpolation.
Georg Brandl116aa622007-08-15 14:28:22 +00001102
Georg Brandlbb27c122010-11-11 07:26:40 +00001103 .. method:: set(section, option, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001104
Georg Brandlbb27c122010-11-11 07:26:40 +00001105 If the given section exists, set the given option to the specified value;
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001106 otherwise raise :exc:`NoSectionError`. *option* and *value* must be
1107 strings; if not, :exc:`TypeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001108
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001109
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001110 .. method:: write(fileobject, space_around_delimiters=True)
1111
1112 Write a representation of the configuration to the specified :term:`file
1113 object`, which must be opened in text mode (accepting strings). This
1114 representation can be parsed by a future :meth:`read` call. If
1115 *space_around_delimiters* is true, delimiters between
1116 keys and values are surrounded by spaces.
1117
1118
1119 .. method:: remove_option(section, option)
1120
1121 Remove the specified *option* from the specified *section*. If the
1122 section does not exist, raise :exc:`NoSectionError`. If the option
1123 existed to be removed, return :const:`True`; otherwise return
1124 :const:`False`.
1125
1126
1127 .. method:: remove_section(section)
1128
1129 Remove the specified *section* from the configuration. If the section in
1130 fact existed, return ``True``. Otherwise return ``False``.
1131
1132
1133 .. method:: optionxform(option)
1134
1135 Transforms the option name *option* as found in an input file or as passed
1136 in by client code to the form that should be used in the internal
1137 structures. The default implementation returns a lower-case version of
1138 *option*; subclasses may override this or client code can set an attribute
1139 of this name on instances to affect this behavior.
1140
1141 You don't need to subclass the parser to use this method, you can also
1142 set it on an instance, to a function that takes a string argument and
1143 returns a string. Setting it to ``str``, for example, would make option
1144 names case sensitive::
1145
1146 cfgparser = ConfigParser()
1147 cfgparser.optionxform = str
1148
1149 Note that when reading configuration files, whitespace around the option
1150 names is stripped before :meth:`optionxform` is called.
1151
1152
1153 .. method:: readfp(fp, filename=None)
1154
1155 .. deprecated:: 3.2
1156 Use :meth:`read_file` instead.
1157
Łukasz Langaba702da2011-04-28 12:02:05 +02001158 .. versionchanged:: 3.2
1159 :meth:`readfp` now iterates on *f* instead of calling ``f.readline()``.
1160
1161 For existing code calling :meth:`readfp` with arguments which don't
1162 support iteration, the following generator may be used as a wrapper
1163 around the file-like object::
1164
1165 def readline_generator(f):
1166 line = f.readline()
1167 while line:
1168 yield line
1169 line = f.readline()
1170
1171 Instead of ``parser.readfp(f)`` use
1172 ``parser.read_file(readline_generator(f))``.
1173
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001174
1175.. data:: MAX_INTERPOLATION_DEPTH
1176
1177 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
1178 parameter is false. This is relevant only when the default *interpolation*
1179 is used.
1180
1181
1182.. _rawconfigparser-objects:
1183
1184RawConfigParser Objects
1185-----------------------
1186
Ezio Melottie927e252012-09-08 20:46:01 +03001187.. class:: RawConfigParser(defaults=None, dict_type=collections.OrderedDict, \
1188 allow_no_value=False, *, delimiters=('=', ':'), \
1189 comment_prefixes=('#', ';'), \
1190 inline_comment_prefixes=None, strict=True, \
1191 empty_lines_in_values=True, \
1192 default_section=configparser.DEFAULTSECT[, \
1193 interpolation])
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001194
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001195 Legacy variant of the :class:`ConfigParser` with interpolation disabled
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001196 by default and unsafe ``add_section`` and ``set`` methods.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001197
1198 .. note::
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001199 Consider using :class:`ConfigParser` instead which checks types of
Łukasz Langa34cea142014-09-14 23:37:03 -07001200 the values to be stored internally. If you don't want interpolation, you
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001201 can use ``ConfigParser(interpolation=None)``.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001202
1203
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001204 .. method:: add_section(section)
1205
1206 Add a section named *section* to the instance. If a section by the given
1207 name already exists, :exc:`DuplicateSectionError` is raised. If the
1208 *default section* name is passed, :exc:`ValueError` is raised.
1209
1210 Type of *section* is not checked which lets users create non-string named
Łukasz Langa34cea142014-09-14 23:37:03 -07001211 sections. This behaviour is unsupported and may cause internal errors.
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001212
1213
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001214 .. method:: set(section, option, value)
1215
1216 If the given section exists, set the given option to the specified value;
1217 otherwise raise :exc:`NoSectionError`. While it is possible to use
1218 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters
1219 set to true) for *internal* storage of non-string values, full
1220 functionality (including interpolation and output to files) can only be
1221 achieved using string values.
1222
1223 This method lets users assign non-string values to keys internally. This
1224 behaviour is unsupported and will cause errors when attempting to write
1225 to a file or get it in non-raw mode. **Use the mapping protocol API**
1226 which does not allow such assignments to take place.
1227
1228
Łukasz Langa26d513c2010-11-10 18:57:39 +00001229Exceptions
1230----------
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001231
Łukasz Langa26d513c2010-11-10 18:57:39 +00001232.. exception:: Error
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001233
Fred Drake5a7c11f2010-11-13 05:24:17 +00001234 Base class for all other :mod:`configparser` exceptions.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001235
Georg Brandl48310cd2009-01-03 21:18:54 +00001236
Łukasz Langa26d513c2010-11-10 18:57:39 +00001237.. exception:: NoSectionError
Georg Brandl48310cd2009-01-03 21:18:54 +00001238
Łukasz Langa26d513c2010-11-10 18:57:39 +00001239 Exception raised when a specified section is not found.
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:: DuplicateSectionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001243
Łukasz Langa26d513c2010-11-10 18:57:39 +00001244 Exception raised if :meth:`add_section` is called with the name of a section
1245 that is already present or in strict parsers when a section if found more
1246 than once in a single input file, string or dictionary.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001247
Łukasz Langa26d513c2010-11-10 18:57:39 +00001248 .. versionadded:: 3.2
1249 Optional ``source`` and ``lineno`` attributes and arguments to
1250 :meth:`__init__` were added.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001251
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001252
Łukasz Langa26d513c2010-11-10 18:57:39 +00001253.. exception:: DuplicateOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001254
Łukasz Langa26d513c2010-11-10 18:57:39 +00001255 Exception raised by strict parsers if a single option appears twice during
1256 reading from a single file, string or dictionary. This catches misspellings
1257 and case sensitivity-related errors, e.g. a dictionary may have two keys
1258 representing the same case-insensitive configuration key.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001259
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001260
Łukasz Langa26d513c2010-11-10 18:57:39 +00001261.. exception:: NoOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001262
Łukasz Langa26d513c2010-11-10 18:57:39 +00001263 Exception raised when a specified option is not found in the specified
1264 section.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001265
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001266
Łukasz Langa26d513c2010-11-10 18:57:39 +00001267.. exception:: InterpolationError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001268
Łukasz Langa26d513c2010-11-10 18:57:39 +00001269 Base class for exceptions raised when problems occur performing string
1270 interpolation.
Georg Brandl48310cd2009-01-03 21:18:54 +00001271
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001272
Łukasz Langa26d513c2010-11-10 18:57:39 +00001273.. exception:: InterpolationDepthError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001274
Łukasz Langa26d513c2010-11-10 18:57:39 +00001275 Exception raised when string interpolation cannot be completed because the
Georg Brandlbb27c122010-11-11 07:26:40 +00001276 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
Łukasz Langa26d513c2010-11-10 18:57:39 +00001277 :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001278
Fred Drake03c44a32010-02-19 06:08:41 +00001279
Łukasz Langa26d513c2010-11-10 18:57:39 +00001280.. exception:: InterpolationMissingOptionError
Fred Drake03c44a32010-02-19 06:08:41 +00001281
Georg Brandlbb27c122010-11-11 07:26:40 +00001282 Exception raised when an option referenced from a value does not exist.
1283 Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001284
Fred Drake03c44a32010-02-19 06:08:41 +00001285
Łukasz Langa26d513c2010-11-10 18:57:39 +00001286.. exception:: InterpolationSyntaxError
Fred Drake03c44a32010-02-19 06:08:41 +00001287
Georg Brandlbb27c122010-11-11 07:26:40 +00001288 Exception raised when the source text into which substitutions are made does
1289 not conform to the required syntax. Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001290
Łukasz Langa26d513c2010-11-10 18:57:39 +00001291
1292.. exception:: MissingSectionHeaderError
1293
Georg Brandlbb27c122010-11-11 07:26:40 +00001294 Exception raised when attempting to parse a file which has no section
1295 headers.
Łukasz Langa26d513c2010-11-10 18:57:39 +00001296
1297
1298.. exception:: ParsingError
1299
1300 Exception raised when errors occur attempting to parse a file.
1301
1302 .. versionchanged:: 3.2
1303 The ``filename`` attribute and :meth:`__init__` argument were renamed to
1304 ``source`` for consistency.
1305
Georg Brandlbb27c122010-11-11 07:26:40 +00001306
1307.. rubric:: Footnotes
1308
1309.. [1] Config parsers allow for heavy customization. If you are interested in
1310 changing the behaviour outlined by the footnote reference, consult the
1311 `Customizing Parser Behaviour`_ section.
Łukasz Langadfdd2f72014-09-15 02:08:41 -07001312