blob: 8d141a2af7a2649e48e28e5efa74819a2d02eb8e [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
Martin Pantereb995702016-07-28 01:11:04 +000069creating the above configuration file programmatically.
Łukasz Langa26d513c2010-11-10 18:57:39 +000070
Ł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
Jesus Cea647680e2016-09-20 00:01:53 +0200153provide :meth:`~ConfigParser.getboolean`. This method is case-insensitive and
154recognizes Boolean values from ``'yes'``/``'no'``, ``'on'``/``'off'``,
Łukasz Langa34cea142014-09-14 23:37:03 -0700155``'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
Jesus Cea647680e2016-09-20 00:01:53 +0200166Apart from :meth:`~ConfigParser.getboolean`, config parsers also
167provide equivalent :meth:`~ConfigParser.getint` and
168:meth:`~ConfigParser.getfloat` methods. You can register your own
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700169converters and customize the provided ones. [1]_
Georg Brandlbb27c122010-11-11 07:26:40 +0000170
Łukasz Langa26d513c2010-11-10 18:57:39 +0000171Fallback Values
172---------------
173
Fred Drake5a7c11f2010-11-13 05:24:17 +0000174As with a dictionary, you can use a section's :meth:`get` method to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000175provide fallback values:
176
Łukasz Langa26d513c2010-11-10 18:57:39 +0000177.. doctest::
178
Georg Brandlbb27c122010-11-11 07:26:40 +0000179 >>> topsecret.get('Port')
180 '50022'
181 >>> topsecret.get('CompressionLevel')
182 '9'
183 >>> topsecret.get('Cipher')
184 >>> topsecret.get('Cipher', '3des-cbc')
185 '3des-cbc'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000186
Fred Drake5a7c11f2010-11-13 05:24:17 +0000187Please note that default values have precedence over fallback values.
188For instance, in our example the ``'CompressionLevel'`` key was
189specified only in the ``'DEFAULT'`` section. If we try to get it from
190the section ``'topsecret.server.com'``, we will always get the default,
191even if we specify a fallback:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000192
Łukasz Langa26d513c2010-11-10 18:57:39 +0000193.. doctest::
194
Georg Brandlbb27c122010-11-11 07:26:40 +0000195 >>> topsecret.get('CompressionLevel', '3')
196 '9'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000197
198One more thing to be aware of is that the parser-level :meth:`get` method
199provides a custom, more complex interface, maintained for backwards
Fred Drake5a7c11f2010-11-13 05:24:17 +0000200compatibility. When using this method, a fallback value can be provided via
201the ``fallback`` keyword-only argument:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000202
Łukasz Langa26d513c2010-11-10 18:57:39 +0000203.. doctest::
204
Georg Brandlbb27c122010-11-11 07:26:40 +0000205 >>> config.get('bitbucket.org', 'monster',
206 ... fallback='No such things as monsters')
207 'No such things as monsters'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000208
Jesus Cea647680e2016-09-20 00:01:53 +0200209The same ``fallback`` argument can be used with the
210:meth:`~ConfigParser.getint`, :meth:`~ConfigParser.getfloat` and
211:meth:`~ConfigParser.getboolean` methods, for example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000212
Łukasz Langa26d513c2010-11-10 18:57:39 +0000213.. doctest::
214
Georg Brandlbb27c122010-11-11 07:26:40 +0000215 >>> 'BatchMode' in topsecret
216 False
217 >>> topsecret.getboolean('BatchMode', fallback=True)
218 True
219 >>> config['DEFAULT']['BatchMode'] = 'no'
220 >>> topsecret.getboolean('BatchMode', fallback=True)
221 False
222
Łukasz Langa26d513c2010-11-10 18:57:39 +0000223
224Supported INI File Structure
225----------------------------
226
Georg Brandl96a60ae2010-07-28 13:13:46 +0000227A configuration file consists of sections, each led by a ``[section]`` header,
Fred Drakea4923622010-08-09 12:52:45 +0000228followed by key/value entries separated by a specific string (``=`` or ``:`` by
Georg Brandlbb27c122010-11-11 07:26:40 +0000229default [1]_). By default, section names are case sensitive but keys are not
Fred Drake5a7c11f2010-11-13 05:24:17 +0000230[1]_. Leading and trailing whitespace is removed from keys and values.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000231Values can be omitted, in which case the key/value delimiter may also be left
232out. Values can also span multiple lines, as long as they are indented deeper
233than the first line of the value. Depending on the parser's mode, blank lines
234may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000235
Fred Drake5a7c11f2010-11-13 05:24:17 +0000236Configuration files may include comments, prefixed by specific
237characters (``#`` and ``;`` by default [1]_). Comments may appear on
Łukasz Langab25a7912010-12-17 01:32:29 +0000238their own on an otherwise empty line, possibly indented. [1]_
Georg Brandl96a60ae2010-07-28 13:13:46 +0000239
Georg Brandlbb27c122010-11-11 07:26:40 +0000240For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000241
Georg Brandlbb27c122010-11-11 07:26:40 +0000242.. code-block:: ini
Georg Brandl116aa622007-08-15 14:28:22 +0000243
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000244 [Simple Values]
Łukasz Langab25a7912010-12-17 01:32:29 +0000245 key=value
246 spaces in keys=allowed
247 spaces in values=allowed as well
248 spaces around the delimiter = obviously
249 you can also use : to delimit keys from values
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000250
251 [All Values Are Strings]
252 values like this: 1000000
253 or this: 3.14159265359
254 are they treated as numbers? : no
255 integers, floats and booleans are held as: strings
256 can use the API to get converted values directly: true
Georg Brandl116aa622007-08-15 14:28:22 +0000257
Georg Brandl96a60ae2010-07-28 13:13:46 +0000258 [Multiline Values]
259 chorus: I'm a lumberjack, and I'm okay
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000260 I sleep all night and I work all day
Georg Brandl116aa622007-08-15 14:28:22 +0000261
Georg Brandl96a60ae2010-07-28 13:13:46 +0000262 [No Values]
263 key_without_value
264 empty string value here =
Georg Brandl116aa622007-08-15 14:28:22 +0000265
Łukasz Langab25a7912010-12-17 01:32:29 +0000266 [You can use comments]
267 # like this
268 ; or this
269
270 # By default only in an empty line.
271 # Inline comments can be harmful because they prevent users
272 # from using the delimiting characters as parts of values.
273 # That being said, this can be customized.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000274
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000275 [Sections Can Be Indented]
276 can_values_be_as_well = True
277 does_that_mean_anything_special = False
278 purpose = formatting for readability
279 multiline_values = are
280 handled just fine as
281 long as they are indented
282 deeper than the first line
283 of a value
284 # Did I mention we can indent comments, too?
Georg Brandl116aa622007-08-15 14:28:22 +0000285
Georg Brandl96a60ae2010-07-28 13:13:46 +0000286
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000287Interpolation of values
288-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000289
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000290On top of the core functionality, :class:`ConfigParser` supports
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000291interpolation. This means values can be preprocessed before returning them
292from ``get()`` calls.
293
294.. class:: BasicInterpolation()
295
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000296 The default implementation used by :class:`ConfigParser`. It enables
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000297 values to contain format strings which refer to other values in the same
298 section, or values in the special default section [1]_. Additional default
299 values can be provided on initialization.
300
301 For example:
302
303 .. code-block:: ini
304
305 [Paths]
306 home_dir: /Users
307 my_dir: %(home_dir)s/lumberjack
308 my_pictures: %(my_dir)s/Pictures
309
310
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000311 In the example above, :class:`ConfigParser` with *interpolation* set to
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000312 ``BasicInterpolation()`` would resolve ``%(home_dir)s`` to the value of
313 ``home_dir`` (``/Users`` in this case). ``%(my_dir)s`` in effect would
314 resolve to ``/Users/lumberjack``. All interpolations are done on demand so
315 keys used in the chain of references do not have to be specified in any
316 specific order in the configuration file.
317
318 With ``interpolation`` set to ``None``, the parser would simply return
319 ``%(my_dir)s/Pictures`` as the value of ``my_pictures`` and
320 ``%(home_dir)s/lumberjack`` as the value of ``my_dir``.
321
322.. class:: ExtendedInterpolation()
323
324 An alternative handler for interpolation which implements a more advanced
Łukasz Langa34cea142014-09-14 23:37:03 -0700325 syntax, used for instance in ``zc.buildout``. Extended interpolation is
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000326 using ``${section:option}`` to denote a value from a foreign section.
Łukasz Langa34cea142014-09-14 23:37:03 -0700327 Interpolation can span multiple levels. For convenience, if the
328 ``section:`` part is omitted, interpolation defaults to the current section
329 (and possibly the default values from the special section).
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000330
331 For example, the configuration specified above with basic interpolation,
332 would look like this with extended interpolation:
333
334 .. code-block:: ini
335
336 [Paths]
337 home_dir: /Users
338 my_dir: ${home_dir}/lumberjack
339 my_pictures: ${my_dir}/Pictures
340
341 Values from other sections can be fetched as well:
342
343 .. code-block:: ini
344
345 [Common]
346 home_dir: /Users
347 library_dir: /Library
348 system_dir: /System
349 macports_dir: /opt/local
350
351 [Frameworks]
352 Python: 3.2
353 path: ${Common:system_dir}/Library/Frameworks/
354
355 [Arthur]
356 nickname: Two Sheds
357 last_name: Jackson
358 my_dir: ${Common:home_dir}/twosheds
359 my_pictures: ${my_dir}/Pictures
360 python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
Georg Brandlbb27c122010-11-11 07:26:40 +0000361
Łukasz Langa26d513c2010-11-10 18:57:39 +0000362Mapping Protocol Access
363-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000364
Łukasz Langa26d513c2010-11-10 18:57:39 +0000365.. versionadded:: 3.2
Georg Brandl96a60ae2010-07-28 13:13:46 +0000366
Łukasz Langa26d513c2010-11-10 18:57:39 +0000367Mapping protocol access is a generic name for functionality that enables using
Georg Brandlbb27c122010-11-11 07:26:40 +0000368custom objects as if they were dictionaries. In case of :mod:`configparser`,
Łukasz Langa26d513c2010-11-10 18:57:39 +0000369the mapping interface implementation is using the
370``parser['section']['option']`` notation.
371
372``parser['section']`` in particular returns a proxy for the section's data in
Georg Brandlbb27c122010-11-11 07:26:40 +0000373the parser. This means that the values are not copied but they are taken from
374the original parser on demand. What's even more important is that when values
Łukasz Langa26d513c2010-11-10 18:57:39 +0000375are changed on a section proxy, they are actually mutated in the original
376parser.
377
378:mod:`configparser` objects behave as close to actual dictionaries as possible.
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300379The mapping interface is complete and adheres to the
380:class:`~collections.abc.MutableMapping` ABC.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000381However, there are a few differences that should be taken into account:
382
Georg Brandlbb27c122010-11-11 07:26:40 +0000383* By default, all keys in sections are accessible in a case-insensitive manner
384 [1]_. E.g. ``for option in parser["section"]`` yields only ``optionxform``'ed
385 option key names. This means lowercased keys by default. At the same time,
Fred Drake5a7c11f2010-11-13 05:24:17 +0000386 for a section that holds the key ``'a'``, both expressions return ``True``::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000387
Georg Brandlbb27c122010-11-11 07:26:40 +0000388 "a" in parser["section"]
389 "A" in parser["section"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000390
Georg Brandlbb27c122010-11-11 07:26:40 +0000391* All sections include ``DEFAULTSECT`` values as well which means that
392 ``.clear()`` on a section may not leave the section visibly empty. This is
Łukasz Langa26d513c2010-11-10 18:57:39 +0000393 because default values cannot be deleted from the section (because technically
Donald Stufft8b852f12014-05-20 12:58:38 -0400394 they are not there). If they are overridden in the section, deleting causes
Georg Brandlbb27c122010-11-11 07:26:40 +0000395 the default value to be visible again. Trying to delete a default value
396 causes a ``KeyError``.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000397
Łukasz Langa3a8479a2012-12-31 03:38:39 +0100398* ``DEFAULTSECT`` cannot be removed from the parser:
399
400 * trying to delete it raises ``ValueError``,
401
402 * ``parser.clear()`` leaves it intact,
403
404 * ``parser.popitem()`` never returns it.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000405
Łukasz Langa71b37a52010-12-17 21:56:32 +0000406* ``parser.get(section, option, **kwargs)`` - the second argument is **not**
Łukasz Langa34cea142014-09-14 23:37:03 -0700407 a fallback value. Note however that the section-level ``get()`` methods are
Łukasz Langa71b37a52010-12-17 21:56:32 +0000408 compatible both with the mapping protocol and the classic configparser API.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000409
Łukasz Langa71b37a52010-12-17 21:56:32 +0000410* ``parser.items()`` is compatible with the mapping protocol (returns a list of
411 *section_name*, *section_proxy* pairs including the DEFAULTSECT). However,
412 this method can also be invoked with arguments: ``parser.items(section, raw,
Łukasz Langa34cea142014-09-14 23:37:03 -0700413 vars)``. The latter call returns a list of *option*, *value* pairs for
Łukasz Langa71b37a52010-12-17 21:56:32 +0000414 a specified ``section``, with all interpolations expanded (unless
415 ``raw=True`` is provided).
Łukasz Langa26d513c2010-11-10 18:57:39 +0000416
417The mapping protocol is implemented on top of the existing legacy API so that
Łukasz Langa71b37a52010-12-17 21:56:32 +0000418subclasses overriding the original interface still should have mappings working
419as expected.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000420
Georg Brandlbb27c122010-11-11 07:26:40 +0000421
Łukasz Langa26d513c2010-11-10 18:57:39 +0000422Customizing Parser Behaviour
423----------------------------
424
425There are nearly as many INI format variants as there are applications using it.
426:mod:`configparser` goes a long way to provide support for the largest sensible
Georg Brandlbb27c122010-11-11 07:26:40 +0000427set of INI styles available. The default functionality is mainly dictated by
Łukasz Langa26d513c2010-11-10 18:57:39 +0000428historical background and it's very likely that you will want to customize some
429of the features.
430
Fred Drake5a7c11f2010-11-13 05:24:17 +0000431The most common way to change the way a specific config parser works is to use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000432the :meth:`__init__` options:
433
434* *defaults*, default value: ``None``
435
436 This option accepts a dictionary of key-value pairs which will be initially
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000437 put in the ``DEFAULT`` section. This makes for an elegant way to support
438 concise configuration files that don't specify values which are the same as
439 the documented default.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000440
Fred Drake5a7c11f2010-11-13 05:24:17 +0000441 Hint: if you want to specify default values for a specific section, use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000442 :meth:`read_dict` before you read the actual file.
443
444* *dict_type*, default value: :class:`collections.OrderedDict`
445
446 This option has a major impact on how the mapping protocol will behave and how
Fred Drake5a7c11f2010-11-13 05:24:17 +0000447 the written configuration files look. With the default ordered
Łukasz Langa26d513c2010-11-10 18:57:39 +0000448 dictionary, every section is stored in the order they were added to the
Georg Brandlbb27c122010-11-11 07:26:40 +0000449 parser. Same goes for options within sections.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000450
451 An alternative dictionary type can be used for example to sort sections and
Georg Brandlbb27c122010-11-11 07:26:40 +0000452 options on write-back. You can also use a regular dictionary for performance
Łukasz Langa26d513c2010-11-10 18:57:39 +0000453 reasons.
454
455 Please note: there are ways to add a set of key-value pairs in a single
Georg Brandlbb27c122010-11-11 07:26:40 +0000456 operation. When you use a regular dictionary in those operations, the order
457 of the keys may be random. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000458
Łukasz Langa26d513c2010-11-10 18:57:39 +0000459 .. doctest::
460
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000461 >>> parser = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000462 >>> parser.read_dict({'section1': {'key1': 'value1',
463 ... 'key2': 'value2',
464 ... 'key3': 'value3'},
465 ... 'section2': {'keyA': 'valueA',
466 ... 'keyB': 'valueB',
467 ... 'keyC': 'valueC'},
468 ... 'section3': {'foo': 'x',
469 ... 'bar': 'y',
470 ... 'baz': 'z'}
471 ... })
472 >>> parser.sections()
473 ['section3', 'section2', 'section1']
474 >>> [option for option in parser['section3']]
475 ['baz', 'foo', 'bar']
Łukasz Langa26d513c2010-11-10 18:57:39 +0000476
477 In these operations you need to use an ordered dictionary as well:
478
Łukasz Langa26d513c2010-11-10 18:57:39 +0000479 .. doctest::
480
Georg Brandlbb27c122010-11-11 07:26:40 +0000481 >>> from collections import OrderedDict
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000482 >>> parser = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000483 >>> parser.read_dict(
484 ... OrderedDict((
485 ... ('s1',
486 ... OrderedDict((
487 ... ('1', '2'),
488 ... ('3', '4'),
489 ... ('5', '6'),
490 ... ))
491 ... ),
492 ... ('s2',
493 ... OrderedDict((
494 ... ('a', 'b'),
495 ... ('c', 'd'),
496 ... ('e', 'f'),
497 ... ))
498 ... ),
499 ... ))
500 ... )
501 >>> parser.sections()
502 ['s1', 's2']
503 >>> [option for option in parser['s1']]
504 ['1', '3', '5']
505 >>> [option for option in parser['s2'].values()]
506 ['b', 'd', 'f']
Łukasz Langa26d513c2010-11-10 18:57:39 +0000507
508* *allow_no_value*, default value: ``False``
509
510 Some configuration files are known to include settings without values, but
511 which otherwise conform to the syntax supported by :mod:`configparser`. The
Fred Drake5a7c11f2010-11-13 05:24:17 +0000512 *allow_no_value* parameter to the constructor can be used to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000513 indicate that such values should be accepted:
514
Łukasz Langa26d513c2010-11-10 18:57:39 +0000515 .. doctest::
516
Georg Brandlbb27c122010-11-11 07:26:40 +0000517 >>> import configparser
Łukasz Langa26d513c2010-11-10 18:57:39 +0000518
Georg Brandlbb27c122010-11-11 07:26:40 +0000519 >>> sample_config = """
520 ... [mysqld]
521 ... user = mysql
522 ... pid-file = /var/run/mysqld/mysqld.pid
523 ... skip-external-locking
524 ... old_passwords = 1
525 ... skip-bdb
Łukasz Langab25a7912010-12-17 01:32:29 +0000526 ... # we don't need ACID today
527 ... skip-innodb
Georg Brandlbb27c122010-11-11 07:26:40 +0000528 ... """
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000529 >>> config = configparser.ConfigParser(allow_no_value=True)
Georg Brandlbb27c122010-11-11 07:26:40 +0000530 >>> config.read_string(sample_config)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000531
Georg Brandlbb27c122010-11-11 07:26:40 +0000532 >>> # Settings with values are treated as before:
533 >>> config["mysqld"]["user"]
534 'mysql'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000535
Georg Brandlbb27c122010-11-11 07:26:40 +0000536 >>> # Settings without values provide None:
537 >>> config["mysqld"]["skip-bdb"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000538
Georg Brandlbb27c122010-11-11 07:26:40 +0000539 >>> # Settings which aren't specified still raise an error:
540 >>> config["mysqld"]["does-not-exist"]
541 Traceback (most recent call last):
542 ...
543 KeyError: 'does-not-exist'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000544
545* *delimiters*, default value: ``('=', ':')``
546
Łukasz Langa34cea142014-09-14 23:37:03 -0700547 Delimiters are substrings that delimit keys from values within a section.
548 The first occurrence of a delimiting substring on a line is considered
549 a delimiter. This means values (but not keys) can contain the delimiters.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000550
551 See also the *space_around_delimiters* argument to
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000552 :meth:`ConfigParser.write`.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000553
Łukasz Langab25a7912010-12-17 01:32:29 +0000554* *comment_prefixes*, default value: ``('#', ';')``
Łukasz Langa26d513c2010-11-10 18:57:39 +0000555
Łukasz Langab25a7912010-12-17 01:32:29 +0000556* *inline_comment_prefixes*, default value: ``None``
557
558 Comment prefixes are strings that indicate the start of a valid comment within
559 a config file. *comment_prefixes* are used only on otherwise empty lines
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700560 (optionally indented) whereas *inline_comment_prefixes* can be used after
561 every valid value (e.g. section names, options and empty lines as well). By
562 default inline comments are disabled and ``'#'`` and ``';'`` are used as
563 prefixes for whole line comments.
Łukasz Langab25a7912010-12-17 01:32:29 +0000564
565 .. versionchanged:: 3.2
566 In previous versions of :mod:`configparser` behaviour matched
567 ``comment_prefixes=('#',';')`` and ``inline_comment_prefixes=(';',)``.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000568
569 Please note that config parsers don't support escaping of comment prefixes so
Łukasz Langab25a7912010-12-17 01:32:29 +0000570 using *inline_comment_prefixes* may prevent users from specifying option
Łukasz Langa34cea142014-09-14 23:37:03 -0700571 values with characters used as comment prefixes. When in doubt, avoid
572 setting *inline_comment_prefixes*. In any circumstances, the only way of
573 storing comment prefix characters at the beginning of a line in multiline
574 values is to interpolate the prefix, for example::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000575
Łukasz Langab25a7912010-12-17 01:32:29 +0000576 >>> from configparser import ConfigParser, ExtendedInterpolation
577 >>> parser = ConfigParser(interpolation=ExtendedInterpolation())
578 >>> # the default BasicInterpolation could be used as well
579 >>> parser.read_string("""
580 ... [DEFAULT]
581 ... hash = #
582 ...
583 ... [hashes]
584 ... shebang =
585 ... ${hash}!/usr/bin/env python
586 ... ${hash} -*- coding: utf-8 -*-
587 ...
588 ... extensions =
589 ... enabled_extension
590 ... another_extension
591 ... #disabled_by_comment
592 ... yet_another_extension
593 ...
594 ... interpolation not necessary = if # is not at line start
595 ... even in multiline values = line #1
596 ... line #2
597 ... line #3
598 ... """)
599 >>> print(parser['hashes']['shebang'])
Łukasz Langa26d513c2010-11-10 18:57:39 +0000600
Łukasz Langab25a7912010-12-17 01:32:29 +0000601 #!/usr/bin/env python
602 # -*- coding: utf-8 -*-
603 >>> print(parser['hashes']['extensions'])
604
605 enabled_extension
606 another_extension
607 yet_another_extension
608 >>> print(parser['hashes']['interpolation not necessary'])
609 if # is not at line start
610 >>> print(parser['hashes']['even in multiline values'])
611 line #1
612 line #2
613 line #3
614
615* *strict*, default value: ``True``
616
617 When set to ``True``, the parser will not allow for any section or option
Łukasz Langa26d513c2010-11-10 18:57:39 +0000618 duplicates while reading from a single source (using :meth:`read_file`,
Łukasz Langa34cea142014-09-14 23:37:03 -0700619 :meth:`read_string` or :meth:`read_dict`). It is recommended to use strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000620 parsers in new applications.
621
Łukasz Langab25a7912010-12-17 01:32:29 +0000622 .. versionchanged:: 3.2
623 In previous versions of :mod:`configparser` behaviour matched
624 ``strict=False``.
625
Łukasz Langa26d513c2010-11-10 18:57:39 +0000626* *empty_lines_in_values*, default value: ``True``
627
Fred Drake5a7c11f2010-11-13 05:24:17 +0000628 In config parsers, values can span multiple lines as long as they are
629 indented more than the key that holds them. By default parsers also let
630 empty lines to be parts of values. At the same time, keys can be arbitrarily
631 indented themselves to improve readability. In consequence, when
632 configuration files get big and complex, it is easy for the user to lose
633 track of the file structure. Take for instance:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000634
Georg Brandlbb27c122010-11-11 07:26:40 +0000635 .. code-block:: ini
Łukasz Langa26d513c2010-11-10 18:57:39 +0000636
Georg Brandlbb27c122010-11-11 07:26:40 +0000637 [Section]
638 key = multiline
639 value with a gotcha
Łukasz Langa26d513c2010-11-10 18:57:39 +0000640
Georg Brandlbb27c122010-11-11 07:26:40 +0000641 this = is still a part of the multiline value of 'key'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000642
Georg Brandlbb27c122010-11-11 07:26:40 +0000643 This can be especially problematic for the user to see if she's using a
644 proportional font to edit the file. That is why when your application does
645 not need values with empty lines, you should consider disallowing them. This
646 will make empty lines split keys every time. In the example above, it would
Łukasz Langa26d513c2010-11-10 18:57:39 +0000647 produce two keys, ``key`` and ``this``.
648
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000649* *default_section*, default value: ``configparser.DEFAULTSECT`` (that is:
650 ``"DEFAULT"``)
651
652 The convention of allowing a special section of default values for other
653 sections or interpolation purposes is a powerful concept of this library,
Łukasz Langa34cea142014-09-14 23:37:03 -0700654 letting users create complex declarative configurations. This section is
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000655 normally called ``"DEFAULT"`` but this can be customized to point to any
Łukasz Langa34cea142014-09-14 23:37:03 -0700656 other valid section name. Some typical values include: ``"general"`` or
657 ``"common"``. The name provided is used for recognizing default sections
658 when reading from any source and is used when writing configuration back to
659 a file. Its current value can be retrieved using the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000660 ``parser_instance.default_section`` attribute and may be modified at runtime
661 (i.e. to convert files from one format to another).
662
663* *interpolation*, default value: ``configparser.BasicInterpolation``
664
665 Interpolation behaviour may be customized by providing a custom handler
666 through the *interpolation* argument. ``None`` can be used to turn off
667 interpolation completely, ``ExtendedInterpolation()`` provides a more
Łukasz Langa34cea142014-09-14 23:37:03 -0700668 advanced variant inspired by ``zc.buildout``. More on the subject in the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000669 `dedicated documentation section <#interpolation-of-values>`_.
Łukasz Langab25a7912010-12-17 01:32:29 +0000670 :class:`RawConfigParser` has a default value of ``None``.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000671
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700672* *converters*, default value: not set
673
674 Config parsers provide option value getters that perform type conversion. By
Jesus Cea647680e2016-09-20 00:01:53 +0200675 default :meth:`~ConfigParser.getint`, :meth:`~ConfigParser.getfloat`, and
676 :meth:`~ConfigParser.getboolean` are implemented. Should other getters be
677 desirable, users may define them in a subclass or pass a dictionary where each
678 key is a name of the converter and each value is a callable implementing said
679 conversion. For instance, passing ``{'decimal': decimal.Decimal}`` would add
680 :meth:`getdecimal` on both the parser object and all section proxies. In
681 other words, it will be possible to write both
682 ``parser_instance.getdecimal('section', 'key', fallback=0)`` and
683 ``parser_instance['section'].getdecimal('key', 0)``.
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700684
685 If the converter needs to access the state of the parser, it can be
686 implemented as a method on a config parser subclass. If the name of this
687 method starts with ``get``, it will be available on all section proxies, in
688 the dict-compatible form (see the ``getdecimal()`` example above).
Łukasz Langa26d513c2010-11-10 18:57:39 +0000689
Fred Drake5a7c11f2010-11-13 05:24:17 +0000690More advanced customization may be achieved by overriding default values of
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700691these parser attributes. The defaults are defined on the classes, so they may
692be overridden by subclasses or by attribute assignment.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000693
Fred Drake5a7c11f2010-11-13 05:24:17 +0000694.. attribute:: BOOLEAN_STATES
Łukasz Langa26d513c2010-11-10 18:57:39 +0000695
Jesus Cea647680e2016-09-20 00:01:53 +0200696 By default when using :meth:`~ConfigParser.getboolean`, config parsers
697 consider the following values ``True``: ``'1'``, ``'yes'``, ``'true'``,
698 ``'on'`` and the following values ``False``: ``'0'``, ``'no'``, ``'false'``,
699 ``'off'``. You can override this by specifying a custom dictionary of strings
700 and their Boolean outcomes. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000701
Łukasz Langa26d513c2010-11-10 18:57:39 +0000702 .. doctest::
703
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000704 >>> custom = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000705 >>> custom['section1'] = {'funky': 'nope'}
706 >>> custom['section1'].getboolean('funky')
707 Traceback (most recent call last):
708 ...
709 ValueError: Not a boolean: nope
710 >>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}
711 >>> custom['section1'].getboolean('funky')
712 False
Łukasz Langa26d513c2010-11-10 18:57:39 +0000713
Fred Drake5a7c11f2010-11-13 05:24:17 +0000714 Other typical Boolean pairs include ``accept``/``reject`` or
Łukasz Langa26d513c2010-11-10 18:57:39 +0000715 ``enabled``/``disabled``.
716
Fred Drake5a7c11f2010-11-13 05:24:17 +0000717.. method:: optionxform(option)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000718
Fred Drake5a7c11f2010-11-13 05:24:17 +0000719 This method transforms option names on every read, get, or set
720 operation. The default converts the name to lowercase. This also
721 means that when a configuration file gets written, all keys will be
722 lowercase. Override this method if that's unsuitable.
723 For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000724
Łukasz Langa26d513c2010-11-10 18:57:39 +0000725 .. doctest::
726
Georg Brandlbb27c122010-11-11 07:26:40 +0000727 >>> config = """
728 ... [Section1]
729 ... Key = Value
730 ...
731 ... [Section2]
732 ... AnotherKey = Value
733 ... """
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000734 >>> typical = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000735 >>> typical.read_string(config)
736 >>> list(typical['Section1'].keys())
737 ['key']
738 >>> list(typical['Section2'].keys())
739 ['anotherkey']
740 >>> custom = configparser.RawConfigParser()
741 >>> custom.optionxform = lambda option: option
742 >>> custom.read_string(config)
743 >>> list(custom['Section1'].keys())
744 ['Key']
745 >>> list(custom['Section2'].keys())
746 ['AnotherKey']
747
Łukasz Langa66c908e2011-01-28 11:57:30 +0000748.. attribute:: SECTCRE
749
Łukasz Langa34cea142014-09-14 23:37:03 -0700750 A compiled regular expression used to parse section headers. The default
751 matches ``[section]`` to the name ``"section"``. Whitespace is considered
752 part of the section name, thus ``[ larch ]`` will be read as a section of
753 name ``" larch "``. Override this attribute if that's unsuitable. For
754 example:
Łukasz Langa66c908e2011-01-28 11:57:30 +0000755
756 .. doctest::
757
758 >>> config = """
759 ... [Section 1]
760 ... option = value
761 ...
762 ... [ Section 2 ]
763 ... another = val
764 ... """
765 >>> typical = ConfigParser()
766 >>> typical.read_string(config)
767 >>> typical.sections()
768 ['Section 1', ' Section 2 ']
769 >>> custom = ConfigParser()
770 >>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]")
771 >>> custom.read_string(config)
772 >>> custom.sections()
773 ['Section 1', 'Section 2']
774
775 .. note::
776
777 While ConfigParser objects also use an ``OPTCRE`` attribute for recognizing
778 option lines, it's not recommended to override it because that would
779 interfere with constructor options *allow_no_value* and *delimiters*.
780
Łukasz Langa26d513c2010-11-10 18:57:39 +0000781
782Legacy API Examples
783-------------------
784
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000785Mainly because of backwards compatibility concerns, :mod:`configparser`
786provides also a legacy API with explicit ``get``/``set`` methods. While there
787are valid use cases for the methods outlined below, mapping protocol access is
788preferred for new projects. The legacy API is at times more advanced,
789low-level and downright counterintuitive.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000790
791An example of writing to a configuration file::
792
793 import configparser
794
795 config = configparser.RawConfigParser()
796
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000797 # Please note that using RawConfigParser's set functions, you can assign
798 # non-string values to keys internally, but will receive an error when
799 # attempting to write to a file or when you get it in non-raw mode. Setting
800 # values using the mapping protocol or ConfigParser's set() does not allow
801 # such assignments to take place.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000802 config.add_section('Section1')
R David Murray1a1883d2012-09-29 14:40:23 -0400803 config.set('Section1', 'an_int', '15')
804 config.set('Section1', 'a_bool', 'true')
805 config.set('Section1', 'a_float', '3.1415')
Łukasz Langa26d513c2010-11-10 18:57:39 +0000806 config.set('Section1', 'baz', 'fun')
807 config.set('Section1', 'bar', 'Python')
808 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
809
810 # Writing our configuration file to 'example.cfg'
811 with open('example.cfg', 'w') as configfile:
812 config.write(configfile)
813
814An example of reading the configuration file again::
815
816 import configparser
817
818 config = configparser.RawConfigParser()
819 config.read('example.cfg')
820
821 # getfloat() raises an exception if the value is not a float
822 # getint() and getboolean() also do this for their respective types
R David Murray1a1883d2012-09-29 14:40:23 -0400823 a_float = config.getfloat('Section1', 'a_float')
824 an_int = config.getint('Section1', 'an_int')
825 print(a_float + an_int)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000826
827 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
828 # This is because we are using a RawConfigParser().
R David Murray1a1883d2012-09-29 14:40:23 -0400829 if config.getboolean('Section1', 'a_bool'):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000830 print(config.get('Section1', 'foo'))
831
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000832To get interpolation, use :class:`ConfigParser`::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000833
834 import configparser
835
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000836 cfg = configparser.ConfigParser()
Łukasz Langa26d513c2010-11-10 18:57:39 +0000837 cfg.read('example.cfg')
838
Éric Araujo941afed2011-09-01 02:47:34 +0200839 # Set the optional *raw* argument of get() to True if you wish to disable
Łukasz Langa26d513c2010-11-10 18:57:39 +0000840 # interpolation in a single get operation.
Serhiy Storchakadba90392016-05-10 12:01:23 +0300841 print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!"
842 print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!"
Łukasz Langa26d513c2010-11-10 18:57:39 +0000843
Éric Araujo941afed2011-09-01 02:47:34 +0200844 # The optional *vars* argument is a dict with members that will take
Łukasz Langa26d513c2010-11-10 18:57:39 +0000845 # precedence in interpolation.
846 print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation',
Serhiy Storchakadba90392016-05-10 12:01:23 +0300847 'baz': 'evil'}))
Łukasz Langa26d513c2010-11-10 18:57:39 +0000848
Éric Araujo941afed2011-09-01 02:47:34 +0200849 # The optional *fallback* argument can be used to provide a fallback value
Łukasz Langa26d513c2010-11-10 18:57:39 +0000850 print(cfg.get('Section1', 'foo'))
851 # -> "Python is fun!"
852
853 print(cfg.get('Section1', 'foo', fallback='Monty is not.'))
854 # -> "Python is fun!"
855
856 print(cfg.get('Section1', 'monster', fallback='No such things as monsters.'))
857 # -> "No such things as monsters."
858
859 # A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError
860 # but we can also use:
861
862 print(cfg.get('Section1', 'monster', fallback=None))
863 # -> None
864
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000865Default values are available in both types of ConfigParsers. They are used in
866interpolation if an option used is not defined elsewhere. ::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000867
868 import configparser
869
870 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000871 config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'})
Łukasz Langa26d513c2010-11-10 18:57:39 +0000872 config.read('example.cfg')
873
Serhiy Storchakadba90392016-05-10 12:01:23 +0300874 print(config.get('Section1', 'foo')) # -> "Python is fun!"
Łukasz Langa26d513c2010-11-10 18:57:39 +0000875 config.remove_option('Section1', 'bar')
876 config.remove_option('Section1', 'baz')
Serhiy Storchakadba90392016-05-10 12:01:23 +0300877 print(config.get('Section1', 'foo')) # -> "Life is hard!"
Łukasz Langa26d513c2010-11-10 18:57:39 +0000878
Georg Brandlbb27c122010-11-11 07:26:40 +0000879
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000880.. _configparser-objects:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000881
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000882ConfigParser Objects
883--------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000884
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700885.. 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 +0000886
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000887 The main configuration parser. When *defaults* is given, it is initialized
Georg Brandl96a60ae2010-07-28 13:13:46 +0000888 into the dictionary of intrinsic defaults. When *dict_type* is given, it
889 will be used to create the dictionary objects for the list of sections, for
890 the options within a section, and for the default values.
891
Fred Drake5a7c11f2010-11-13 05:24:17 +0000892 When *delimiters* is given, it is used as the set of substrings that
Georg Brandl96a60ae2010-07-28 13:13:46 +0000893 divide keys from values. When *comment_prefixes* is given, it will be used
Łukasz Langab25a7912010-12-17 01:32:29 +0000894 as the set of substrings that prefix comments in otherwise empty lines.
Łukasz Langa34cea142014-09-14 23:37:03 -0700895 Comments can be indented. When *inline_comment_prefixes* is given, it will
896 be used as the set of substrings that prefix comments in non-empty lines.
Łukasz Langab25a7912010-12-17 01:32:29 +0000897
Łukasz Langab25a7912010-12-17 01:32:29 +0000898 When *strict* is ``True`` (the default), the parser won't allow for
Fred Drakea4923622010-08-09 12:52:45 +0000899 any section or option duplicates while reading from a single source (file,
900 string or dictionary), raising :exc:`DuplicateSectionError` or
Fred Drake5a7c11f2010-11-13 05:24:17 +0000901 :exc:`DuplicateOptionError`. When *empty_lines_in_values* is ``False``
Fred Drakea4923622010-08-09 12:52:45 +0000902 (default: ``True``), each empty line marks the end of an option. Otherwise,
903 internal empty lines of a multiline option are kept as part of the value.
904 When *allow_no_value* is ``True`` (default: ``False``), options without
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000905 values are accepted; the value held for these is ``None`` and they are
906 serialized without the trailing delimiter.
Fred Drake03c44a32010-02-19 06:08:41 +0000907
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000908 When *default_section* is given, it specifies the name for the special
909 section holding default values for other sections and interpolation purposes
Łukasz Langa34cea142014-09-14 23:37:03 -0700910 (normally named ``"DEFAULT"``). This value can be retrieved and changed on
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000911 runtime using the ``default_section`` instance attribute.
912
913 Interpolation behaviour may be customized by providing a custom handler
914 through the *interpolation* argument. ``None`` can be used to turn off
915 interpolation completely, ``ExtendedInterpolation()`` provides a more
Łukasz Langa34cea142014-09-14 23:37:03 -0700916 advanced variant inspired by ``zc.buildout``. More on the subject in the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000917 `dedicated documentation section <#interpolation-of-values>`_.
918
919 All option names used in interpolation will be passed through the
920 :meth:`optionxform` method just like any other option name reference. For
921 example, using the default implementation of :meth:`optionxform` (which
922 converts option names to lower case), the values ``foo %(bar)s`` and ``foo
923 %(BAR)s`` are equivalent.
Georg Brandl116aa622007-08-15 14:28:22 +0000924
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700925 When *converters* is given, it should be a dictionary where each key
926 represents the name of a type converter and each value is a callable
927 implementing the conversion from string to the desired datatype. Every
928 converter gets its own corresponding :meth:`get*()` method on the parser
929 object and section proxies.
930
Raymond Hettinger231b7f12009-03-03 00:23:19 +0000931 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +0000932 The default *dict_type* is :class:`collections.OrderedDict`.
933
Fred Drake03c44a32010-02-19 06:08:41 +0000934 .. versionchanged:: 3.2
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000935 *allow_no_value*, *delimiters*, *comment_prefixes*, *strict*,
936 *empty_lines_in_values*, *default_section* and *interpolation* were
937 added.
Georg Brandl116aa622007-08-15 14:28:22 +0000938
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700939 .. versionchanged:: 3.5
940 The *converters* argument was added.
941
Fred Drake03c44a32010-02-19 06:08:41 +0000942
Georg Brandlbb27c122010-11-11 07:26:40 +0000943 .. method:: defaults()
Georg Brandl116aa622007-08-15 14:28:22 +0000944
Georg Brandlbb27c122010-11-11 07:26:40 +0000945 Return a dictionary containing the instance-wide defaults.
Georg Brandl116aa622007-08-15 14:28:22 +0000946
947
Georg Brandlbb27c122010-11-11 07:26:40 +0000948 .. method:: sections()
Georg Brandl116aa622007-08-15 14:28:22 +0000949
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000950 Return a list of the sections available; the *default section* is not
951 included in the list.
Georg Brandl116aa622007-08-15 14:28:22 +0000952
953
Georg Brandlbb27c122010-11-11 07:26:40 +0000954 .. method:: add_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000955
Georg Brandlbb27c122010-11-11 07:26:40 +0000956 Add a section named *section* to the instance. If a section by the given
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000957 name already exists, :exc:`DuplicateSectionError` is raised. If the
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000958 *default section* name is passed, :exc:`ValueError` is raised. The name
959 of the section must be a string; if not, :exc:`TypeError` is raised.
960
961 .. versionchanged:: 3.2
962 Non-string section names raise :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000963
Georg Brandl116aa622007-08-15 14:28:22 +0000964
Georg Brandlbb27c122010-11-11 07:26:40 +0000965 .. method:: has_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000966
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000967 Indicates whether the named *section* is present in the configuration.
968 The *default section* is not acknowledged.
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:: options(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000972
Georg Brandlbb27c122010-11-11 07:26:40 +0000973 Return a list of options available in the specified *section*.
Georg Brandl116aa622007-08-15 14:28:22 +0000974
Georg Brandl116aa622007-08-15 14:28:22 +0000975
Georg Brandlbb27c122010-11-11 07:26:40 +0000976 .. method:: has_option(section, option)
Georg Brandl116aa622007-08-15 14:28:22 +0000977
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000978 If the given *section* exists, and contains the given *option*, return
Łukasz Langa34cea142014-09-14 23:37:03 -0700979 :const:`True`; otherwise return :const:`False`. If the specified
Łukasz Langa71b37a52010-12-17 21:56:32 +0000980 *section* is :const:`None` or an empty string, DEFAULT is assumed.
Georg Brandl116aa622007-08-15 14:28:22 +0000981
Georg Brandl116aa622007-08-15 14:28:22 +0000982
Georg Brandlbb27c122010-11-11 07:26:40 +0000983 .. method:: read(filenames, encoding=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000984
Georg Brandlbb27c122010-11-11 07:26:40 +0000985 Attempt to read and parse a list of filenames, returning a list of
986 filenames which were successfully parsed. If *filenames* is a string, it
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000987 is treated as a single filename. If a file named in *filenames* cannot
988 be opened, that file will be ignored. This is designed so that you can
989 specify a list of potential configuration file locations (for example,
990 the current directory, the user's home directory, and some system-wide
991 directory), and all existing configuration files in the list will be
992 read. If none of the named files exist, the :class:`ConfigParser`
993 instance will contain an empty dataset. An application which requires
994 initial values to be loaded from a file should load the required file or
995 files using :meth:`read_file` before calling :meth:`read` for any
996 optional files::
Georg Brandl116aa622007-08-15 14:28:22 +0000997
Georg Brandlbb27c122010-11-11 07:26:40 +0000998 import configparser, os
Georg Brandl8dcaa732010-07-29 12:17:40 +0000999
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001000 config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +00001001 config.read_file(open('defaults.cfg'))
1002 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
1003 encoding='cp1250')
Georg Brandl116aa622007-08-15 14:28:22 +00001004
Georg Brandlbb27c122010-11-11 07:26:40 +00001005 .. versionadded:: 3.2
1006 The *encoding* parameter. Previously, all files were read using the
1007 default encoding for :func:`open`.
Georg Brandl116aa622007-08-15 14:28:22 +00001008
Georg Brandl116aa622007-08-15 14:28:22 +00001009
Georg Brandlbb27c122010-11-11 07:26:40 +00001010 .. method:: read_file(f, source=None)
Georg Brandl73753d32009-09-22 13:53:14 +00001011
Łukasz Langadaab1c82011-04-27 18:10:05 +02001012 Read and parse configuration data from *f* which must be an iterable
Łukasz Langaba702da2011-04-28 12:02:05 +02001013 yielding Unicode strings (for example files opened in text mode).
Georg Brandl116aa622007-08-15 14:28:22 +00001014
Georg Brandlbb27c122010-11-11 07:26:40 +00001015 Optional argument *source* specifies the name of the file being read. If
Fred Drake5a7c11f2010-11-13 05:24:17 +00001016 not given and *f* has a :attr:`name` attribute, that is used for
1017 *source*; the default is ``'<???>'``.
Fred Drakea4923622010-08-09 12:52:45 +00001018
Georg Brandlbb27c122010-11-11 07:26:40 +00001019 .. versionadded:: 3.2
Łukasz Langa43ae6192011-04-27 18:13:42 +02001020 Replaces :meth:`readfp`.
1021
Georg Brandlbb27c122010-11-11 07:26:40 +00001022 .. method:: read_string(string, source='<string>')
Fred Drakea4923622010-08-09 12:52:45 +00001023
Fred Drake5a7c11f2010-11-13 05:24:17 +00001024 Parse configuration data from a string.
Fred Drakea4923622010-08-09 12:52:45 +00001025
Fred Drake5a7c11f2010-11-13 05:24:17 +00001026 Optional argument *source* specifies a context-specific name of the
1027 string passed. If not given, ``'<string>'`` is used. This should
1028 commonly be a filesystem path or a URL.
Fred Drakea4923622010-08-09 12:52:45 +00001029
Georg Brandlbb27c122010-11-11 07:26:40 +00001030 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +00001031
Fred Drakea4923622010-08-09 12:52:45 +00001032
Georg Brandlbb27c122010-11-11 07:26:40 +00001033 .. method:: read_dict(dictionary, source='<dict>')
Fred Drakea4923622010-08-09 12:52:45 +00001034
Łukasz Langa71b37a52010-12-17 21:56:32 +00001035 Load configuration from any object that provides a dict-like ``items()``
1036 method. Keys are section names, values are dictionaries with keys and
1037 values that should be present in the section. If the used dictionary
1038 type preserves order, sections and their keys will be added in order.
1039 Values are automatically converted to strings.
Fred Drakea4923622010-08-09 12:52:45 +00001040
Georg Brandlbb27c122010-11-11 07:26:40 +00001041 Optional argument *source* specifies a context-specific name of the
1042 dictionary passed. If not given, ``<dict>`` is used.
Georg Brandl116aa622007-08-15 14:28:22 +00001043
Łukasz Langa71b37a52010-12-17 21:56:32 +00001044 This method can be used to copy state between parsers.
1045
Georg Brandlbb27c122010-11-11 07:26:40 +00001046 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +00001047
Georg Brandl116aa622007-08-15 14:28:22 +00001048
Ezio Melottie927e252012-09-08 20:46:01 +03001049 .. method:: get(section, option, *, raw=False, vars=None[, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +00001050
Georg Brandlbb27c122010-11-11 07:26:40 +00001051 Get an *option* value for the named *section*. If *vars* is provided, it
1052 must be a dictionary. The *option* is looked up in *vars* (if provided),
1053 *section*, and in *DEFAULTSECT* in that order. If the key is not found
1054 and *fallback* is provided, it is used as a fallback value. ``None`` can
1055 be provided as a *fallback* value.
Georg Brandl470a1232010-07-29 14:17:12 +00001056
Georg Brandlbb27c122010-11-11 07:26:40 +00001057 All the ``'%'`` interpolations are expanded in the return values, unless
1058 the *raw* argument is true. Values for interpolation keys are looked up
1059 in the same manner as the option.
Georg Brandl116aa622007-08-15 14:28:22 +00001060
Georg Brandlbb27c122010-11-11 07:26:40 +00001061 .. versionchanged:: 3.2
1062 Arguments *raw*, *vars* and *fallback* are keyword only to protect
1063 users from trying to use the third argument as the *fallback* fallback
1064 (especially when using the mapping protocol).
Georg Brandl116aa622007-08-15 14:28:22 +00001065
Łukasz Langa26d513c2010-11-10 18:57:39 +00001066
Ezio Melottie927e252012-09-08 20:46:01 +03001067 .. method:: getint(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001068
Georg Brandlbb27c122010-11-11 07:26:40 +00001069 A convenience method which coerces the *option* in the specified *section*
1070 to an integer. See :meth:`get` for explanation of *raw*, *vars* and
1071 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001072
1073
Ezio Melottie927e252012-09-08 20:46:01 +03001074 .. method:: getfloat(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001075
Georg Brandlbb27c122010-11-11 07:26:40 +00001076 A convenience method which coerces the *option* in the specified *section*
1077 to a floating point number. See :meth:`get` for explanation of *raw*,
1078 *vars* and *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001079
1080
Ezio Melottie927e252012-09-08 20:46:01 +03001081 .. method:: getboolean(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001082
Georg Brandlbb27c122010-11-11 07:26:40 +00001083 A convenience method which coerces the *option* in the specified *section*
1084 to a Boolean value. Note that the accepted values for the option are
Fred Drake5a7c11f2010-11-13 05:24:17 +00001085 ``'1'``, ``'yes'``, ``'true'``, and ``'on'``, which cause this method to
1086 return ``True``, and ``'0'``, ``'no'``, ``'false'``, and ``'off'``, which
Georg Brandlbb27c122010-11-11 07:26:40 +00001087 cause it to return ``False``. These string values are checked in a
1088 case-insensitive manner. Any other value will cause it to raise
1089 :exc:`ValueError`. See :meth:`get` for explanation of *raw*, *vars* and
1090 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001091
1092
Ezio Melottie0add762012-09-14 06:32:35 +03001093 .. method:: items(raw=False, vars=None)
1094 items(section, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001095
Łukasz Langa71b37a52010-12-17 21:56:32 +00001096 When *section* is not given, return a list of *section_name*,
1097 *section_proxy* pairs, including DEFAULTSECT.
1098
1099 Otherwise, return a list of *name*, *value* pairs for the options in the
1100 given *section*. Optional arguments have the same meaning as for the
Georg Brandlbb27c122010-11-11 07:26:40 +00001101 :meth:`get` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001102
Łukasz Langa72547622011-05-09 18:49:42 +02001103 .. versionchanged:: 3.2
Łukasz Langa34cea142014-09-14 23:37:03 -07001104 Items present in *vars* no longer appear in the result. The previous
Łukasz Langa72547622011-05-09 18:49:42 +02001105 behaviour mixed actual parser options with variables provided for
1106 interpolation.
Georg Brandl116aa622007-08-15 14:28:22 +00001107
Georg Brandlbb27c122010-11-11 07:26:40 +00001108 .. method:: set(section, option, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001109
Georg Brandlbb27c122010-11-11 07:26:40 +00001110 If the given section exists, set the given option to the specified value;
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001111 otherwise raise :exc:`NoSectionError`. *option* and *value* must be
1112 strings; if not, :exc:`TypeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001113
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001114
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001115 .. method:: write(fileobject, space_around_delimiters=True)
1116
1117 Write a representation of the configuration to the specified :term:`file
1118 object`, which must be opened in text mode (accepting strings). This
1119 representation can be parsed by a future :meth:`read` call. If
1120 *space_around_delimiters* is true, delimiters between
1121 keys and values are surrounded by spaces.
1122
1123
1124 .. method:: remove_option(section, option)
1125
1126 Remove the specified *option* from the specified *section*. If the
1127 section does not exist, raise :exc:`NoSectionError`. If the option
1128 existed to be removed, return :const:`True`; otherwise return
1129 :const:`False`.
1130
1131
1132 .. method:: remove_section(section)
1133
1134 Remove the specified *section* from the configuration. If the section in
1135 fact existed, return ``True``. Otherwise return ``False``.
1136
1137
1138 .. method:: optionxform(option)
1139
1140 Transforms the option name *option* as found in an input file or as passed
1141 in by client code to the form that should be used in the internal
1142 structures. The default implementation returns a lower-case version of
1143 *option*; subclasses may override this or client code can set an attribute
1144 of this name on instances to affect this behavior.
1145
1146 You don't need to subclass the parser to use this method, you can also
1147 set it on an instance, to a function that takes a string argument and
1148 returns a string. Setting it to ``str``, for example, would make option
1149 names case sensitive::
1150
1151 cfgparser = ConfigParser()
1152 cfgparser.optionxform = str
1153
1154 Note that when reading configuration files, whitespace around the option
1155 names is stripped before :meth:`optionxform` is called.
1156
1157
1158 .. method:: readfp(fp, filename=None)
1159
1160 .. deprecated:: 3.2
1161 Use :meth:`read_file` instead.
1162
Łukasz Langaba702da2011-04-28 12:02:05 +02001163 .. versionchanged:: 3.2
1164 :meth:`readfp` now iterates on *f* instead of calling ``f.readline()``.
1165
1166 For existing code calling :meth:`readfp` with arguments which don't
1167 support iteration, the following generator may be used as a wrapper
1168 around the file-like object::
1169
1170 def readline_generator(f):
1171 line = f.readline()
1172 while line:
1173 yield line
1174 line = f.readline()
1175
1176 Instead of ``parser.readfp(f)`` use
1177 ``parser.read_file(readline_generator(f))``.
1178
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001179
1180.. data:: MAX_INTERPOLATION_DEPTH
1181
1182 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
1183 parameter is false. This is relevant only when the default *interpolation*
1184 is used.
1185
1186
1187.. _rawconfigparser-objects:
1188
1189RawConfigParser Objects
1190-----------------------
1191
Ezio Melottie927e252012-09-08 20:46:01 +03001192.. class:: RawConfigParser(defaults=None, dict_type=collections.OrderedDict, \
1193 allow_no_value=False, *, delimiters=('=', ':'), \
1194 comment_prefixes=('#', ';'), \
1195 inline_comment_prefixes=None, strict=True, \
1196 empty_lines_in_values=True, \
1197 default_section=configparser.DEFAULTSECT[, \
1198 interpolation])
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001199
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001200 Legacy variant of the :class:`ConfigParser` with interpolation disabled
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001201 by default and unsafe ``add_section`` and ``set`` methods.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001202
1203 .. note::
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001204 Consider using :class:`ConfigParser` instead which checks types of
Łukasz Langa34cea142014-09-14 23:37:03 -07001205 the values to be stored internally. If you don't want interpolation, you
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001206 can use ``ConfigParser(interpolation=None)``.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001207
1208
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001209 .. method:: add_section(section)
1210
1211 Add a section named *section* to the instance. If a section by the given
1212 name already exists, :exc:`DuplicateSectionError` is raised. If the
1213 *default section* name is passed, :exc:`ValueError` is raised.
1214
1215 Type of *section* is not checked which lets users create non-string named
Łukasz Langa34cea142014-09-14 23:37:03 -07001216 sections. This behaviour is unsupported and may cause internal errors.
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001217
1218
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001219 .. method:: set(section, option, value)
1220
1221 If the given section exists, set the given option to the specified value;
1222 otherwise raise :exc:`NoSectionError`. While it is possible to use
1223 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters
1224 set to true) for *internal* storage of non-string values, full
1225 functionality (including interpolation and output to files) can only be
1226 achieved using string values.
1227
1228 This method lets users assign non-string values to keys internally. This
1229 behaviour is unsupported and will cause errors when attempting to write
1230 to a file or get it in non-raw mode. **Use the mapping protocol API**
1231 which does not allow such assignments to take place.
1232
1233
Łukasz Langa26d513c2010-11-10 18:57:39 +00001234Exceptions
1235----------
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001236
Łukasz Langa26d513c2010-11-10 18:57:39 +00001237.. exception:: Error
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001238
Fred Drake5a7c11f2010-11-13 05:24:17 +00001239 Base class for all other :mod:`configparser` exceptions.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001240
Georg Brandl48310cd2009-01-03 21:18:54 +00001241
Łukasz Langa26d513c2010-11-10 18:57:39 +00001242.. exception:: NoSectionError
Georg Brandl48310cd2009-01-03 21:18:54 +00001243
Łukasz Langa26d513c2010-11-10 18:57:39 +00001244 Exception raised when a specified section is not found.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001245
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001246
Łukasz Langa26d513c2010-11-10 18:57:39 +00001247.. exception:: DuplicateSectionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001248
Łukasz Langa26d513c2010-11-10 18:57:39 +00001249 Exception raised if :meth:`add_section` is called with the name of a section
1250 that is already present or in strict parsers when a section if found more
1251 than once in a single input file, string or dictionary.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001252
Łukasz Langa26d513c2010-11-10 18:57:39 +00001253 .. versionadded:: 3.2
1254 Optional ``source`` and ``lineno`` attributes and arguments to
1255 :meth:`__init__` were added.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001256
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001257
Łukasz Langa26d513c2010-11-10 18:57:39 +00001258.. exception:: DuplicateOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001259
Łukasz Langa26d513c2010-11-10 18:57:39 +00001260 Exception raised by strict parsers if a single option appears twice during
1261 reading from a single file, string or dictionary. This catches misspellings
1262 and case sensitivity-related errors, e.g. a dictionary may have two keys
1263 representing the same case-insensitive configuration key.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001264
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001265
Łukasz Langa26d513c2010-11-10 18:57:39 +00001266.. exception:: NoOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001267
Łukasz Langa26d513c2010-11-10 18:57:39 +00001268 Exception raised when a specified option is not found in the specified
1269 section.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001270
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001271
Łukasz Langa26d513c2010-11-10 18:57:39 +00001272.. exception:: InterpolationError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001273
Łukasz Langa26d513c2010-11-10 18:57:39 +00001274 Base class for exceptions raised when problems occur performing string
1275 interpolation.
Georg Brandl48310cd2009-01-03 21:18:54 +00001276
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001277
Łukasz Langa26d513c2010-11-10 18:57:39 +00001278.. exception:: InterpolationDepthError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001279
Łukasz Langa26d513c2010-11-10 18:57:39 +00001280 Exception raised when string interpolation cannot be completed because the
Georg Brandlbb27c122010-11-11 07:26:40 +00001281 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
Łukasz Langa26d513c2010-11-10 18:57:39 +00001282 :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001283
Fred Drake03c44a32010-02-19 06:08:41 +00001284
Łukasz Langa26d513c2010-11-10 18:57:39 +00001285.. exception:: InterpolationMissingOptionError
Fred Drake03c44a32010-02-19 06:08:41 +00001286
Georg Brandlbb27c122010-11-11 07:26:40 +00001287 Exception raised when an option referenced from a value does not exist.
1288 Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001289
Fred Drake03c44a32010-02-19 06:08:41 +00001290
Łukasz Langa26d513c2010-11-10 18:57:39 +00001291.. exception:: InterpolationSyntaxError
Fred Drake03c44a32010-02-19 06:08:41 +00001292
Georg Brandlbb27c122010-11-11 07:26:40 +00001293 Exception raised when the source text into which substitutions are made does
1294 not conform to the required syntax. Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001295
Łukasz Langa26d513c2010-11-10 18:57:39 +00001296
1297.. exception:: MissingSectionHeaderError
1298
Georg Brandlbb27c122010-11-11 07:26:40 +00001299 Exception raised when attempting to parse a file which has no section
1300 headers.
Łukasz Langa26d513c2010-11-10 18:57:39 +00001301
1302
1303.. exception:: ParsingError
1304
1305 Exception raised when errors occur attempting to parse a file.
1306
1307 .. versionchanged:: 3.2
1308 The ``filename`` attribute and :meth:`__init__` argument were renamed to
1309 ``source`` for consistency.
1310
Georg Brandlbb27c122010-11-11 07:26:40 +00001311
1312.. rubric:: Footnotes
1313
1314.. [1] Config parsers allow for heavy customization. If you are interested in
1315 changing the behaviour outlined by the footnote reference, consult the
1316 `Customizing Parser Behaviour`_ section.
Łukasz Langadfdd2f72014-09-15 02:08:41 -07001317