blob: eeae96aab99efc6d4ab65fed1f44ca7bb7d74c08 [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
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040022--------------
23
Łukasz Langa7f64c8a2010-12-16 01:16:22 +000024This module provides the :class:`ConfigParser` class which implements a basic
25configuration language which provides a structure similar to what's found in
26Microsoft Windows INI files. You can use this to write Python programs which
27can be customized by end users easily.
Georg Brandl116aa622007-08-15 14:28:22 +000028
Georg Brandle720c0a2009-04-27 16:20:50 +000029.. note::
Georg Brandl116aa622007-08-15 14:28:22 +000030
Georg Brandle720c0a2009-04-27 16:20:50 +000031 This library does *not* interpret or write the value-type prefixes used in
32 the Windows Registry extended version of INI syntax.
Georg Brandl116aa622007-08-15 14:28:22 +000033
Łukasz Langa26d513c2010-11-10 18:57:39 +000034.. seealso::
35
36 Module :mod:`shlex`
37 Support for a creating Unix shell-like mini-languages which can be used
38 as an alternate format for application configuration files.
39
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000040 Module :mod:`json`
41 The json module implements a subset of JavaScript syntax which can also
42 be used for this purpose.
43
Georg Brandlbb27c122010-11-11 07:26:40 +000044
Łukasz Langa26d513c2010-11-10 18:57:39 +000045Quick Start
46-----------
47
Georg Brandlbb27c122010-11-11 07:26:40 +000048Let's take a very basic configuration file that looks like this:
Łukasz Langa26d513c2010-11-10 18:57:39 +000049
Georg Brandlbb27c122010-11-11 07:26:40 +000050.. code-block:: ini
Łukasz Langa26d513c2010-11-10 18:57:39 +000051
Georg Brandlbb27c122010-11-11 07:26:40 +000052 [DEFAULT]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000053 ServerAliveInterval = 45
54 Compression = yes
55 CompressionLevel = 9
56 ForwardX11 = yes
Łukasz Langa26d513c2010-11-10 18:57:39 +000057
Georg Brandlbb27c122010-11-11 07:26:40 +000058 [bitbucket.org]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000059 User = hg
Łukasz Langa26d513c2010-11-10 18:57:39 +000060
Georg Brandlbb27c122010-11-11 07:26:40 +000061 [topsecret.server.com]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000062 Port = 50022
63 ForwardX11 = no
Łukasz Langa26d513c2010-11-10 18:57:39 +000064
Fred Drake5a7c11f2010-11-13 05:24:17 +000065The structure of INI files is described `in the following section
66<#supported-ini-file-structure>`_. Essentially, the file
Łukasz Langa26d513c2010-11-10 18:57:39 +000067consists of sections, each of which contains keys with values.
Georg Brandlbb27c122010-11-11 07:26:40 +000068:mod:`configparser` classes can read and write such files. Let's start by
Łukasz Langa26d513c2010-11-10 18:57:39 +000069creating the above configuration file programatically.
70
Łukasz Langa26d513c2010-11-10 18:57:39 +000071.. doctest::
72
Georg Brandlbb27c122010-11-11 07:26:40 +000073 >>> import configparser
Łukasz Langa7f64c8a2010-12-16 01:16:22 +000074 >>> config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +000075 >>> config['DEFAULT'] = {'ServerAliveInterval': '45',
76 ... 'Compression': 'yes',
77 ... 'CompressionLevel': '9'}
78 >>> config['bitbucket.org'] = {}
79 >>> config['bitbucket.org']['User'] = 'hg'
80 >>> config['topsecret.server.com'] = {}
81 >>> topsecret = config['topsecret.server.com']
82 >>> topsecret['Port'] = '50022' # mutates the parser
83 >>> topsecret['ForwardX11'] = 'no' # same here
84 >>> config['DEFAULT']['ForwardX11'] = 'yes'
85 >>> with open('example.ini', 'w') as configfile:
86 ... config.write(configfile)
87 ...
Łukasz Langa26d513c2010-11-10 18:57:39 +000088
Fred Drake5a7c11f2010-11-13 05:24:17 +000089As you can see, we can treat a config parser much like a dictionary.
90There are differences, `outlined later <#mapping-protocol-access>`_, but
91the behavior is very close to what you would expect from a dictionary.
Łukasz Langa26d513c2010-11-10 18:57:39 +000092
Fred Drake5a7c11f2010-11-13 05:24:17 +000093Now that we have created and saved a configuration file, let's read it
94back and explore the data it holds.
Łukasz Langa26d513c2010-11-10 18:57:39 +000095
Łukasz Langa26d513c2010-11-10 18:57:39 +000096.. doctest::
97
Georg Brandlbb27c122010-11-11 07:26:40 +000098 >>> import configparser
Łukasz Langa7f64c8a2010-12-16 01:16:22 +000099 >>> config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000100 >>> config.sections()
101 []
102 >>> config.read('example.ini')
103 ['example.ini']
104 >>> config.sections()
105 ['bitbucket.org', 'topsecret.server.com']
106 >>> 'bitbucket.org' in config
107 True
108 >>> 'bytebong.com' in config
109 False
110 >>> config['bitbucket.org']['User']
111 'hg'
112 >>> config['DEFAULT']['Compression']
113 'yes'
114 >>> topsecret = config['topsecret.server.com']
115 >>> topsecret['ForwardX11']
116 'no'
117 >>> topsecret['Port']
118 '50022'
119 >>> for key in config['bitbucket.org']: print(key)
120 ...
121 user
122 compressionlevel
123 serveraliveinterval
124 compression
125 forwardx11
126 >>> config['bitbucket.org']['ForwardX11']
127 'yes'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000128
Fred Drake5a7c11f2010-11-13 05:24:17 +0000129As we can see above, the API is pretty straightforward. The only bit of magic
Łukasz Langa26d513c2010-11-10 18:57:39 +0000130involves the ``DEFAULT`` section which provides default values for all other
Fred Drake5a7c11f2010-11-13 05:24:17 +0000131sections [1]_. Note also that keys in sections are
132case-insensitive and stored in lowercase [1]_.
Georg Brandlbb27c122010-11-11 07:26:40 +0000133
Łukasz Langa26d513c2010-11-10 18:57:39 +0000134
135Supported Datatypes
136-------------------
137
138Config parsers do not guess datatypes of values in configuration files, always
Georg Brandlbb27c122010-11-11 07:26:40 +0000139storing them internally as strings. This means that if you need other
140datatypes, you should convert on your own:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000141
Łukasz Langa26d513c2010-11-10 18:57:39 +0000142.. doctest::
143
Georg Brandlbb27c122010-11-11 07:26:40 +0000144 >>> int(topsecret['Port'])
145 50022
146 >>> float(topsecret['CompressionLevel'])
147 9.0
Łukasz Langa26d513c2010-11-10 18:57:39 +0000148
Łukasz Langa34cea142014-09-14 23:37:03 -0700149Since this task is so common, config parsers provide a range of handy getter
150methods to handle integers, floats and booleans. The last one is the most
151interesting because simply passing the value to ``bool()`` would do no good
152since ``bool('False')`` is still ``True``. This is why config parsers also
153provide :meth:`getboolean`. This method is case-insensitive and recognizes
154Boolean values from ``'yes'``/``'no'``, ``'on'``/``'off'``,
155``'true'``/``'false'`` and ``'1'``/``'0'`` [1]_. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000156
Łukasz Langa26d513c2010-11-10 18:57:39 +0000157.. doctest::
158
Georg Brandlbb27c122010-11-11 07:26:40 +0000159 >>> topsecret.getboolean('ForwardX11')
160 False
161 >>> config['bitbucket.org'].getboolean('ForwardX11')
162 True
163 >>> config.getboolean('bitbucket.org', 'Compression')
164 True
Łukasz Langa26d513c2010-11-10 18:57:39 +0000165
166Apart from :meth:`getboolean`, config parsers also provide equivalent
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700167:meth:`getint` and :meth:`getfloat` methods. You can register your own
168converters and customize the provided ones. [1]_
Georg Brandlbb27c122010-11-11 07:26:40 +0000169
Łukasz Langa26d513c2010-11-10 18:57:39 +0000170Fallback Values
171---------------
172
Fred Drake5a7c11f2010-11-13 05:24:17 +0000173As with a dictionary, you can use a section's :meth:`get` method to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000174provide fallback values:
175
Łukasz Langa26d513c2010-11-10 18:57:39 +0000176.. doctest::
177
Georg Brandlbb27c122010-11-11 07:26:40 +0000178 >>> topsecret.get('Port')
179 '50022'
180 >>> topsecret.get('CompressionLevel')
181 '9'
182 >>> topsecret.get('Cipher')
183 >>> topsecret.get('Cipher', '3des-cbc')
184 '3des-cbc'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000185
Fred Drake5a7c11f2010-11-13 05:24:17 +0000186Please note that default values have precedence over fallback values.
187For instance, in our example the ``'CompressionLevel'`` key was
188specified only in the ``'DEFAULT'`` section. If we try to get it from
189the section ``'topsecret.server.com'``, we will always get the default,
190even if we specify a fallback:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000191
Łukasz Langa26d513c2010-11-10 18:57:39 +0000192.. doctest::
193
Georg Brandlbb27c122010-11-11 07:26:40 +0000194 >>> topsecret.get('CompressionLevel', '3')
195 '9'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000196
197One more thing to be aware of is that the parser-level :meth:`get` method
198provides a custom, more complex interface, maintained for backwards
Fred Drake5a7c11f2010-11-13 05:24:17 +0000199compatibility. When using this method, a fallback value can be provided via
200the ``fallback`` keyword-only argument:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000201
Łukasz Langa26d513c2010-11-10 18:57:39 +0000202.. doctest::
203
Georg Brandlbb27c122010-11-11 07:26:40 +0000204 >>> config.get('bitbucket.org', 'monster',
205 ... fallback='No such things as monsters')
206 'No such things as monsters'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000207
208The same ``fallback`` argument can be used with the :meth:`getint`,
209:meth:`getfloat` and :meth:`getboolean` methods, for example:
210
Łukasz Langa26d513c2010-11-10 18:57:39 +0000211.. doctest::
212
Georg Brandlbb27c122010-11-11 07:26:40 +0000213 >>> 'BatchMode' in topsecret
214 False
215 >>> topsecret.getboolean('BatchMode', fallback=True)
216 True
217 >>> config['DEFAULT']['BatchMode'] = 'no'
218 >>> topsecret.getboolean('BatchMode', fallback=True)
219 False
220
Łukasz Langa26d513c2010-11-10 18:57:39 +0000221
222Supported INI File Structure
223----------------------------
224
Georg Brandl96a60ae2010-07-28 13:13:46 +0000225A configuration file consists of sections, each led by a ``[section]`` header,
Fred Drakea4923622010-08-09 12:52:45 +0000226followed by key/value entries separated by a specific string (``=`` or ``:`` by
Georg Brandlbb27c122010-11-11 07:26:40 +0000227default [1]_). By default, section names are case sensitive but keys are not
Fred Drake5a7c11f2010-11-13 05:24:17 +0000228[1]_. Leading and trailing whitespace is removed from keys and values.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000229Values can be omitted, in which case the key/value delimiter may also be left
230out. Values can also span multiple lines, as long as they are indented deeper
231than the first line of the value. Depending on the parser's mode, blank lines
232may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000233
Fred Drake5a7c11f2010-11-13 05:24:17 +0000234Configuration files may include comments, prefixed by specific
235characters (``#`` and ``;`` by default [1]_). Comments may appear on
Łukasz Langab25a7912010-12-17 01:32:29 +0000236their own on an otherwise empty line, possibly indented. [1]_
Georg Brandl96a60ae2010-07-28 13:13:46 +0000237
Georg Brandlbb27c122010-11-11 07:26:40 +0000238For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000239
Georg Brandlbb27c122010-11-11 07:26:40 +0000240.. code-block:: ini
Georg Brandl116aa622007-08-15 14:28:22 +0000241
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000242 [Simple Values]
Łukasz Langab25a7912010-12-17 01:32:29 +0000243 key=value
244 spaces in keys=allowed
245 spaces in values=allowed as well
246 spaces around the delimiter = obviously
247 you can also use : to delimit keys from values
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000248
249 [All Values Are Strings]
250 values like this: 1000000
251 or this: 3.14159265359
252 are they treated as numbers? : no
253 integers, floats and booleans are held as: strings
254 can use the API to get converted values directly: true
Georg Brandl116aa622007-08-15 14:28:22 +0000255
Georg Brandl96a60ae2010-07-28 13:13:46 +0000256 [Multiline Values]
257 chorus: I'm a lumberjack, and I'm okay
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000258 I sleep all night and I work all day
Georg Brandl116aa622007-08-15 14:28:22 +0000259
Georg Brandl96a60ae2010-07-28 13:13:46 +0000260 [No Values]
261 key_without_value
262 empty string value here =
Georg Brandl116aa622007-08-15 14:28:22 +0000263
Łukasz Langab25a7912010-12-17 01:32:29 +0000264 [You can use comments]
265 # like this
266 ; or this
267
268 # By default only in an empty line.
269 # Inline comments can be harmful because they prevent users
270 # from using the delimiting characters as parts of values.
271 # That being said, this can be customized.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000272
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000273 [Sections Can Be Indented]
274 can_values_be_as_well = True
275 does_that_mean_anything_special = False
276 purpose = formatting for readability
277 multiline_values = are
278 handled just fine as
279 long as they are indented
280 deeper than the first line
281 of a value
282 # Did I mention we can indent comments, too?
Georg Brandl116aa622007-08-15 14:28:22 +0000283
Georg Brandl96a60ae2010-07-28 13:13:46 +0000284
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000285Interpolation of values
286-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000287
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000288On top of the core functionality, :class:`ConfigParser` supports
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000289interpolation. This means values can be preprocessed before returning them
290from ``get()`` calls.
291
292.. class:: BasicInterpolation()
293
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000294 The default implementation used by :class:`ConfigParser`. It enables
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000295 values to contain format strings which refer to other values in the same
296 section, or values in the special default section [1]_. Additional default
297 values can be provided on initialization.
298
299 For example:
300
301 .. code-block:: ini
302
303 [Paths]
304 home_dir: /Users
305 my_dir: %(home_dir)s/lumberjack
306 my_pictures: %(my_dir)s/Pictures
307
308
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000309 In the example above, :class:`ConfigParser` with *interpolation* set to
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000310 ``BasicInterpolation()`` would resolve ``%(home_dir)s`` to the value of
311 ``home_dir`` (``/Users`` in this case). ``%(my_dir)s`` in effect would
312 resolve to ``/Users/lumberjack``. All interpolations are done on demand so
313 keys used in the chain of references do not have to be specified in any
314 specific order in the configuration file.
315
316 With ``interpolation`` set to ``None``, the parser would simply return
317 ``%(my_dir)s/Pictures`` as the value of ``my_pictures`` and
318 ``%(home_dir)s/lumberjack`` as the value of ``my_dir``.
319
320.. class:: ExtendedInterpolation()
321
322 An alternative handler for interpolation which implements a more advanced
Łukasz Langa34cea142014-09-14 23:37:03 -0700323 syntax, used for instance in ``zc.buildout``. Extended interpolation is
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000324 using ``${section:option}`` to denote a value from a foreign section.
Łukasz Langa34cea142014-09-14 23:37:03 -0700325 Interpolation can span multiple levels. For convenience, if the
326 ``section:`` part is omitted, interpolation defaults to the current section
327 (and possibly the default values from the special section).
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000328
329 For example, the configuration specified above with basic interpolation,
330 would look like this with extended interpolation:
331
332 .. code-block:: ini
333
334 [Paths]
335 home_dir: /Users
336 my_dir: ${home_dir}/lumberjack
337 my_pictures: ${my_dir}/Pictures
338
339 Values from other sections can be fetched as well:
340
341 .. code-block:: ini
342
343 [Common]
344 home_dir: /Users
345 library_dir: /Library
346 system_dir: /System
347 macports_dir: /opt/local
348
349 [Frameworks]
350 Python: 3.2
351 path: ${Common:system_dir}/Library/Frameworks/
352
353 [Arthur]
354 nickname: Two Sheds
355 last_name: Jackson
356 my_dir: ${Common:home_dir}/twosheds
357 my_pictures: ${my_dir}/Pictures
358 python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
Georg Brandlbb27c122010-11-11 07:26:40 +0000359
Łukasz Langa26d513c2010-11-10 18:57:39 +0000360Mapping Protocol Access
361-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000362
Łukasz Langa26d513c2010-11-10 18:57:39 +0000363.. versionadded:: 3.2
Georg Brandl96a60ae2010-07-28 13:13:46 +0000364
Łukasz Langa26d513c2010-11-10 18:57:39 +0000365Mapping protocol access is a generic name for functionality that enables using
Georg Brandlbb27c122010-11-11 07:26:40 +0000366custom objects as if they were dictionaries. In case of :mod:`configparser`,
Łukasz Langa26d513c2010-11-10 18:57:39 +0000367the mapping interface implementation is using the
368``parser['section']['option']`` notation.
369
370``parser['section']`` in particular returns a proxy for the section's data in
Georg Brandlbb27c122010-11-11 07:26:40 +0000371the parser. This means that the values are not copied but they are taken from
372the original parser on demand. What's even more important is that when values
Łukasz Langa26d513c2010-11-10 18:57:39 +0000373are changed on a section proxy, they are actually mutated in the original
374parser.
375
376:mod:`configparser` objects behave as close to actual dictionaries as possible.
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300377The mapping interface is complete and adheres to the
378:class:`~collections.abc.MutableMapping` ABC.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000379However, there are a few differences that should be taken into account:
380
Georg Brandlbb27c122010-11-11 07:26:40 +0000381* By default, all keys in sections are accessible in a case-insensitive manner
382 [1]_. E.g. ``for option in parser["section"]`` yields only ``optionxform``'ed
383 option key names. This means lowercased keys by default. At the same time,
Fred Drake5a7c11f2010-11-13 05:24:17 +0000384 for a section that holds the key ``'a'``, both expressions return ``True``::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000385
Georg Brandlbb27c122010-11-11 07:26:40 +0000386 "a" in parser["section"]
387 "A" in parser["section"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000388
Georg Brandlbb27c122010-11-11 07:26:40 +0000389* All sections include ``DEFAULTSECT`` values as well which means that
390 ``.clear()`` on a section may not leave the section visibly empty. This is
Łukasz Langa26d513c2010-11-10 18:57:39 +0000391 because default values cannot be deleted from the section (because technically
Donald Stufft8b852f12014-05-20 12:58:38 -0400392 they are not there). If they are overridden in the section, deleting causes
Georg Brandlbb27c122010-11-11 07:26:40 +0000393 the default value to be visible again. Trying to delete a default value
394 causes a ``KeyError``.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000395
Łukasz Langa3a8479a2012-12-31 03:38:39 +0100396* ``DEFAULTSECT`` cannot be removed from the parser:
397
398 * trying to delete it raises ``ValueError``,
399
400 * ``parser.clear()`` leaves it intact,
401
402 * ``parser.popitem()`` never returns it.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000403
Łukasz Langa71b37a52010-12-17 21:56:32 +0000404* ``parser.get(section, option, **kwargs)`` - the second argument is **not**
Łukasz Langa34cea142014-09-14 23:37:03 -0700405 a fallback value. Note however that the section-level ``get()`` methods are
Łukasz Langa71b37a52010-12-17 21:56:32 +0000406 compatible both with the mapping protocol and the classic configparser API.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000407
Łukasz Langa71b37a52010-12-17 21:56:32 +0000408* ``parser.items()`` is compatible with the mapping protocol (returns a list of
409 *section_name*, *section_proxy* pairs including the DEFAULTSECT). However,
410 this method can also be invoked with arguments: ``parser.items(section, raw,
Łukasz Langa34cea142014-09-14 23:37:03 -0700411 vars)``. The latter call returns a list of *option*, *value* pairs for
Łukasz Langa71b37a52010-12-17 21:56:32 +0000412 a specified ``section``, with all interpolations expanded (unless
413 ``raw=True`` is provided).
Łukasz Langa26d513c2010-11-10 18:57:39 +0000414
415The mapping protocol is implemented on top of the existing legacy API so that
Łukasz Langa71b37a52010-12-17 21:56:32 +0000416subclasses overriding the original interface still should have mappings working
417as expected.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000418
Georg Brandlbb27c122010-11-11 07:26:40 +0000419
Łukasz Langa26d513c2010-11-10 18:57:39 +0000420Customizing Parser Behaviour
421----------------------------
422
423There are nearly as many INI format variants as there are applications using it.
424:mod:`configparser` goes a long way to provide support for the largest sensible
Georg Brandlbb27c122010-11-11 07:26:40 +0000425set of INI styles available. The default functionality is mainly dictated by
Łukasz Langa26d513c2010-11-10 18:57:39 +0000426historical background and it's very likely that you will want to customize some
427of the features.
428
Fred Drake5a7c11f2010-11-13 05:24:17 +0000429The most common way to change the way a specific config parser works is to use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000430the :meth:`__init__` options:
431
432* *defaults*, default value: ``None``
433
434 This option accepts a dictionary of key-value pairs which will be initially
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000435 put in the ``DEFAULT`` section. This makes for an elegant way to support
436 concise configuration files that don't specify values which are the same as
437 the documented default.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000438
Fred Drake5a7c11f2010-11-13 05:24:17 +0000439 Hint: if you want to specify default values for a specific section, use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000440 :meth:`read_dict` before you read the actual file.
441
442* *dict_type*, default value: :class:`collections.OrderedDict`
443
444 This option has a major impact on how the mapping protocol will behave and how
Fred Drake5a7c11f2010-11-13 05:24:17 +0000445 the written configuration files look. With the default ordered
Łukasz Langa26d513c2010-11-10 18:57:39 +0000446 dictionary, every section is stored in the order they were added to the
Georg Brandlbb27c122010-11-11 07:26:40 +0000447 parser. Same goes for options within sections.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000448
449 An alternative dictionary type can be used for example to sort sections and
Georg Brandlbb27c122010-11-11 07:26:40 +0000450 options on write-back. You can also use a regular dictionary for performance
Łukasz Langa26d513c2010-11-10 18:57:39 +0000451 reasons.
452
453 Please note: there are ways to add a set of key-value pairs in a single
Georg Brandlbb27c122010-11-11 07:26:40 +0000454 operation. When you use a regular dictionary in those operations, the order
455 of the keys may be random. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000456
Łukasz Langa26d513c2010-11-10 18:57:39 +0000457 .. doctest::
458
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000459 >>> parser = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000460 >>> parser.read_dict({'section1': {'key1': 'value1',
461 ... 'key2': 'value2',
462 ... 'key3': 'value3'},
463 ... 'section2': {'keyA': 'valueA',
464 ... 'keyB': 'valueB',
465 ... 'keyC': 'valueC'},
466 ... 'section3': {'foo': 'x',
467 ... 'bar': 'y',
468 ... 'baz': 'z'}
469 ... })
470 >>> parser.sections()
471 ['section3', 'section2', 'section1']
472 >>> [option for option in parser['section3']]
473 ['baz', 'foo', 'bar']
Łukasz Langa26d513c2010-11-10 18:57:39 +0000474
475 In these operations you need to use an ordered dictionary as well:
476
Łukasz Langa26d513c2010-11-10 18:57:39 +0000477 .. doctest::
478
Georg Brandlbb27c122010-11-11 07:26:40 +0000479 >>> from collections import OrderedDict
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000480 >>> parser = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000481 >>> parser.read_dict(
482 ... OrderedDict((
483 ... ('s1',
484 ... OrderedDict((
485 ... ('1', '2'),
486 ... ('3', '4'),
487 ... ('5', '6'),
488 ... ))
489 ... ),
490 ... ('s2',
491 ... OrderedDict((
492 ... ('a', 'b'),
493 ... ('c', 'd'),
494 ... ('e', 'f'),
495 ... ))
496 ... ),
497 ... ))
498 ... )
499 >>> parser.sections()
500 ['s1', 's2']
501 >>> [option for option in parser['s1']]
502 ['1', '3', '5']
503 >>> [option for option in parser['s2'].values()]
504 ['b', 'd', 'f']
Łukasz Langa26d513c2010-11-10 18:57:39 +0000505
506* *allow_no_value*, default value: ``False``
507
508 Some configuration files are known to include settings without values, but
509 which otherwise conform to the syntax supported by :mod:`configparser`. The
Fred Drake5a7c11f2010-11-13 05:24:17 +0000510 *allow_no_value* parameter to the constructor can be used to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000511 indicate that such values should be accepted:
512
Łukasz Langa26d513c2010-11-10 18:57:39 +0000513 .. doctest::
514
Georg Brandlbb27c122010-11-11 07:26:40 +0000515 >>> import configparser
Łukasz Langa26d513c2010-11-10 18:57:39 +0000516
Georg Brandlbb27c122010-11-11 07:26:40 +0000517 >>> sample_config = """
518 ... [mysqld]
519 ... user = mysql
520 ... pid-file = /var/run/mysqld/mysqld.pid
521 ... skip-external-locking
522 ... old_passwords = 1
523 ... skip-bdb
Łukasz Langab25a7912010-12-17 01:32:29 +0000524 ... # we don't need ACID today
525 ... skip-innodb
Georg Brandlbb27c122010-11-11 07:26:40 +0000526 ... """
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000527 >>> config = configparser.ConfigParser(allow_no_value=True)
Georg Brandlbb27c122010-11-11 07:26:40 +0000528 >>> config.read_string(sample_config)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000529
Georg Brandlbb27c122010-11-11 07:26:40 +0000530 >>> # Settings with values are treated as before:
531 >>> config["mysqld"]["user"]
532 'mysql'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000533
Georg Brandlbb27c122010-11-11 07:26:40 +0000534 >>> # Settings without values provide None:
535 >>> config["mysqld"]["skip-bdb"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000536
Georg Brandlbb27c122010-11-11 07:26:40 +0000537 >>> # Settings which aren't specified still raise an error:
538 >>> config["mysqld"]["does-not-exist"]
539 Traceback (most recent call last):
540 ...
541 KeyError: 'does-not-exist'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000542
543* *delimiters*, default value: ``('=', ':')``
544
Łukasz Langa34cea142014-09-14 23:37:03 -0700545 Delimiters are substrings that delimit keys from values within a section.
546 The first occurrence of a delimiting substring on a line is considered
547 a delimiter. This means values (but not keys) can contain the delimiters.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000548
549 See also the *space_around_delimiters* argument to
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000550 :meth:`ConfigParser.write`.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000551
Łukasz Langab25a7912010-12-17 01:32:29 +0000552* *comment_prefixes*, default value: ``('#', ';')``
Łukasz Langa26d513c2010-11-10 18:57:39 +0000553
Łukasz Langab25a7912010-12-17 01:32:29 +0000554* *inline_comment_prefixes*, default value: ``None``
555
556 Comment prefixes are strings that indicate the start of a valid comment within
557 a config file. *comment_prefixes* are used only on otherwise empty lines
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700558 (optionally indented) whereas *inline_comment_prefixes* can be used after
559 every valid value (e.g. section names, options and empty lines as well). By
560 default inline comments are disabled and ``'#'`` and ``';'`` are used as
561 prefixes for whole line comments.
Łukasz Langab25a7912010-12-17 01:32:29 +0000562
563 .. versionchanged:: 3.2
564 In previous versions of :mod:`configparser` behaviour matched
565 ``comment_prefixes=('#',';')`` and ``inline_comment_prefixes=(';',)``.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000566
567 Please note that config parsers don't support escaping of comment prefixes so
Łukasz Langab25a7912010-12-17 01:32:29 +0000568 using *inline_comment_prefixes* may prevent users from specifying option
Łukasz Langa34cea142014-09-14 23:37:03 -0700569 values with characters used as comment prefixes. When in doubt, avoid
570 setting *inline_comment_prefixes*. In any circumstances, the only way of
571 storing comment prefix characters at the beginning of a line in multiline
572 values is to interpolate the prefix, for example::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000573
Łukasz Langab25a7912010-12-17 01:32:29 +0000574 >>> from configparser import ConfigParser, ExtendedInterpolation
575 >>> parser = ConfigParser(interpolation=ExtendedInterpolation())
576 >>> # the default BasicInterpolation could be used as well
577 >>> parser.read_string("""
578 ... [DEFAULT]
579 ... hash = #
580 ...
581 ... [hashes]
582 ... shebang =
583 ... ${hash}!/usr/bin/env python
584 ... ${hash} -*- coding: utf-8 -*-
585 ...
586 ... extensions =
587 ... enabled_extension
588 ... another_extension
589 ... #disabled_by_comment
590 ... yet_another_extension
591 ...
592 ... interpolation not necessary = if # is not at line start
593 ... even in multiline values = line #1
594 ... line #2
595 ... line #3
596 ... """)
597 >>> print(parser['hashes']['shebang'])
Łukasz Langa26d513c2010-11-10 18:57:39 +0000598
Łukasz Langab25a7912010-12-17 01:32:29 +0000599 #!/usr/bin/env python
600 # -*- coding: utf-8 -*-
601 >>> print(parser['hashes']['extensions'])
602
603 enabled_extension
604 another_extension
605 yet_another_extension
606 >>> print(parser['hashes']['interpolation not necessary'])
607 if # is not at line start
608 >>> print(parser['hashes']['even in multiline values'])
609 line #1
610 line #2
611 line #3
612
613* *strict*, default value: ``True``
614
615 When set to ``True``, the parser will not allow for any section or option
Łukasz Langa26d513c2010-11-10 18:57:39 +0000616 duplicates while reading from a single source (using :meth:`read_file`,
Łukasz Langa34cea142014-09-14 23:37:03 -0700617 :meth:`read_string` or :meth:`read_dict`). It is recommended to use strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000618 parsers in new applications.
619
Łukasz Langab25a7912010-12-17 01:32:29 +0000620 .. versionchanged:: 3.2
621 In previous versions of :mod:`configparser` behaviour matched
622 ``strict=False``.
623
Łukasz Langa26d513c2010-11-10 18:57:39 +0000624* *empty_lines_in_values*, default value: ``True``
625
Fred Drake5a7c11f2010-11-13 05:24:17 +0000626 In config parsers, values can span multiple lines as long as they are
627 indented more than the key that holds them. By default parsers also let
628 empty lines to be parts of values. At the same time, keys can be arbitrarily
629 indented themselves to improve readability. In consequence, when
630 configuration files get big and complex, it is easy for the user to lose
631 track of the file structure. Take for instance:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000632
Georg Brandlbb27c122010-11-11 07:26:40 +0000633 .. code-block:: ini
Łukasz Langa26d513c2010-11-10 18:57:39 +0000634
Georg Brandlbb27c122010-11-11 07:26:40 +0000635 [Section]
636 key = multiline
637 value with a gotcha
Łukasz Langa26d513c2010-11-10 18:57:39 +0000638
Georg Brandlbb27c122010-11-11 07:26:40 +0000639 this = is still a part of the multiline value of 'key'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000640
Georg Brandlbb27c122010-11-11 07:26:40 +0000641 This can be especially problematic for the user to see if she's using a
642 proportional font to edit the file. That is why when your application does
643 not need values with empty lines, you should consider disallowing them. This
644 will make empty lines split keys every time. In the example above, it would
Łukasz Langa26d513c2010-11-10 18:57:39 +0000645 produce two keys, ``key`` and ``this``.
646
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000647* *default_section*, default value: ``configparser.DEFAULTSECT`` (that is:
648 ``"DEFAULT"``)
649
650 The convention of allowing a special section of default values for other
651 sections or interpolation purposes is a powerful concept of this library,
Łukasz Langa34cea142014-09-14 23:37:03 -0700652 letting users create complex declarative configurations. This section is
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000653 normally called ``"DEFAULT"`` but this can be customized to point to any
Łukasz Langa34cea142014-09-14 23:37:03 -0700654 other valid section name. Some typical values include: ``"general"`` or
655 ``"common"``. The name provided is used for recognizing default sections
656 when reading from any source and is used when writing configuration back to
657 a file. Its current value can be retrieved using the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000658 ``parser_instance.default_section`` attribute and may be modified at runtime
659 (i.e. to convert files from one format to another).
660
661* *interpolation*, default value: ``configparser.BasicInterpolation``
662
663 Interpolation behaviour may be customized by providing a custom handler
664 through the *interpolation* argument. ``None`` can be used to turn off
665 interpolation completely, ``ExtendedInterpolation()`` provides a more
Łukasz Langa34cea142014-09-14 23:37:03 -0700666 advanced variant inspired by ``zc.buildout``. More on the subject in the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000667 `dedicated documentation section <#interpolation-of-values>`_.
Łukasz Langab25a7912010-12-17 01:32:29 +0000668 :class:`RawConfigParser` has a default value of ``None``.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000669
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700670* *converters*, default value: not set
671
672 Config parsers provide option value getters that perform type conversion. By
673 default :meth:`getint`, :meth:`getfloat`, and :meth:`getboolean` are
674 implemented. Should other getters be desirable, users may define them in
675 a subclass or pass a dictionary where each key is a name of the converter and
676 each value is a callable implementing said conversion. For instance, passing
677 ``{'decimal': decimal.Decimal}`` would add :meth:`getdecimal` on both the
678 parser object and all section proxies. In other words, it will be possible
679 to write both ``parser_instance.getdecimal('section', 'key', fallback=0)``
680 and ``parser_instance['section'].getdecimal('key', 0)``.
681
682 If the converter needs to access the state of the parser, it can be
683 implemented as a method on a config parser subclass. If the name of this
684 method starts with ``get``, it will be available on all section proxies, in
685 the dict-compatible form (see the ``getdecimal()`` example above).
Łukasz Langa26d513c2010-11-10 18:57:39 +0000686
Fred Drake5a7c11f2010-11-13 05:24:17 +0000687More advanced customization may be achieved by overriding default values of
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700688these parser attributes. The defaults are defined on the classes, so they may
689be overridden by subclasses or by attribute assignment.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000690
Fred Drake5a7c11f2010-11-13 05:24:17 +0000691.. attribute:: BOOLEAN_STATES
Łukasz Langa26d513c2010-11-10 18:57:39 +0000692
693 By default when using :meth:`getboolean`, config parsers consider the
694 following values ``True``: ``'1'``, ``'yes'``, ``'true'``, ``'on'`` and the
Georg Brandlbb27c122010-11-11 07:26:40 +0000695 following values ``False``: ``'0'``, ``'no'``, ``'false'``, ``'off'``. You
696 can override this by specifying a custom dictionary of strings and their
Fred Drake5a7c11f2010-11-13 05:24:17 +0000697 Boolean outcomes. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000698
Łukasz Langa26d513c2010-11-10 18:57:39 +0000699 .. doctest::
700
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000701 >>> custom = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000702 >>> custom['section1'] = {'funky': 'nope'}
703 >>> custom['section1'].getboolean('funky')
704 Traceback (most recent call last):
705 ...
706 ValueError: Not a boolean: nope
707 >>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}
708 >>> custom['section1'].getboolean('funky')
709 False
Łukasz Langa26d513c2010-11-10 18:57:39 +0000710
Fred Drake5a7c11f2010-11-13 05:24:17 +0000711 Other typical Boolean pairs include ``accept``/``reject`` or
Łukasz Langa26d513c2010-11-10 18:57:39 +0000712 ``enabled``/``disabled``.
713
Fred Drake5a7c11f2010-11-13 05:24:17 +0000714.. method:: optionxform(option)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000715
Fred Drake5a7c11f2010-11-13 05:24:17 +0000716 This method transforms option names on every read, get, or set
717 operation. The default converts the name to lowercase. This also
718 means that when a configuration file gets written, all keys will be
719 lowercase. Override this method if that's unsuitable.
720 For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000721
Łukasz Langa26d513c2010-11-10 18:57:39 +0000722 .. doctest::
723
Georg Brandlbb27c122010-11-11 07:26:40 +0000724 >>> config = """
725 ... [Section1]
726 ... Key = Value
727 ...
728 ... [Section2]
729 ... AnotherKey = Value
730 ... """
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000731 >>> typical = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000732 >>> typical.read_string(config)
733 >>> list(typical['Section1'].keys())
734 ['key']
735 >>> list(typical['Section2'].keys())
736 ['anotherkey']
737 >>> custom = configparser.RawConfigParser()
738 >>> custom.optionxform = lambda option: option
739 >>> custom.read_string(config)
740 >>> list(custom['Section1'].keys())
741 ['Key']
742 >>> list(custom['Section2'].keys())
743 ['AnotherKey']
744
Łukasz Langa66c908e2011-01-28 11:57:30 +0000745.. attribute:: SECTCRE
746
Łukasz Langa34cea142014-09-14 23:37:03 -0700747 A compiled regular expression used to parse section headers. The default
748 matches ``[section]`` to the name ``"section"``. Whitespace is considered
749 part of the section name, thus ``[ larch ]`` will be read as a section of
750 name ``" larch "``. Override this attribute if that's unsuitable. For
751 example:
Łukasz Langa66c908e2011-01-28 11:57:30 +0000752
753 .. doctest::
754
755 >>> config = """
756 ... [Section 1]
757 ... option = value
758 ...
759 ... [ Section 2 ]
760 ... another = val
761 ... """
762 >>> typical = ConfigParser()
763 >>> typical.read_string(config)
764 >>> typical.sections()
765 ['Section 1', ' Section 2 ']
766 >>> custom = ConfigParser()
767 >>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]")
768 >>> custom.read_string(config)
769 >>> custom.sections()
770 ['Section 1', 'Section 2']
771
772 .. note::
773
774 While ConfigParser objects also use an ``OPTCRE`` attribute for recognizing
775 option lines, it's not recommended to override it because that would
776 interfere with constructor options *allow_no_value* and *delimiters*.
777
Łukasz Langa26d513c2010-11-10 18:57:39 +0000778
779Legacy API Examples
780-------------------
781
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000782Mainly because of backwards compatibility concerns, :mod:`configparser`
783provides also a legacy API with explicit ``get``/``set`` methods. While there
784are valid use cases for the methods outlined below, mapping protocol access is
785preferred for new projects. The legacy API is at times more advanced,
786low-level and downright counterintuitive.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000787
788An example of writing to a configuration file::
789
790 import configparser
791
792 config = configparser.RawConfigParser()
793
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000794 # Please note that using RawConfigParser's set functions, you can assign
795 # non-string values to keys internally, but will receive an error when
796 # attempting to write to a file or when you get it in non-raw mode. Setting
797 # values using the mapping protocol or ConfigParser's set() does not allow
798 # such assignments to take place.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000799 config.add_section('Section1')
R David Murray1a1883d2012-09-29 14:40:23 -0400800 config.set('Section1', 'an_int', '15')
801 config.set('Section1', 'a_bool', 'true')
802 config.set('Section1', 'a_float', '3.1415')
Łukasz Langa26d513c2010-11-10 18:57:39 +0000803 config.set('Section1', 'baz', 'fun')
804 config.set('Section1', 'bar', 'Python')
805 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
806
807 # Writing our configuration file to 'example.cfg'
808 with open('example.cfg', 'w') as configfile:
809 config.write(configfile)
810
811An example of reading the configuration file again::
812
813 import configparser
814
815 config = configparser.RawConfigParser()
816 config.read('example.cfg')
817
818 # getfloat() raises an exception if the value is not a float
819 # getint() and getboolean() also do this for their respective types
R David Murray1a1883d2012-09-29 14:40:23 -0400820 a_float = config.getfloat('Section1', 'a_float')
821 an_int = config.getint('Section1', 'an_int')
822 print(a_float + an_int)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000823
824 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
825 # This is because we are using a RawConfigParser().
R David Murray1a1883d2012-09-29 14:40:23 -0400826 if config.getboolean('Section1', 'a_bool'):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000827 print(config.get('Section1', 'foo'))
828
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000829To get interpolation, use :class:`ConfigParser`::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000830
831 import configparser
832
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000833 cfg = configparser.ConfigParser()
Łukasz Langa26d513c2010-11-10 18:57:39 +0000834 cfg.read('example.cfg')
835
Éric Araujo941afed2011-09-01 02:47:34 +0200836 # Set the optional *raw* argument of get() to True if you wish to disable
Łukasz Langa26d513c2010-11-10 18:57:39 +0000837 # interpolation in a single get operation.
Serhiy Storchakadba90392016-05-10 12:01:23 +0300838 print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!"
839 print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!"
Łukasz Langa26d513c2010-11-10 18:57:39 +0000840
Éric Araujo941afed2011-09-01 02:47:34 +0200841 # The optional *vars* argument is a dict with members that will take
Łukasz Langa26d513c2010-11-10 18:57:39 +0000842 # precedence in interpolation.
843 print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation',
Serhiy Storchakadba90392016-05-10 12:01:23 +0300844 'baz': 'evil'}))
Łukasz Langa26d513c2010-11-10 18:57:39 +0000845
Éric Araujo941afed2011-09-01 02:47:34 +0200846 # The optional *fallback* argument can be used to provide a fallback value
Łukasz Langa26d513c2010-11-10 18:57:39 +0000847 print(cfg.get('Section1', 'foo'))
848 # -> "Python is fun!"
849
850 print(cfg.get('Section1', 'foo', fallback='Monty is not.'))
851 # -> "Python is fun!"
852
853 print(cfg.get('Section1', 'monster', fallback='No such things as monsters.'))
854 # -> "No such things as monsters."
855
856 # A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError
857 # but we can also use:
858
859 print(cfg.get('Section1', 'monster', fallback=None))
860 # -> None
861
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000862Default values are available in both types of ConfigParsers. They are used in
863interpolation if an option used is not defined elsewhere. ::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000864
865 import configparser
866
867 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000868 config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'})
Łukasz Langa26d513c2010-11-10 18:57:39 +0000869 config.read('example.cfg')
870
Serhiy Storchakadba90392016-05-10 12:01:23 +0300871 print(config.get('Section1', 'foo')) # -> "Python is fun!"
Łukasz Langa26d513c2010-11-10 18:57:39 +0000872 config.remove_option('Section1', 'bar')
873 config.remove_option('Section1', 'baz')
Serhiy Storchakadba90392016-05-10 12:01:23 +0300874 print(config.get('Section1', 'foo')) # -> "Life is hard!"
Łukasz Langa26d513c2010-11-10 18:57:39 +0000875
Georg Brandlbb27c122010-11-11 07:26:40 +0000876
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000877.. _configparser-objects:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000878
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000879ConfigParser Objects
880--------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000881
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700882.. 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 +0000883
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000884 The main configuration parser. When *defaults* is given, it is initialized
Georg Brandl96a60ae2010-07-28 13:13:46 +0000885 into the dictionary of intrinsic defaults. When *dict_type* is given, it
886 will be used to create the dictionary objects for the list of sections, for
887 the options within a section, and for the default values.
888
Fred Drake5a7c11f2010-11-13 05:24:17 +0000889 When *delimiters* is given, it is used as the set of substrings that
Georg Brandl96a60ae2010-07-28 13:13:46 +0000890 divide keys from values. When *comment_prefixes* is given, it will be used
Łukasz Langab25a7912010-12-17 01:32:29 +0000891 as the set of substrings that prefix comments in otherwise empty lines.
Łukasz Langa34cea142014-09-14 23:37:03 -0700892 Comments can be indented. When *inline_comment_prefixes* is given, it will
893 be used as the set of substrings that prefix comments in non-empty lines.
Łukasz Langab25a7912010-12-17 01:32:29 +0000894
Łukasz Langab25a7912010-12-17 01:32:29 +0000895 When *strict* is ``True`` (the default), the parser won't allow for
Fred Drakea4923622010-08-09 12:52:45 +0000896 any section or option duplicates while reading from a single source (file,
897 string or dictionary), raising :exc:`DuplicateSectionError` or
Fred Drake5a7c11f2010-11-13 05:24:17 +0000898 :exc:`DuplicateOptionError`. When *empty_lines_in_values* is ``False``
Fred Drakea4923622010-08-09 12:52:45 +0000899 (default: ``True``), each empty line marks the end of an option. Otherwise,
900 internal empty lines of a multiline option are kept as part of the value.
901 When *allow_no_value* is ``True`` (default: ``False``), options without
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000902 values are accepted; the value held for these is ``None`` and they are
903 serialized without the trailing delimiter.
Fred Drake03c44a32010-02-19 06:08:41 +0000904
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000905 When *default_section* is given, it specifies the name for the special
906 section holding default values for other sections and interpolation purposes
Łukasz Langa34cea142014-09-14 23:37:03 -0700907 (normally named ``"DEFAULT"``). This value can be retrieved and changed on
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000908 runtime using the ``default_section`` instance attribute.
909
910 Interpolation behaviour may be customized by providing a custom handler
911 through the *interpolation* argument. ``None`` can be used to turn off
912 interpolation completely, ``ExtendedInterpolation()`` provides a more
Łukasz Langa34cea142014-09-14 23:37:03 -0700913 advanced variant inspired by ``zc.buildout``. More on the subject in the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000914 `dedicated documentation section <#interpolation-of-values>`_.
915
916 All option names used in interpolation will be passed through the
917 :meth:`optionxform` method just like any other option name reference. For
918 example, using the default implementation of :meth:`optionxform` (which
919 converts option names to lower case), the values ``foo %(bar)s`` and ``foo
920 %(BAR)s`` are equivalent.
Georg Brandl116aa622007-08-15 14:28:22 +0000921
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700922 When *converters* is given, it should be a dictionary where each key
923 represents the name of a type converter and each value is a callable
924 implementing the conversion from string to the desired datatype. Every
925 converter gets its own corresponding :meth:`get*()` method on the parser
926 object and section proxies.
927
Raymond Hettinger231b7f12009-03-03 00:23:19 +0000928 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +0000929 The default *dict_type* is :class:`collections.OrderedDict`.
930
Fred Drake03c44a32010-02-19 06:08:41 +0000931 .. versionchanged:: 3.2
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000932 *allow_no_value*, *delimiters*, *comment_prefixes*, *strict*,
933 *empty_lines_in_values*, *default_section* and *interpolation* were
934 added.
Georg Brandl116aa622007-08-15 14:28:22 +0000935
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700936 .. versionchanged:: 3.5
937 The *converters* argument was added.
938
Fred Drake03c44a32010-02-19 06:08:41 +0000939
Georg Brandlbb27c122010-11-11 07:26:40 +0000940 .. method:: defaults()
Georg Brandl116aa622007-08-15 14:28:22 +0000941
Georg Brandlbb27c122010-11-11 07:26:40 +0000942 Return a dictionary containing the instance-wide defaults.
Georg Brandl116aa622007-08-15 14:28:22 +0000943
944
Georg Brandlbb27c122010-11-11 07:26:40 +0000945 .. method:: sections()
Georg Brandl116aa622007-08-15 14:28:22 +0000946
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000947 Return a list of the sections available; the *default section* is not
948 included in the list.
Georg Brandl116aa622007-08-15 14:28:22 +0000949
950
Georg Brandlbb27c122010-11-11 07:26:40 +0000951 .. method:: add_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000952
Georg Brandlbb27c122010-11-11 07:26:40 +0000953 Add a section named *section* to the instance. If a section by the given
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000954 name already exists, :exc:`DuplicateSectionError` is raised. If the
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000955 *default section* name is passed, :exc:`ValueError` is raised. The name
956 of the section must be a string; if not, :exc:`TypeError` is raised.
957
958 .. versionchanged:: 3.2
959 Non-string section names raise :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000960
Georg Brandl116aa622007-08-15 14:28:22 +0000961
Georg Brandlbb27c122010-11-11 07:26:40 +0000962 .. method:: has_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000963
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000964 Indicates whether the named *section* is present in the configuration.
965 The *default section* is not acknowledged.
Georg Brandl116aa622007-08-15 14:28:22 +0000966
Georg Brandl116aa622007-08-15 14:28:22 +0000967
Georg Brandlbb27c122010-11-11 07:26:40 +0000968 .. method:: options(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000969
Georg Brandlbb27c122010-11-11 07:26:40 +0000970 Return a list of options available in the specified *section*.
Georg Brandl116aa622007-08-15 14:28:22 +0000971
Georg Brandl116aa622007-08-15 14:28:22 +0000972
Georg Brandlbb27c122010-11-11 07:26:40 +0000973 .. method:: has_option(section, option)
Georg Brandl116aa622007-08-15 14:28:22 +0000974
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000975 If the given *section* exists, and contains the given *option*, return
Łukasz Langa34cea142014-09-14 23:37:03 -0700976 :const:`True`; otherwise return :const:`False`. If the specified
Łukasz Langa71b37a52010-12-17 21:56:32 +0000977 *section* is :const:`None` or an empty string, DEFAULT is assumed.
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(filenames, encoding=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000981
Georg Brandlbb27c122010-11-11 07:26:40 +0000982 Attempt to read and parse a list of filenames, returning a list of
983 filenames which were successfully parsed. If *filenames* is a string, it
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000984 is treated as a single filename. If a file named in *filenames* cannot
985 be opened, that file will be ignored. This is designed so that you can
986 specify a list of potential configuration file locations (for example,
987 the current directory, the user's home directory, and some system-wide
988 directory), and all existing configuration files in the list will be
989 read. If none of the named files exist, the :class:`ConfigParser`
990 instance will contain an empty dataset. An application which requires
991 initial values to be loaded from a file should load the required file or
992 files using :meth:`read_file` before calling :meth:`read` for any
993 optional files::
Georg Brandl116aa622007-08-15 14:28:22 +0000994
Georg Brandlbb27c122010-11-11 07:26:40 +0000995 import configparser, os
Georg Brandl8dcaa732010-07-29 12:17:40 +0000996
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000997 config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000998 config.read_file(open('defaults.cfg'))
999 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
1000 encoding='cp1250')
Georg Brandl116aa622007-08-15 14:28:22 +00001001
Georg Brandlbb27c122010-11-11 07:26:40 +00001002 .. versionadded:: 3.2
1003 The *encoding* parameter. Previously, all files were read using the
1004 default encoding for :func:`open`.
Georg Brandl116aa622007-08-15 14:28:22 +00001005
Georg Brandl116aa622007-08-15 14:28:22 +00001006
Georg Brandlbb27c122010-11-11 07:26:40 +00001007 .. method:: read_file(f, source=None)
Georg Brandl73753d32009-09-22 13:53:14 +00001008
Łukasz Langadaab1c82011-04-27 18:10:05 +02001009 Read and parse configuration data from *f* which must be an iterable
Łukasz Langaba702da2011-04-28 12:02:05 +02001010 yielding Unicode strings (for example files opened in text mode).
Georg Brandl116aa622007-08-15 14:28:22 +00001011
Georg Brandlbb27c122010-11-11 07:26:40 +00001012 Optional argument *source* specifies the name of the file being read. If
Fred Drake5a7c11f2010-11-13 05:24:17 +00001013 not given and *f* has a :attr:`name` attribute, that is used for
1014 *source*; the default is ``'<???>'``.
Fred Drakea4923622010-08-09 12:52:45 +00001015
Georg Brandlbb27c122010-11-11 07:26:40 +00001016 .. versionadded:: 3.2
Łukasz Langa43ae6192011-04-27 18:13:42 +02001017 Replaces :meth:`readfp`.
1018
Georg Brandlbb27c122010-11-11 07:26:40 +00001019 .. method:: read_string(string, source='<string>')
Fred Drakea4923622010-08-09 12:52:45 +00001020
Fred Drake5a7c11f2010-11-13 05:24:17 +00001021 Parse configuration data from a string.
Fred Drakea4923622010-08-09 12:52:45 +00001022
Fred Drake5a7c11f2010-11-13 05:24:17 +00001023 Optional argument *source* specifies a context-specific name of the
1024 string passed. If not given, ``'<string>'`` is used. This should
1025 commonly be a filesystem path or a URL.
Fred Drakea4923622010-08-09 12:52:45 +00001026
Georg Brandlbb27c122010-11-11 07:26:40 +00001027 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +00001028
Fred Drakea4923622010-08-09 12:52:45 +00001029
Georg Brandlbb27c122010-11-11 07:26:40 +00001030 .. method:: read_dict(dictionary, source='<dict>')
Fred Drakea4923622010-08-09 12:52:45 +00001031
Łukasz Langa71b37a52010-12-17 21:56:32 +00001032 Load configuration from any object that provides a dict-like ``items()``
1033 method. Keys are section names, values are dictionaries with keys and
1034 values that should be present in the section. If the used dictionary
1035 type preserves order, sections and their keys will be added in order.
1036 Values are automatically converted to strings.
Fred Drakea4923622010-08-09 12:52:45 +00001037
Georg Brandlbb27c122010-11-11 07:26:40 +00001038 Optional argument *source* specifies a context-specific name of the
1039 dictionary passed. If not given, ``<dict>`` is used.
Georg Brandl116aa622007-08-15 14:28:22 +00001040
Łukasz Langa71b37a52010-12-17 21:56:32 +00001041 This method can be used to copy state between parsers.
1042
Georg Brandlbb27c122010-11-11 07:26:40 +00001043 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +00001044
Georg Brandl116aa622007-08-15 14:28:22 +00001045
Ezio Melottie927e252012-09-08 20:46:01 +03001046 .. method:: get(section, option, *, raw=False, vars=None[, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +00001047
Georg Brandlbb27c122010-11-11 07:26:40 +00001048 Get an *option* value for the named *section*. If *vars* is provided, it
1049 must be a dictionary. The *option* is looked up in *vars* (if provided),
1050 *section*, and in *DEFAULTSECT* in that order. If the key is not found
1051 and *fallback* is provided, it is used as a fallback value. ``None`` can
1052 be provided as a *fallback* value.
Georg Brandl470a1232010-07-29 14:17:12 +00001053
Georg Brandlbb27c122010-11-11 07:26:40 +00001054 All the ``'%'`` interpolations are expanded in the return values, unless
1055 the *raw* argument is true. Values for interpolation keys are looked up
1056 in the same manner as the option.
Georg Brandl116aa622007-08-15 14:28:22 +00001057
Georg Brandlbb27c122010-11-11 07:26:40 +00001058 .. versionchanged:: 3.2
1059 Arguments *raw*, *vars* and *fallback* are keyword only to protect
1060 users from trying to use the third argument as the *fallback* fallback
1061 (especially when using the mapping protocol).
Georg Brandl116aa622007-08-15 14:28:22 +00001062
Łukasz Langa26d513c2010-11-10 18:57:39 +00001063
Ezio Melottie927e252012-09-08 20:46:01 +03001064 .. method:: getint(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001065
Georg Brandlbb27c122010-11-11 07:26:40 +00001066 A convenience method which coerces the *option* in the specified *section*
1067 to an integer. See :meth:`get` for explanation of *raw*, *vars* and
1068 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001069
1070
Ezio Melottie927e252012-09-08 20:46:01 +03001071 .. method:: getfloat(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001072
Georg Brandlbb27c122010-11-11 07:26:40 +00001073 A convenience method which coerces the *option* in the specified *section*
1074 to a floating point number. See :meth:`get` for explanation of *raw*,
1075 *vars* and *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001076
1077
Ezio Melottie927e252012-09-08 20:46:01 +03001078 .. method:: getboolean(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001079
Georg Brandlbb27c122010-11-11 07:26:40 +00001080 A convenience method which coerces the *option* in the specified *section*
1081 to a Boolean value. Note that the accepted values for the option are
Fred Drake5a7c11f2010-11-13 05:24:17 +00001082 ``'1'``, ``'yes'``, ``'true'``, and ``'on'``, which cause this method to
1083 return ``True``, and ``'0'``, ``'no'``, ``'false'``, and ``'off'``, which
Georg Brandlbb27c122010-11-11 07:26:40 +00001084 cause it to return ``False``. These string values are checked in a
1085 case-insensitive manner. Any other value will cause it to raise
1086 :exc:`ValueError`. See :meth:`get` for explanation of *raw*, *vars* and
1087 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001088
1089
Ezio Melottie0add762012-09-14 06:32:35 +03001090 .. method:: items(raw=False, vars=None)
1091 items(section, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001092
Łukasz Langa71b37a52010-12-17 21:56:32 +00001093 When *section* is not given, return a list of *section_name*,
1094 *section_proxy* pairs, including DEFAULTSECT.
1095
1096 Otherwise, return a list of *name*, *value* pairs for the options in the
1097 given *section*. Optional arguments have the same meaning as for the
Georg Brandlbb27c122010-11-11 07:26:40 +00001098 :meth:`get` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001099
Łukasz Langa72547622011-05-09 18:49:42 +02001100 .. versionchanged:: 3.2
Łukasz Langa34cea142014-09-14 23:37:03 -07001101 Items present in *vars* no longer appear in the result. The previous
Łukasz Langa72547622011-05-09 18:49:42 +02001102 behaviour mixed actual parser options with variables provided for
1103 interpolation.
Georg Brandl116aa622007-08-15 14:28:22 +00001104
Georg Brandlbb27c122010-11-11 07:26:40 +00001105 .. method:: set(section, option, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001106
Georg Brandlbb27c122010-11-11 07:26:40 +00001107 If the given section exists, set the given option to the specified value;
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001108 otherwise raise :exc:`NoSectionError`. *option* and *value* must be
1109 strings; if not, :exc:`TypeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001110
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001111
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001112 .. method:: write(fileobject, space_around_delimiters=True)
1113
1114 Write a representation of the configuration to the specified :term:`file
1115 object`, which must be opened in text mode (accepting strings). This
1116 representation can be parsed by a future :meth:`read` call. If
1117 *space_around_delimiters* is true, delimiters between
1118 keys and values are surrounded by spaces.
1119
1120
1121 .. method:: remove_option(section, option)
1122
1123 Remove the specified *option* from the specified *section*. If the
1124 section does not exist, raise :exc:`NoSectionError`. If the option
1125 existed to be removed, return :const:`True`; otherwise return
1126 :const:`False`.
1127
1128
1129 .. method:: remove_section(section)
1130
1131 Remove the specified *section* from the configuration. If the section in
1132 fact existed, return ``True``. Otherwise return ``False``.
1133
1134
1135 .. method:: optionxform(option)
1136
1137 Transforms the option name *option* as found in an input file or as passed
1138 in by client code to the form that should be used in the internal
1139 structures. The default implementation returns a lower-case version of
1140 *option*; subclasses may override this or client code can set an attribute
1141 of this name on instances to affect this behavior.
1142
1143 You don't need to subclass the parser to use this method, you can also
1144 set it on an instance, to a function that takes a string argument and
1145 returns a string. Setting it to ``str``, for example, would make option
1146 names case sensitive::
1147
1148 cfgparser = ConfigParser()
1149 cfgparser.optionxform = str
1150
1151 Note that when reading configuration files, whitespace around the option
1152 names is stripped before :meth:`optionxform` is called.
1153
1154
1155 .. method:: readfp(fp, filename=None)
1156
1157 .. deprecated:: 3.2
1158 Use :meth:`read_file` instead.
1159
Łukasz Langaba702da2011-04-28 12:02:05 +02001160 .. versionchanged:: 3.2
1161 :meth:`readfp` now iterates on *f* instead of calling ``f.readline()``.
1162
1163 For existing code calling :meth:`readfp` with arguments which don't
1164 support iteration, the following generator may be used as a wrapper
1165 around the file-like object::
1166
1167 def readline_generator(f):
1168 line = f.readline()
1169 while line:
1170 yield line
1171 line = f.readline()
1172
1173 Instead of ``parser.readfp(f)`` use
1174 ``parser.read_file(readline_generator(f))``.
1175
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001176
1177.. data:: MAX_INTERPOLATION_DEPTH
1178
1179 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
1180 parameter is false. This is relevant only when the default *interpolation*
1181 is used.
1182
1183
1184.. _rawconfigparser-objects:
1185
1186RawConfigParser Objects
1187-----------------------
1188
Ezio Melottie927e252012-09-08 20:46:01 +03001189.. class:: RawConfigParser(defaults=None, dict_type=collections.OrderedDict, \
1190 allow_no_value=False, *, delimiters=('=', ':'), \
1191 comment_prefixes=('#', ';'), \
1192 inline_comment_prefixes=None, strict=True, \
1193 empty_lines_in_values=True, \
1194 default_section=configparser.DEFAULTSECT[, \
1195 interpolation])
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001196
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001197 Legacy variant of the :class:`ConfigParser` with interpolation disabled
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001198 by default and unsafe ``add_section`` and ``set`` methods.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001199
1200 .. note::
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001201 Consider using :class:`ConfigParser` instead which checks types of
Łukasz Langa34cea142014-09-14 23:37:03 -07001202 the values to be stored internally. If you don't want interpolation, you
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001203 can use ``ConfigParser(interpolation=None)``.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001204
1205
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001206 .. method:: add_section(section)
1207
1208 Add a section named *section* to the instance. If a section by the given
1209 name already exists, :exc:`DuplicateSectionError` is raised. If the
1210 *default section* name is passed, :exc:`ValueError` is raised.
1211
1212 Type of *section* is not checked which lets users create non-string named
Łukasz Langa34cea142014-09-14 23:37:03 -07001213 sections. This behaviour is unsupported and may cause internal errors.
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001214
1215
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001216 .. method:: set(section, option, value)
1217
1218 If the given section exists, set the given option to the specified value;
1219 otherwise raise :exc:`NoSectionError`. While it is possible to use
1220 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters
1221 set to true) for *internal* storage of non-string values, full
1222 functionality (including interpolation and output to files) can only be
1223 achieved using string values.
1224
1225 This method lets users assign non-string values to keys internally. This
1226 behaviour is unsupported and will cause errors when attempting to write
1227 to a file or get it in non-raw mode. **Use the mapping protocol API**
1228 which does not allow such assignments to take place.
1229
1230
Łukasz Langa26d513c2010-11-10 18:57:39 +00001231Exceptions
1232----------
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001233
Łukasz Langa26d513c2010-11-10 18:57:39 +00001234.. exception:: Error
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001235
Fred Drake5a7c11f2010-11-13 05:24:17 +00001236 Base class for all other :mod:`configparser` exceptions.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001237
Georg Brandl48310cd2009-01-03 21:18:54 +00001238
Łukasz Langa26d513c2010-11-10 18:57:39 +00001239.. exception:: NoSectionError
Georg Brandl48310cd2009-01-03 21:18:54 +00001240
Łukasz Langa26d513c2010-11-10 18:57:39 +00001241 Exception raised when a specified section is not found.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001242
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001243
Łukasz Langa26d513c2010-11-10 18:57:39 +00001244.. exception:: DuplicateSectionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001245
Łukasz Langa26d513c2010-11-10 18:57:39 +00001246 Exception raised if :meth:`add_section` is called with the name of a section
1247 that is already present or in strict parsers when a section if found more
1248 than once in a single input file, string or dictionary.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001249
Łukasz Langa26d513c2010-11-10 18:57:39 +00001250 .. versionadded:: 3.2
1251 Optional ``source`` and ``lineno`` attributes and arguments to
1252 :meth:`__init__` were added.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001253
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001254
Łukasz Langa26d513c2010-11-10 18:57:39 +00001255.. exception:: DuplicateOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001256
Łukasz Langa26d513c2010-11-10 18:57:39 +00001257 Exception raised by strict parsers if a single option appears twice during
1258 reading from a single file, string or dictionary. This catches misspellings
1259 and case sensitivity-related errors, e.g. a dictionary may have two keys
1260 representing the same case-insensitive configuration key.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001261
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001262
Łukasz Langa26d513c2010-11-10 18:57:39 +00001263.. exception:: NoOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001264
Łukasz Langa26d513c2010-11-10 18:57:39 +00001265 Exception raised when a specified option is not found in the specified
1266 section.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001267
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001268
Łukasz Langa26d513c2010-11-10 18:57:39 +00001269.. exception:: InterpolationError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001270
Łukasz Langa26d513c2010-11-10 18:57:39 +00001271 Base class for exceptions raised when problems occur performing string
1272 interpolation.
Georg Brandl48310cd2009-01-03 21:18:54 +00001273
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001274
Łukasz Langa26d513c2010-11-10 18:57:39 +00001275.. exception:: InterpolationDepthError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001276
Łukasz Langa26d513c2010-11-10 18:57:39 +00001277 Exception raised when string interpolation cannot be completed because the
Georg Brandlbb27c122010-11-11 07:26:40 +00001278 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
Łukasz Langa26d513c2010-11-10 18:57:39 +00001279 :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001280
Fred Drake03c44a32010-02-19 06:08:41 +00001281
Łukasz Langa26d513c2010-11-10 18:57:39 +00001282.. exception:: InterpolationMissingOptionError
Fred Drake03c44a32010-02-19 06:08:41 +00001283
Georg Brandlbb27c122010-11-11 07:26:40 +00001284 Exception raised when an option referenced from a value does not exist.
1285 Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001286
Fred Drake03c44a32010-02-19 06:08:41 +00001287
Łukasz Langa26d513c2010-11-10 18:57:39 +00001288.. exception:: InterpolationSyntaxError
Fred Drake03c44a32010-02-19 06:08:41 +00001289
Georg Brandlbb27c122010-11-11 07:26:40 +00001290 Exception raised when the source text into which substitutions are made does
1291 not conform to the required syntax. Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001292
Łukasz Langa26d513c2010-11-10 18:57:39 +00001293
1294.. exception:: MissingSectionHeaderError
1295
Georg Brandlbb27c122010-11-11 07:26:40 +00001296 Exception raised when attempting to parse a file which has no section
1297 headers.
Łukasz Langa26d513c2010-11-10 18:57:39 +00001298
1299
1300.. exception:: ParsingError
1301
1302 Exception raised when errors occur attempting to parse a file.
1303
1304 .. versionchanged:: 3.2
1305 The ``filename`` attribute and :meth:`__init__` argument were renamed to
1306 ``source`` for consistency.
1307
Georg Brandlbb27c122010-11-11 07:26:40 +00001308
1309.. rubric:: Footnotes
1310
1311.. [1] Config parsers allow for heavy customization. If you are interested in
1312 changing the behaviour outlined by the footnote reference, consult the
1313 `Customizing Parser Behaviour`_ section.
Łukasz Langadfdd2f72014-09-15 02:08:41 -07001314