blob: 646e8a317f52c3e314de7677b26656ee5cc29fef [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`
Alex Jordan01fa9ae2017-04-05 22:21:30 -040037 Support for creating Unix shell-like mini-languages which can be used as
38 an alternate format for application configuration files.
Łukasz Langa26d513c2010-11-10 18:57:39 +000039
Ł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
Marco Buttub2a7c2f2017-03-02 12:02:43 +010045.. testsetup::
46
47 import configparser
48
49
Łukasz Langa26d513c2010-11-10 18:57:39 +000050Quick Start
51-----------
52
Georg Brandlbb27c122010-11-11 07:26:40 +000053Let's take a very basic configuration file that looks like this:
Łukasz Langa26d513c2010-11-10 18:57:39 +000054
Georg Brandlbb27c122010-11-11 07:26:40 +000055.. code-block:: ini
Łukasz Langa26d513c2010-11-10 18:57:39 +000056
Georg Brandlbb27c122010-11-11 07:26:40 +000057 [DEFAULT]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000058 ServerAliveInterval = 45
59 Compression = yes
60 CompressionLevel = 9
61 ForwardX11 = yes
Łukasz Langa26d513c2010-11-10 18:57:39 +000062
Georg Brandlbb27c122010-11-11 07:26:40 +000063 [bitbucket.org]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000064 User = hg
Łukasz Langa26d513c2010-11-10 18:57:39 +000065
Georg Brandlbb27c122010-11-11 07:26:40 +000066 [topsecret.server.com]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000067 Port = 50022
68 ForwardX11 = no
Łukasz Langa26d513c2010-11-10 18:57:39 +000069
Fred Drake5a7c11f2010-11-13 05:24:17 +000070The structure of INI files is described `in the following section
71<#supported-ini-file-structure>`_. Essentially, the file
Łukasz Langa26d513c2010-11-10 18:57:39 +000072consists of sections, each of which contains keys with values.
Georg Brandlbb27c122010-11-11 07:26:40 +000073:mod:`configparser` classes can read and write such files. Let's start by
Martin Pantereb995702016-07-28 01:11:04 +000074creating the above configuration file programmatically.
Łukasz Langa26d513c2010-11-10 18:57:39 +000075
Łukasz Langa26d513c2010-11-10 18:57:39 +000076.. doctest::
77
Georg Brandlbb27c122010-11-11 07:26:40 +000078 >>> import configparser
Łukasz Langa7f64c8a2010-12-16 01:16:22 +000079 >>> config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +000080 >>> config['DEFAULT'] = {'ServerAliveInterval': '45',
81 ... 'Compression': 'yes',
82 ... 'CompressionLevel': '9'}
83 >>> config['bitbucket.org'] = {}
84 >>> config['bitbucket.org']['User'] = 'hg'
85 >>> config['topsecret.server.com'] = {}
86 >>> topsecret = config['topsecret.server.com']
87 >>> topsecret['Port'] = '50022' # mutates the parser
88 >>> topsecret['ForwardX11'] = 'no' # same here
89 >>> config['DEFAULT']['ForwardX11'] = 'yes'
90 >>> with open('example.ini', 'w') as configfile:
91 ... config.write(configfile)
92 ...
Łukasz Langa26d513c2010-11-10 18:57:39 +000093
Fred Drake5a7c11f2010-11-13 05:24:17 +000094As you can see, we can treat a config parser much like a dictionary.
95There are differences, `outlined later <#mapping-protocol-access>`_, but
96the behavior is very close to what you would expect from a dictionary.
Łukasz Langa26d513c2010-11-10 18:57:39 +000097
Fred Drake5a7c11f2010-11-13 05:24:17 +000098Now that we have created and saved a configuration file, let's read it
99back and explore the data it holds.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000100
Łukasz Langa26d513c2010-11-10 18:57:39 +0000101.. doctest::
102
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000103 >>> config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000104 >>> config.sections()
105 []
106 >>> config.read('example.ini')
107 ['example.ini']
108 >>> config.sections()
109 ['bitbucket.org', 'topsecret.server.com']
110 >>> 'bitbucket.org' in config
111 True
112 >>> 'bytebong.com' in config
113 False
114 >>> config['bitbucket.org']['User']
115 'hg'
116 >>> config['DEFAULT']['Compression']
117 'yes'
118 >>> topsecret = config['topsecret.server.com']
119 >>> topsecret['ForwardX11']
120 'no'
121 >>> topsecret['Port']
122 '50022'
Marco Buttub2a7c2f2017-03-02 12:02:43 +0100123 >>> for key in config['bitbucket.org']: # doctest: +SKIP
124 ... print(key)
Georg Brandlbb27c122010-11-11 07:26:40 +0000125 user
126 compressionlevel
127 serveraliveinterval
128 compression
129 forwardx11
130 >>> config['bitbucket.org']['ForwardX11']
131 'yes'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000132
Fred Drake5a7c11f2010-11-13 05:24:17 +0000133As we can see above, the API is pretty straightforward. The only bit of magic
Łukasz Langa26d513c2010-11-10 18:57:39 +0000134involves the ``DEFAULT`` section which provides default values for all other
Fred Drake5a7c11f2010-11-13 05:24:17 +0000135sections [1]_. Note also that keys in sections are
136case-insensitive and stored in lowercase [1]_.
Georg Brandlbb27c122010-11-11 07:26:40 +0000137
sblondon48b0b1b2020-09-23 14:28:58 +0200138It is possible to read several configurations into a single
139:class:`ConfigParser`, where the most recently added configuration has the
140highest priority. Any conflicting keys are taken from the more recent
141configuration while the previously existing keys are retained.
142
143.. doctest::
144
145 >>> another_config = configparser.ConfigParser()
146 >>> another_config.read('example.ini')
147 ['example.ini']
148 >>> another_config['topsecret.server.com']['Port']
149 '50022'
150 >>> another_config.read_string("[topsecret.server.com]\nPort=48484")
151 >>> another_config['topsecret.server.com']['Port']
152 '48484'
153 >>> another_config.read_dict({"topsecret.server.com": {"Port": 21212}})
154 >>> another_config['topsecret.server.com']['Port']
155 '21212'
156 >>> another_config['topsecret.server.com']['ForwardX11']
157 'no'
158
159This behaviour is equivalent to a :meth:`ConfigParser.read` call with several
160files passed to the *filenames* parameter.
161
Łukasz Langa26d513c2010-11-10 18:57:39 +0000162
163Supported Datatypes
164-------------------
165
166Config parsers do not guess datatypes of values in configuration files, always
Georg Brandlbb27c122010-11-11 07:26:40 +0000167storing them internally as strings. This means that if you need other
168datatypes, you should convert on your own:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000169
Łukasz Langa26d513c2010-11-10 18:57:39 +0000170.. doctest::
171
Georg Brandlbb27c122010-11-11 07:26:40 +0000172 >>> int(topsecret['Port'])
173 50022
174 >>> float(topsecret['CompressionLevel'])
175 9.0
Łukasz Langa26d513c2010-11-10 18:57:39 +0000176
Łukasz Langa34cea142014-09-14 23:37:03 -0700177Since this task is so common, config parsers provide a range of handy getter
178methods to handle integers, floats and booleans. The last one is the most
179interesting because simply passing the value to ``bool()`` would do no good
180since ``bool('False')`` is still ``True``. This is why config parsers also
Jesus Cea647680e2016-09-20 00:01:53 +0200181provide :meth:`~ConfigParser.getboolean`. This method is case-insensitive and
182recognizes Boolean values from ``'yes'``/``'no'``, ``'on'``/``'off'``,
Łukasz Langa34cea142014-09-14 23:37:03 -0700183``'true'``/``'false'`` and ``'1'``/``'0'`` [1]_. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000184
Łukasz Langa26d513c2010-11-10 18:57:39 +0000185.. doctest::
186
Georg Brandlbb27c122010-11-11 07:26:40 +0000187 >>> topsecret.getboolean('ForwardX11')
188 False
189 >>> config['bitbucket.org'].getboolean('ForwardX11')
190 True
191 >>> config.getboolean('bitbucket.org', 'Compression')
192 True
Łukasz Langa26d513c2010-11-10 18:57:39 +0000193
Jesus Cea647680e2016-09-20 00:01:53 +0200194Apart from :meth:`~ConfigParser.getboolean`, config parsers also
195provide equivalent :meth:`~ConfigParser.getint` and
196:meth:`~ConfigParser.getfloat` methods. You can register your own
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700197converters and customize the provided ones. [1]_
Georg Brandlbb27c122010-11-11 07:26:40 +0000198
Łukasz Langa26d513c2010-11-10 18:57:39 +0000199Fallback Values
200---------------
201
Fred Drake5a7c11f2010-11-13 05:24:17 +0000202As with a dictionary, you can use a section's :meth:`get` method to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000203provide fallback values:
204
Łukasz Langa26d513c2010-11-10 18:57:39 +0000205.. doctest::
206
Georg Brandlbb27c122010-11-11 07:26:40 +0000207 >>> topsecret.get('Port')
208 '50022'
209 >>> topsecret.get('CompressionLevel')
210 '9'
211 >>> topsecret.get('Cipher')
212 >>> topsecret.get('Cipher', '3des-cbc')
213 '3des-cbc'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000214
Fred Drake5a7c11f2010-11-13 05:24:17 +0000215Please note that default values have precedence over fallback values.
216For instance, in our example the ``'CompressionLevel'`` key was
217specified only in the ``'DEFAULT'`` section. If we try to get it from
218the section ``'topsecret.server.com'``, we will always get the default,
219even if we specify a fallback:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000220
Łukasz Langa26d513c2010-11-10 18:57:39 +0000221.. doctest::
222
Georg Brandlbb27c122010-11-11 07:26:40 +0000223 >>> topsecret.get('CompressionLevel', '3')
224 '9'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000225
226One more thing to be aware of is that the parser-level :meth:`get` method
227provides a custom, more complex interface, maintained for backwards
Fred Drake5a7c11f2010-11-13 05:24:17 +0000228compatibility. When using this method, a fallback value can be provided via
229the ``fallback`` keyword-only argument:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000230
Łukasz Langa26d513c2010-11-10 18:57:39 +0000231.. doctest::
232
Georg Brandlbb27c122010-11-11 07:26:40 +0000233 >>> config.get('bitbucket.org', 'monster',
234 ... fallback='No such things as monsters')
235 'No such things as monsters'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000236
Jesus Cea647680e2016-09-20 00:01:53 +0200237The same ``fallback`` argument can be used with the
238:meth:`~ConfigParser.getint`, :meth:`~ConfigParser.getfloat` and
239:meth:`~ConfigParser.getboolean` methods, for example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000240
Łukasz Langa26d513c2010-11-10 18:57:39 +0000241.. doctest::
242
Georg Brandlbb27c122010-11-11 07:26:40 +0000243 >>> 'BatchMode' in topsecret
244 False
245 >>> topsecret.getboolean('BatchMode', fallback=True)
246 True
247 >>> config['DEFAULT']['BatchMode'] = 'no'
248 >>> topsecret.getboolean('BatchMode', fallback=True)
249 False
250
Łukasz Langa26d513c2010-11-10 18:57:39 +0000251
252Supported INI File Structure
253----------------------------
254
Georg Brandl96a60ae2010-07-28 13:13:46 +0000255A configuration file consists of sections, each led by a ``[section]`` header,
Fred Drakea4923622010-08-09 12:52:45 +0000256followed by key/value entries separated by a specific string (``=`` or ``:`` by
Georg Brandlbb27c122010-11-11 07:26:40 +0000257default [1]_). By default, section names are case sensitive but keys are not
Fred Drake5a7c11f2010-11-13 05:24:17 +0000258[1]_. Leading and trailing whitespace is removed from keys and values.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000259Values can be omitted, in which case the key/value delimiter may also be left
260out. Values can also span multiple lines, as long as they are indented deeper
261than the first line of the value. Depending on the parser's mode, blank lines
262may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000263
Fred Drake5a7c11f2010-11-13 05:24:17 +0000264Configuration files may include comments, prefixed by specific
265characters (``#`` and ``;`` by default [1]_). Comments may appear on
Łukasz Langab25a7912010-12-17 01:32:29 +0000266their own on an otherwise empty line, possibly indented. [1]_
Georg Brandl96a60ae2010-07-28 13:13:46 +0000267
Georg Brandlbb27c122010-11-11 07:26:40 +0000268For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000269
Georg Brandlbb27c122010-11-11 07:26:40 +0000270.. code-block:: ini
Georg Brandl116aa622007-08-15 14:28:22 +0000271
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000272 [Simple Values]
Łukasz Langab25a7912010-12-17 01:32:29 +0000273 key=value
274 spaces in keys=allowed
275 spaces in values=allowed as well
276 spaces around the delimiter = obviously
277 you can also use : to delimit keys from values
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000278
279 [All Values Are Strings]
280 values like this: 1000000
281 or this: 3.14159265359
282 are they treated as numbers? : no
283 integers, floats and booleans are held as: strings
284 can use the API to get converted values directly: true
Georg Brandl116aa622007-08-15 14:28:22 +0000285
Georg Brandl96a60ae2010-07-28 13:13:46 +0000286 [Multiline Values]
287 chorus: I'm a lumberjack, and I'm okay
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000288 I sleep all night and I work all day
Georg Brandl116aa622007-08-15 14:28:22 +0000289
Georg Brandl96a60ae2010-07-28 13:13:46 +0000290 [No Values]
291 key_without_value
292 empty string value here =
Georg Brandl116aa622007-08-15 14:28:22 +0000293
Łukasz Langab25a7912010-12-17 01:32:29 +0000294 [You can use comments]
295 # like this
296 ; or this
297
298 # By default only in an empty line.
299 # Inline comments can be harmful because they prevent users
300 # from using the delimiting characters as parts of values.
301 # That being said, this can be customized.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000302
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000303 [Sections Can Be Indented]
304 can_values_be_as_well = True
305 does_that_mean_anything_special = False
306 purpose = formatting for readability
307 multiline_values = are
308 handled just fine as
309 long as they are indented
310 deeper than the first line
311 of a value
312 # Did I mention we can indent comments, too?
Georg Brandl116aa622007-08-15 14:28:22 +0000313
Georg Brandl96a60ae2010-07-28 13:13:46 +0000314
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000315Interpolation of values
316-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000317
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000318On top of the core functionality, :class:`ConfigParser` supports
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000319interpolation. This means values can be preprocessed before returning them
320from ``get()`` calls.
321
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200322.. index:: single: % (percent); interpolation in configuration files
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300323
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000324.. class:: BasicInterpolation()
325
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000326 The default implementation used by :class:`ConfigParser`. It enables
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000327 values to contain format strings which refer to other values in the same
328 section, or values in the special default section [1]_. Additional default
329 values can be provided on initialization.
330
331 For example:
332
333 .. code-block:: ini
334
335 [Paths]
336 home_dir: /Users
337 my_dir: %(home_dir)s/lumberjack
338 my_pictures: %(my_dir)s/Pictures
339
Arun Persaud9a940932019-09-10 05:51:09 -0700340 [Escape]
341 gain: 80%% # use a %% to escape the % sign (% is the only character that needs to be escaped)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000342
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000343 In the example above, :class:`ConfigParser` with *interpolation* set to
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000344 ``BasicInterpolation()`` would resolve ``%(home_dir)s`` to the value of
345 ``home_dir`` (``/Users`` in this case). ``%(my_dir)s`` in effect would
346 resolve to ``/Users/lumberjack``. All interpolations are done on demand so
347 keys used in the chain of references do not have to be specified in any
348 specific order in the configuration file.
349
350 With ``interpolation`` set to ``None``, the parser would simply return
351 ``%(my_dir)s/Pictures`` as the value of ``my_pictures`` and
352 ``%(home_dir)s/lumberjack`` as the value of ``my_dir``.
353
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200354.. index:: single: $ (dollar); interpolation in configuration files
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300355
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000356.. class:: ExtendedInterpolation()
357
358 An alternative handler for interpolation which implements a more advanced
Łukasz Langa34cea142014-09-14 23:37:03 -0700359 syntax, used for instance in ``zc.buildout``. Extended interpolation is
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000360 using ``${section:option}`` to denote a value from a foreign section.
Łukasz Langa34cea142014-09-14 23:37:03 -0700361 Interpolation can span multiple levels. For convenience, if the
362 ``section:`` part is omitted, interpolation defaults to the current section
363 (and possibly the default values from the special section).
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000364
365 For example, the configuration specified above with basic interpolation,
366 would look like this with extended interpolation:
367
368 .. code-block:: ini
369
370 [Paths]
371 home_dir: /Users
372 my_dir: ${home_dir}/lumberjack
373 my_pictures: ${my_dir}/Pictures
374
Arun Persaud9a940932019-09-10 05:51:09 -0700375 [Escape]
376 cost: $$80 # use a $$ to escape the $ sign ($ is the only character that needs to be escaped)
377
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000378 Values from other sections can be fetched as well:
379
380 .. code-block:: ini
381
382 [Common]
383 home_dir: /Users
384 library_dir: /Library
385 system_dir: /System
386 macports_dir: /opt/local
387
388 [Frameworks]
389 Python: 3.2
390 path: ${Common:system_dir}/Library/Frameworks/
391
392 [Arthur]
393 nickname: Two Sheds
394 last_name: Jackson
395 my_dir: ${Common:home_dir}/twosheds
396 my_pictures: ${my_dir}/Pictures
397 python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
Georg Brandlbb27c122010-11-11 07:26:40 +0000398
Łukasz Langa26d513c2010-11-10 18:57:39 +0000399Mapping Protocol Access
400-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000401
Łukasz Langa26d513c2010-11-10 18:57:39 +0000402.. versionadded:: 3.2
Georg Brandl96a60ae2010-07-28 13:13:46 +0000403
Łukasz Langa26d513c2010-11-10 18:57:39 +0000404Mapping protocol access is a generic name for functionality that enables using
Georg Brandlbb27c122010-11-11 07:26:40 +0000405custom objects as if they were dictionaries. In case of :mod:`configparser`,
Łukasz Langa26d513c2010-11-10 18:57:39 +0000406the mapping interface implementation is using the
407``parser['section']['option']`` notation.
408
409``parser['section']`` in particular returns a proxy for the section's data in
Georg Brandlbb27c122010-11-11 07:26:40 +0000410the parser. This means that the values are not copied but they are taken from
411the original parser on demand. What's even more important is that when values
Łukasz Langa26d513c2010-11-10 18:57:39 +0000412are changed on a section proxy, they are actually mutated in the original
413parser.
414
415:mod:`configparser` objects behave as close to actual dictionaries as possible.
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300416The mapping interface is complete and adheres to the
417:class:`~collections.abc.MutableMapping` ABC.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000418However, there are a few differences that should be taken into account:
419
Georg Brandlbb27c122010-11-11 07:26:40 +0000420* By default, all keys in sections are accessible in a case-insensitive manner
421 [1]_. E.g. ``for option in parser["section"]`` yields only ``optionxform``'ed
422 option key names. This means lowercased keys by default. At the same time,
Fred Drake5a7c11f2010-11-13 05:24:17 +0000423 for a section that holds the key ``'a'``, both expressions return ``True``::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000424
Georg Brandlbb27c122010-11-11 07:26:40 +0000425 "a" in parser["section"]
426 "A" in parser["section"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000427
Georg Brandlbb27c122010-11-11 07:26:40 +0000428* All sections include ``DEFAULTSECT`` values as well which means that
429 ``.clear()`` on a section may not leave the section visibly empty. This is
Łukasz Langa26d513c2010-11-10 18:57:39 +0000430 because default values cannot be deleted from the section (because technically
Donald Stufft8b852f12014-05-20 12:58:38 -0400431 they are not there). If they are overridden in the section, deleting causes
Georg Brandlbb27c122010-11-11 07:26:40 +0000432 the default value to be visible again. Trying to delete a default value
Stéphane Wirtele483f022018-10-26 12:52:11 +0200433 causes a :exc:`KeyError`.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000434
Łukasz Langa3a8479a2012-12-31 03:38:39 +0100435* ``DEFAULTSECT`` cannot be removed from the parser:
436
Stéphane Wirtele483f022018-10-26 12:52:11 +0200437 * trying to delete it raises :exc:`ValueError`,
Łukasz Langa3a8479a2012-12-31 03:38:39 +0100438
439 * ``parser.clear()`` leaves it intact,
440
441 * ``parser.popitem()`` never returns it.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000442
Łukasz Langa71b37a52010-12-17 21:56:32 +0000443* ``parser.get(section, option, **kwargs)`` - the second argument is **not**
Łukasz Langa34cea142014-09-14 23:37:03 -0700444 a fallback value. Note however that the section-level ``get()`` methods are
Łukasz Langa71b37a52010-12-17 21:56:32 +0000445 compatible both with the mapping protocol and the classic configparser API.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000446
Łukasz Langa71b37a52010-12-17 21:56:32 +0000447* ``parser.items()`` is compatible with the mapping protocol (returns a list of
448 *section_name*, *section_proxy* pairs including the DEFAULTSECT). However,
449 this method can also be invoked with arguments: ``parser.items(section, raw,
Łukasz Langa34cea142014-09-14 23:37:03 -0700450 vars)``. The latter call returns a list of *option*, *value* pairs for
Łukasz Langa71b37a52010-12-17 21:56:32 +0000451 a specified ``section``, with all interpolations expanded (unless
452 ``raw=True`` is provided).
Łukasz Langa26d513c2010-11-10 18:57:39 +0000453
454The mapping protocol is implemented on top of the existing legacy API so that
Łukasz Langa71b37a52010-12-17 21:56:32 +0000455subclasses overriding the original interface still should have mappings working
456as expected.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000457
Georg Brandlbb27c122010-11-11 07:26:40 +0000458
Łukasz Langa26d513c2010-11-10 18:57:39 +0000459Customizing Parser Behaviour
460----------------------------
461
462There are nearly as many INI format variants as there are applications using it.
463:mod:`configparser` goes a long way to provide support for the largest sensible
Georg Brandlbb27c122010-11-11 07:26:40 +0000464set of INI styles available. The default functionality is mainly dictated by
Łukasz Langa26d513c2010-11-10 18:57:39 +0000465historical background and it's very likely that you will want to customize some
466of the features.
467
Fred Drake5a7c11f2010-11-13 05:24:17 +0000468The most common way to change the way a specific config parser works is to use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000469the :meth:`__init__` options:
470
471* *defaults*, default value: ``None``
472
473 This option accepts a dictionary of key-value pairs which will be initially
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000474 put in the ``DEFAULT`` section. This makes for an elegant way to support
475 concise configuration files that don't specify values which are the same as
476 the documented default.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000477
Fred Drake5a7c11f2010-11-13 05:24:17 +0000478 Hint: if you want to specify default values for a specific section, use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000479 :meth:`read_dict` before you read the actual file.
480
John Reese3a5b0d82018-06-05 16:31:33 -0700481* *dict_type*, default value: :class:`dict`
Łukasz Langa26d513c2010-11-10 18:57:39 +0000482
483 This option has a major impact on how the mapping protocol will behave and how
John Reese3a5b0d82018-06-05 16:31:33 -0700484 the written configuration files look. With the standard dictionary, every
485 section is stored in the order they were added to the parser. Same goes for
486 options within sections.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000487
488 An alternative dictionary type can be used for example to sort sections and
John Reese3a5b0d82018-06-05 16:31:33 -0700489 options on write-back.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000490
491 Please note: there are ways to add a set of key-value pairs in a single
Georg Brandlbb27c122010-11-11 07:26:40 +0000492 operation. When you use a regular dictionary in those operations, the order
John Reese3a5b0d82018-06-05 16:31:33 -0700493 of the keys will be ordered. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000494
Łukasz Langa26d513c2010-11-10 18:57:39 +0000495 .. doctest::
496
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000497 >>> parser = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000498 >>> parser.read_dict({'section1': {'key1': 'value1',
499 ... 'key2': 'value2',
500 ... 'key3': 'value3'},
501 ... 'section2': {'keyA': 'valueA',
502 ... 'keyB': 'valueB',
503 ... 'keyC': 'valueC'},
504 ... 'section3': {'foo': 'x',
505 ... 'bar': 'y',
506 ... 'baz': 'z'}
507 ... })
Inada Naoki0897e0c2019-01-31 17:53:48 +0900508 >>> parser.sections()
John Reese3a5b0d82018-06-05 16:31:33 -0700509 ['section1', 'section2', 'section3']
Inada Naoki0897e0c2019-01-31 17:53:48 +0900510 >>> [option for option in parser['section3']]
John Reese3a5b0d82018-06-05 16:31:33 -0700511 ['foo', 'bar', 'baz']
Łukasz Langa26d513c2010-11-10 18:57:39 +0000512
513* *allow_no_value*, default value: ``False``
514
515 Some configuration files are known to include settings without values, but
516 which otherwise conform to the syntax supported by :mod:`configparser`. The
Fred Drake5a7c11f2010-11-13 05:24:17 +0000517 *allow_no_value* parameter to the constructor can be used to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000518 indicate that such values should be accepted:
519
Łukasz Langa26d513c2010-11-10 18:57:39 +0000520 .. doctest::
521
Georg Brandlbb27c122010-11-11 07:26:40 +0000522 >>> import configparser
Łukasz Langa26d513c2010-11-10 18:57:39 +0000523
Georg Brandlbb27c122010-11-11 07:26:40 +0000524 >>> sample_config = """
525 ... [mysqld]
526 ... user = mysql
527 ... pid-file = /var/run/mysqld/mysqld.pid
528 ... skip-external-locking
529 ... old_passwords = 1
530 ... skip-bdb
Łukasz Langab25a7912010-12-17 01:32:29 +0000531 ... # we don't need ACID today
532 ... skip-innodb
Georg Brandlbb27c122010-11-11 07:26:40 +0000533 ... """
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000534 >>> config = configparser.ConfigParser(allow_no_value=True)
Georg Brandlbb27c122010-11-11 07:26:40 +0000535 >>> config.read_string(sample_config)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000536
Georg Brandlbb27c122010-11-11 07:26:40 +0000537 >>> # Settings with values are treated as before:
538 >>> config["mysqld"]["user"]
539 'mysql'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000540
Georg Brandlbb27c122010-11-11 07:26:40 +0000541 >>> # Settings without values provide None:
542 >>> config["mysqld"]["skip-bdb"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000543
Georg Brandlbb27c122010-11-11 07:26:40 +0000544 >>> # Settings which aren't specified still raise an error:
545 >>> config["mysqld"]["does-not-exist"]
546 Traceback (most recent call last):
547 ...
548 KeyError: 'does-not-exist'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000549
550* *delimiters*, default value: ``('=', ':')``
551
Łukasz Langa34cea142014-09-14 23:37:03 -0700552 Delimiters are substrings that delimit keys from values within a section.
553 The first occurrence of a delimiting substring on a line is considered
554 a delimiter. This means values (but not keys) can contain the delimiters.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000555
556 See also the *space_around_delimiters* argument to
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000557 :meth:`ConfigParser.write`.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000558
Łukasz Langab25a7912010-12-17 01:32:29 +0000559* *comment_prefixes*, default value: ``('#', ';')``
Łukasz Langa26d513c2010-11-10 18:57:39 +0000560
Łukasz Langab25a7912010-12-17 01:32:29 +0000561* *inline_comment_prefixes*, default value: ``None``
562
563 Comment prefixes are strings that indicate the start of a valid comment within
564 a config file. *comment_prefixes* are used only on otherwise empty lines
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700565 (optionally indented) whereas *inline_comment_prefixes* can be used after
566 every valid value (e.g. section names, options and empty lines as well). By
567 default inline comments are disabled and ``'#'`` and ``';'`` are used as
568 prefixes for whole line comments.
Łukasz Langab25a7912010-12-17 01:32:29 +0000569
570 .. versionchanged:: 3.2
571 In previous versions of :mod:`configparser` behaviour matched
572 ``comment_prefixes=('#',';')`` and ``inline_comment_prefixes=(';',)``.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000573
574 Please note that config parsers don't support escaping of comment prefixes so
Łukasz Langab25a7912010-12-17 01:32:29 +0000575 using *inline_comment_prefixes* may prevent users from specifying option
Łukasz Langa34cea142014-09-14 23:37:03 -0700576 values with characters used as comment prefixes. When in doubt, avoid
577 setting *inline_comment_prefixes*. In any circumstances, the only way of
578 storing comment prefix characters at the beginning of a line in multiline
579 values is to interpolate the prefix, for example::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000580
Łukasz Langab25a7912010-12-17 01:32:29 +0000581 >>> from configparser import ConfigParser, ExtendedInterpolation
582 >>> parser = ConfigParser(interpolation=ExtendedInterpolation())
583 >>> # the default BasicInterpolation could be used as well
584 >>> parser.read_string("""
585 ... [DEFAULT]
586 ... hash = #
587 ...
588 ... [hashes]
589 ... shebang =
590 ... ${hash}!/usr/bin/env python
591 ... ${hash} -*- coding: utf-8 -*-
592 ...
593 ... extensions =
594 ... enabled_extension
595 ... another_extension
596 ... #disabled_by_comment
597 ... yet_another_extension
598 ...
599 ... interpolation not necessary = if # is not at line start
600 ... even in multiline values = line #1
601 ... line #2
602 ... line #3
603 ... """)
604 >>> print(parser['hashes']['shebang'])
Marco Buttub2a7c2f2017-03-02 12:02:43 +0100605 <BLANKLINE>
Łukasz Langab25a7912010-12-17 01:32:29 +0000606 #!/usr/bin/env python
607 # -*- coding: utf-8 -*-
608 >>> print(parser['hashes']['extensions'])
Marco Buttub2a7c2f2017-03-02 12:02:43 +0100609 <BLANKLINE>
Łukasz Langab25a7912010-12-17 01:32:29 +0000610 enabled_extension
611 another_extension
612 yet_another_extension
613 >>> print(parser['hashes']['interpolation not necessary'])
614 if # is not at line start
615 >>> print(parser['hashes']['even in multiline values'])
616 line #1
617 line #2
618 line #3
619
620* *strict*, default value: ``True``
621
622 When set to ``True``, the parser will not allow for any section or option
Łukasz Langa26d513c2010-11-10 18:57:39 +0000623 duplicates while reading from a single source (using :meth:`read_file`,
Łukasz Langa34cea142014-09-14 23:37:03 -0700624 :meth:`read_string` or :meth:`read_dict`). It is recommended to use strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000625 parsers in new applications.
626
Łukasz Langab25a7912010-12-17 01:32:29 +0000627 .. versionchanged:: 3.2
628 In previous versions of :mod:`configparser` behaviour matched
629 ``strict=False``.
630
Łukasz Langa26d513c2010-11-10 18:57:39 +0000631* *empty_lines_in_values*, default value: ``True``
632
Fred Drake5a7c11f2010-11-13 05:24:17 +0000633 In config parsers, values can span multiple lines as long as they are
634 indented more than the key that holds them. By default parsers also let
635 empty lines to be parts of values. At the same time, keys can be arbitrarily
636 indented themselves to improve readability. In consequence, when
637 configuration files get big and complex, it is easy for the user to lose
638 track of the file structure. Take for instance:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000639
Georg Brandlbb27c122010-11-11 07:26:40 +0000640 .. code-block:: ini
Łukasz Langa26d513c2010-11-10 18:57:39 +0000641
Georg Brandlbb27c122010-11-11 07:26:40 +0000642 [Section]
643 key = multiline
644 value with a gotcha
Łukasz Langa26d513c2010-11-10 18:57:39 +0000645
Georg Brandlbb27c122010-11-11 07:26:40 +0000646 this = is still a part of the multiline value of 'key'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000647
Georg Brandlbb27c122010-11-11 07:26:40 +0000648 This can be especially problematic for the user to see if she's using a
649 proportional font to edit the file. That is why when your application does
650 not need values with empty lines, you should consider disallowing them. This
651 will make empty lines split keys every time. In the example above, it would
Łukasz Langa26d513c2010-11-10 18:57:39 +0000652 produce two keys, ``key`` and ``this``.
653
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000654* *default_section*, default value: ``configparser.DEFAULTSECT`` (that is:
655 ``"DEFAULT"``)
656
657 The convention of allowing a special section of default values for other
658 sections or interpolation purposes is a powerful concept of this library,
Łukasz Langa34cea142014-09-14 23:37:03 -0700659 letting users create complex declarative configurations. This section is
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000660 normally called ``"DEFAULT"`` but this can be customized to point to any
Łukasz Langa34cea142014-09-14 23:37:03 -0700661 other valid section name. Some typical values include: ``"general"`` or
662 ``"common"``. The name provided is used for recognizing default sections
663 when reading from any source and is used when writing configuration back to
664 a file. Its current value can be retrieved using the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000665 ``parser_instance.default_section`` attribute and may be modified at runtime
666 (i.e. to convert files from one format to another).
667
668* *interpolation*, default value: ``configparser.BasicInterpolation``
669
670 Interpolation behaviour may be customized by providing a custom handler
671 through the *interpolation* argument. ``None`` can be used to turn off
672 interpolation completely, ``ExtendedInterpolation()`` provides a more
Łukasz Langa34cea142014-09-14 23:37:03 -0700673 advanced variant inspired by ``zc.buildout``. More on the subject in the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000674 `dedicated documentation section <#interpolation-of-values>`_.
Łukasz Langab25a7912010-12-17 01:32:29 +0000675 :class:`RawConfigParser` has a default value of ``None``.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000676
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700677* *converters*, default value: not set
678
679 Config parsers provide option value getters that perform type conversion. By
Jesus Cea647680e2016-09-20 00:01:53 +0200680 default :meth:`~ConfigParser.getint`, :meth:`~ConfigParser.getfloat`, and
681 :meth:`~ConfigParser.getboolean` are implemented. Should other getters be
682 desirable, users may define them in a subclass or pass a dictionary where each
683 key is a name of the converter and each value is a callable implementing said
684 conversion. For instance, passing ``{'decimal': decimal.Decimal}`` would add
685 :meth:`getdecimal` on both the parser object and all section proxies. In
686 other words, it will be possible to write both
687 ``parser_instance.getdecimal('section', 'key', fallback=0)`` and
688 ``parser_instance['section'].getdecimal('key', 0)``.
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700689
690 If the converter needs to access the state of the parser, it can be
691 implemented as a method on a config parser subclass. If the name of this
692 method starts with ``get``, it will be available on all section proxies, in
693 the dict-compatible form (see the ``getdecimal()`` example above).
Łukasz Langa26d513c2010-11-10 18:57:39 +0000694
Fred Drake5a7c11f2010-11-13 05:24:17 +0000695More advanced customization may be achieved by overriding default values of
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700696these parser attributes. The defaults are defined on the classes, so they may
697be overridden by subclasses or by attribute assignment.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000698
Ned Batchelder890423f2018-10-24 19:47:01 -0400699.. attribute:: ConfigParser.BOOLEAN_STATES
Łukasz Langa26d513c2010-11-10 18:57:39 +0000700
Victor Stinnerd3ded082020-08-13 21:41:54 +0200701 By default when using :meth:`~ConfigParser.getboolean`, config parsers
702 consider the following values ``True``: ``'1'``, ``'yes'``, ``'true'``,
703 ``'on'`` and the following values ``False``: ``'0'``, ``'no'``, ``'false'``,
704 ``'off'``. You can override this by specifying a custom dictionary of strings
705 and their Boolean outcomes. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000706
Victor Stinnerd3ded082020-08-13 21:41:54 +0200707 .. doctest::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000708
Victor Stinnerd3ded082020-08-13 21:41:54 +0200709 >>> custom = configparser.ConfigParser()
710 >>> custom['section1'] = {'funky': 'nope'}
711 >>> custom['section1'].getboolean('funky')
712 Traceback (most recent call last):
713 ...
714 ValueError: Not a boolean: nope
715 >>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}
716 >>> custom['section1'].getboolean('funky')
717 False
Łukasz Langa26d513c2010-11-10 18:57:39 +0000718
Victor Stinnerd3ded082020-08-13 21:41:54 +0200719 Other typical Boolean pairs include ``accept``/``reject`` or
720 ``enabled``/``disabled``.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000721
Ned Batchelder890423f2018-10-24 19:47:01 -0400722.. method:: ConfigParser.optionxform(option)
Victor Stinnerd3ded082020-08-13 21:41:54 +0200723 :noindex:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000724
Victor Stinnerd3ded082020-08-13 21:41:54 +0200725 This method transforms option names on every read, get, or set
726 operation. The default converts the name to lowercase. This also
727 means that when a configuration file gets written, all keys will be
728 lowercase. Override this method if that's unsuitable.
729 For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000730
Victor Stinnerd3ded082020-08-13 21:41:54 +0200731 .. doctest::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000732
Victor Stinnerd3ded082020-08-13 21:41:54 +0200733 >>> config = """
734 ... [Section1]
735 ... Key = Value
736 ...
737 ... [Section2]
738 ... AnotherKey = Value
739 ... """
740 >>> typical = configparser.ConfigParser()
741 >>> typical.read_string(config)
742 >>> list(typical['Section1'].keys())
743 ['key']
744 >>> list(typical['Section2'].keys())
745 ['anotherkey']
746 >>> custom = configparser.RawConfigParser()
747 >>> custom.optionxform = lambda option: option
748 >>> custom.read_string(config)
749 >>> list(custom['Section1'].keys())
750 ['Key']
751 >>> list(custom['Section2'].keys())
752 ['AnotherKey']
Georg Brandlbb27c122010-11-11 07:26:40 +0000753
Victor Stinnerd3ded082020-08-13 21:41:54 +0200754 .. note::
755 The optionxform function transforms option names to a canonical form.
756 This should be an idempotent function: if the name is already in
757 canonical form, it should be returned unchanged.
Inada Naoki04694a32019-04-02 18:08:46 +0900758
759
Ned Batchelder890423f2018-10-24 19:47:01 -0400760.. attribute:: ConfigParser.SECTCRE
Łukasz Langa66c908e2011-01-28 11:57:30 +0000761
Victor Stinnerd3ded082020-08-13 21:41:54 +0200762 A compiled regular expression used to parse section headers. The default
763 matches ``[section]`` to the name ``"section"``. Whitespace is considered
764 part of the section name, thus ``[ larch ]`` will be read as a section of
765 name ``" larch "``. Override this attribute if that's unsuitable. For
766 example:
Łukasz Langa66c908e2011-01-28 11:57:30 +0000767
Victor Stinnerd3ded082020-08-13 21:41:54 +0200768 .. doctest::
Łukasz Langa66c908e2011-01-28 11:57:30 +0000769
Victor Stinnerd3ded082020-08-13 21:41:54 +0200770 >>> import re
771 >>> config = """
772 ... [Section 1]
773 ... option = value
774 ...
775 ... [ Section 2 ]
776 ... another = val
777 ... """
778 >>> typical = configparser.ConfigParser()
779 >>> typical.read_string(config)
780 >>> typical.sections()
781 ['Section 1', ' Section 2 ']
782 >>> custom = configparser.ConfigParser()
783 >>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]")
784 >>> custom.read_string(config)
785 >>> custom.sections()
786 ['Section 1', 'Section 2']
Łukasz Langa66c908e2011-01-28 11:57:30 +0000787
Victor Stinnerd3ded082020-08-13 21:41:54 +0200788 .. note::
Łukasz Langa66c908e2011-01-28 11:57:30 +0000789
Victor Stinnerd3ded082020-08-13 21:41:54 +0200790 While ConfigParser objects also use an ``OPTCRE`` attribute for recognizing
791 option lines, it's not recommended to override it because that would
792 interfere with constructor options *allow_no_value* and *delimiters*.
Łukasz Langa66c908e2011-01-28 11:57:30 +0000793
Łukasz Langa26d513c2010-11-10 18:57:39 +0000794
795Legacy API Examples
796-------------------
797
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000798Mainly because of backwards compatibility concerns, :mod:`configparser`
799provides also a legacy API with explicit ``get``/``set`` methods. While there
800are valid use cases for the methods outlined below, mapping protocol access is
801preferred for new projects. The legacy API is at times more advanced,
802low-level and downright counterintuitive.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000803
804An example of writing to a configuration file::
805
806 import configparser
807
808 config = configparser.RawConfigParser()
809
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000810 # Please note that using RawConfigParser's set functions, you can assign
811 # non-string values to keys internally, but will receive an error when
812 # attempting to write to a file or when you get it in non-raw mode. Setting
813 # values using the mapping protocol or ConfigParser's set() does not allow
814 # such assignments to take place.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000815 config.add_section('Section1')
R David Murray1a1883d2012-09-29 14:40:23 -0400816 config.set('Section1', 'an_int', '15')
817 config.set('Section1', 'a_bool', 'true')
818 config.set('Section1', 'a_float', '3.1415')
Łukasz Langa26d513c2010-11-10 18:57:39 +0000819 config.set('Section1', 'baz', 'fun')
820 config.set('Section1', 'bar', 'Python')
821 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
822
823 # Writing our configuration file to 'example.cfg'
824 with open('example.cfg', 'w') as configfile:
825 config.write(configfile)
826
827An example of reading the configuration file again::
828
829 import configparser
830
831 config = configparser.RawConfigParser()
832 config.read('example.cfg')
833
834 # getfloat() raises an exception if the value is not a float
835 # getint() and getboolean() also do this for their respective types
R David Murray1a1883d2012-09-29 14:40:23 -0400836 a_float = config.getfloat('Section1', 'a_float')
837 an_int = config.getint('Section1', 'an_int')
838 print(a_float + an_int)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000839
840 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
841 # This is because we are using a RawConfigParser().
R David Murray1a1883d2012-09-29 14:40:23 -0400842 if config.getboolean('Section1', 'a_bool'):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000843 print(config.get('Section1', 'foo'))
844
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000845To get interpolation, use :class:`ConfigParser`::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000846
847 import configparser
848
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000849 cfg = configparser.ConfigParser()
Łukasz Langa26d513c2010-11-10 18:57:39 +0000850 cfg.read('example.cfg')
851
Éric Araujo941afed2011-09-01 02:47:34 +0200852 # Set the optional *raw* argument of get() to True if you wish to disable
Łukasz Langa26d513c2010-11-10 18:57:39 +0000853 # interpolation in a single get operation.
Serhiy Storchakadba90392016-05-10 12:01:23 +0300854 print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!"
855 print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!"
Łukasz Langa26d513c2010-11-10 18:57:39 +0000856
Éric Araujo941afed2011-09-01 02:47:34 +0200857 # The optional *vars* argument is a dict with members that will take
Łukasz Langa26d513c2010-11-10 18:57:39 +0000858 # precedence in interpolation.
859 print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation',
Serhiy Storchakadba90392016-05-10 12:01:23 +0300860 'baz': 'evil'}))
Łukasz Langa26d513c2010-11-10 18:57:39 +0000861
Éric Araujo941afed2011-09-01 02:47:34 +0200862 # The optional *fallback* argument can be used to provide a fallback value
Łukasz Langa26d513c2010-11-10 18:57:39 +0000863 print(cfg.get('Section1', 'foo'))
864 # -> "Python is fun!"
865
866 print(cfg.get('Section1', 'foo', fallback='Monty is not.'))
867 # -> "Python is fun!"
868
869 print(cfg.get('Section1', 'monster', fallback='No such things as monsters.'))
870 # -> "No such things as monsters."
871
872 # A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError
873 # but we can also use:
874
875 print(cfg.get('Section1', 'monster', fallback=None))
876 # -> None
877
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000878Default values are available in both types of ConfigParsers. They are used in
879interpolation if an option used is not defined elsewhere. ::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000880
881 import configparser
882
883 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000884 config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'})
Łukasz Langa26d513c2010-11-10 18:57:39 +0000885 config.read('example.cfg')
886
Serhiy Storchakadba90392016-05-10 12:01:23 +0300887 print(config.get('Section1', 'foo')) # -> "Python is fun!"
Łukasz Langa26d513c2010-11-10 18:57:39 +0000888 config.remove_option('Section1', 'bar')
889 config.remove_option('Section1', 'baz')
Serhiy Storchakadba90392016-05-10 12:01:23 +0300890 print(config.get('Section1', 'foo')) # -> "Life is hard!"
Łukasz Langa26d513c2010-11-10 18:57:39 +0000891
Georg Brandlbb27c122010-11-11 07:26:40 +0000892
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000893.. _configparser-objects:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000894
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000895ConfigParser Objects
896--------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000897
Andrés Delfino3b0b90c2018-06-08 16:19:21 -0300898.. class:: ConfigParser(defaults=None, dict_type=dict, 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 +0000899
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000900 The main configuration parser. When *defaults* is given, it is initialized
Georg Brandl96a60ae2010-07-28 13:13:46 +0000901 into the dictionary of intrinsic defaults. When *dict_type* is given, it
902 will be used to create the dictionary objects for the list of sections, for
903 the options within a section, and for the default values.
904
Fred Drake5a7c11f2010-11-13 05:24:17 +0000905 When *delimiters* is given, it is used as the set of substrings that
Georg Brandl96a60ae2010-07-28 13:13:46 +0000906 divide keys from values. When *comment_prefixes* is given, it will be used
Łukasz Langab25a7912010-12-17 01:32:29 +0000907 as the set of substrings that prefix comments in otherwise empty lines.
Łukasz Langa34cea142014-09-14 23:37:03 -0700908 Comments can be indented. When *inline_comment_prefixes* is given, it will
909 be used as the set of substrings that prefix comments in non-empty lines.
Łukasz Langab25a7912010-12-17 01:32:29 +0000910
Łukasz Langab25a7912010-12-17 01:32:29 +0000911 When *strict* is ``True`` (the default), the parser won't allow for
Fred Drakea4923622010-08-09 12:52:45 +0000912 any section or option duplicates while reading from a single source (file,
913 string or dictionary), raising :exc:`DuplicateSectionError` or
Fred Drake5a7c11f2010-11-13 05:24:17 +0000914 :exc:`DuplicateOptionError`. When *empty_lines_in_values* is ``False``
Fred Drakea4923622010-08-09 12:52:45 +0000915 (default: ``True``), each empty line marks the end of an option. Otherwise,
916 internal empty lines of a multiline option are kept as part of the value.
917 When *allow_no_value* is ``True`` (default: ``False``), options without
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000918 values are accepted; the value held for these is ``None`` and they are
919 serialized without the trailing delimiter.
Fred Drake03c44a32010-02-19 06:08:41 +0000920
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000921 When *default_section* is given, it specifies the name for the special
922 section holding default values for other sections and interpolation purposes
Łukasz Langa34cea142014-09-14 23:37:03 -0700923 (normally named ``"DEFAULT"``). This value can be retrieved and changed on
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000924 runtime using the ``default_section`` instance attribute.
925
926 Interpolation behaviour may be customized by providing a custom handler
927 through the *interpolation* argument. ``None`` can be used to turn off
928 interpolation completely, ``ExtendedInterpolation()`` provides a more
Łukasz Langa34cea142014-09-14 23:37:03 -0700929 advanced variant inspired by ``zc.buildout``. More on the subject in the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000930 `dedicated documentation section <#interpolation-of-values>`_.
931
932 All option names used in interpolation will be passed through the
933 :meth:`optionxform` method just like any other option name reference. For
934 example, using the default implementation of :meth:`optionxform` (which
935 converts option names to lower case), the values ``foo %(bar)s`` and ``foo
936 %(BAR)s`` are equivalent.
Georg Brandl116aa622007-08-15 14:28:22 +0000937
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700938 When *converters* is given, it should be a dictionary where each key
939 represents the name of a type converter and each value is a callable
940 implementing the conversion from string to the desired datatype. Every
941 converter gets its own corresponding :meth:`get*()` method on the parser
942 object and section proxies.
943
Raymond Hettinger231b7f12009-03-03 00:23:19 +0000944 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +0000945 The default *dict_type* is :class:`collections.OrderedDict`.
946
Fred Drake03c44a32010-02-19 06:08:41 +0000947 .. versionchanged:: 3.2
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000948 *allow_no_value*, *delimiters*, *comment_prefixes*, *strict*,
949 *empty_lines_in_values*, *default_section* and *interpolation* were
950 added.
Georg Brandl116aa622007-08-15 14:28:22 +0000951
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700952 .. versionchanged:: 3.5
953 The *converters* argument was added.
954
Łukasz Langaea579232017-08-21 16:23:38 -0700955 .. versionchanged:: 3.7
956 The *defaults* argument is read with :meth:`read_dict()`,
957 providing consistent behavior across the parser: non-string
958 keys and values are implicitly converted to strings.
959
Inada Naoki0897e0c2019-01-31 17:53:48 +0900960 .. versionchanged:: 3.8
Andrés Delfino3b0b90c2018-06-08 16:19:21 -0300961 The default *dict_type* is :class:`dict`, since it now preserves
962 insertion order.
Fred Drake03c44a32010-02-19 06:08:41 +0000963
Georg Brandlbb27c122010-11-11 07:26:40 +0000964 .. method:: defaults()
Georg Brandl116aa622007-08-15 14:28:22 +0000965
Georg Brandlbb27c122010-11-11 07:26:40 +0000966 Return a dictionary containing the instance-wide defaults.
Georg Brandl116aa622007-08-15 14:28:22 +0000967
968
Georg Brandlbb27c122010-11-11 07:26:40 +0000969 .. method:: sections()
Georg Brandl116aa622007-08-15 14:28:22 +0000970
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000971 Return a list of the sections available; the *default section* is not
972 included in the list.
Georg Brandl116aa622007-08-15 14:28:22 +0000973
974
Georg Brandlbb27c122010-11-11 07:26:40 +0000975 .. method:: add_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000976
Georg Brandlbb27c122010-11-11 07:26:40 +0000977 Add a section named *section* to the instance. If a section by the given
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000978 name already exists, :exc:`DuplicateSectionError` is raised. If the
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000979 *default section* name is passed, :exc:`ValueError` is raised. The name
980 of the section must be a string; if not, :exc:`TypeError` is raised.
981
982 .. versionchanged:: 3.2
983 Non-string section names raise :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000984
Georg Brandl116aa622007-08-15 14:28:22 +0000985
Georg Brandlbb27c122010-11-11 07:26:40 +0000986 .. method:: has_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000987
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000988 Indicates whether the named *section* is present in the configuration.
989 The *default section* is not acknowledged.
Georg Brandl116aa622007-08-15 14:28:22 +0000990
Georg Brandl116aa622007-08-15 14:28:22 +0000991
Georg Brandlbb27c122010-11-11 07:26:40 +0000992 .. method:: options(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000993
Georg Brandlbb27c122010-11-11 07:26:40 +0000994 Return a list of options available in the specified *section*.
Georg Brandl116aa622007-08-15 14:28:22 +0000995
Georg Brandl116aa622007-08-15 14:28:22 +0000996
Georg Brandlbb27c122010-11-11 07:26:40 +0000997 .. method:: has_option(section, option)
Georg Brandl116aa622007-08-15 14:28:22 +0000998
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000999 If the given *section* exists, and contains the given *option*, return
Łukasz Langa34cea142014-09-14 23:37:03 -07001000 :const:`True`; otherwise return :const:`False`. If the specified
Łukasz Langa71b37a52010-12-17 21:56:32 +00001001 *section* is :const:`None` or an empty string, DEFAULT is assumed.
Georg Brandl116aa622007-08-15 14:28:22 +00001002
Georg Brandl116aa622007-08-15 14:28:22 +00001003
Georg Brandlbb27c122010-11-11 07:26:40 +00001004 .. method:: read(filenames, encoding=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001005
Zackery Spytze45473e2018-09-29 10:15:55 -06001006 Attempt to read and parse an iterable of filenames, returning a list of
David Ellis85b8d012017-03-03 17:14:27 +00001007 filenames which were successfully parsed.
1008
Vincent Michele3148532017-11-02 13:47:04 +01001009 If *filenames* is a string, a :class:`bytes` object or a
1010 :term:`path-like object`, it is treated as
David Ellis85b8d012017-03-03 17:14:27 +00001011 a single filename. If a file named in *filenames* cannot be opened, that
Zackery Spytze45473e2018-09-29 10:15:55 -06001012 file will be ignored. This is designed so that you can specify an
1013 iterable of potential configuration file locations (for example, the
1014 current directory, the user's home directory, and some system-wide
1015 directory), and all existing configuration files in the iterable will be
1016 read.
David Ellis85b8d012017-03-03 17:14:27 +00001017
1018 If none of the named files exist, the :class:`ConfigParser`
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001019 instance will contain an empty dataset. An application which requires
1020 initial values to be loaded from a file should load the required file or
1021 files using :meth:`read_file` before calling :meth:`read` for any
1022 optional files::
Georg Brandl116aa622007-08-15 14:28:22 +00001023
Georg Brandlbb27c122010-11-11 07:26:40 +00001024 import configparser, os
Georg Brandl8dcaa732010-07-29 12:17:40 +00001025
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001026 config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +00001027 config.read_file(open('defaults.cfg'))
1028 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
1029 encoding='cp1250')
Georg Brandl116aa622007-08-15 14:28:22 +00001030
Georg Brandlbb27c122010-11-11 07:26:40 +00001031 .. versionadded:: 3.2
1032 The *encoding* parameter. Previously, all files were read using the
1033 default encoding for :func:`open`.
Georg Brandl116aa622007-08-15 14:28:22 +00001034
David Ellis85b8d012017-03-03 17:14:27 +00001035 .. versionadded:: 3.6.1
1036 The *filenames* parameter accepts a :term:`path-like object`.
1037
Vincent Michele3148532017-11-02 13:47:04 +01001038 .. versionadded:: 3.7
1039 The *filenames* parameter accepts a :class:`bytes` object.
1040
Georg Brandl116aa622007-08-15 14:28:22 +00001041
Georg Brandlbb27c122010-11-11 07:26:40 +00001042 .. method:: read_file(f, source=None)
Georg Brandl73753d32009-09-22 13:53:14 +00001043
Łukasz Langadaab1c82011-04-27 18:10:05 +02001044 Read and parse configuration data from *f* which must be an iterable
Łukasz Langaba702da2011-04-28 12:02:05 +02001045 yielding Unicode strings (for example files opened in text mode).
Georg Brandl116aa622007-08-15 14:28:22 +00001046
Georg Brandlbb27c122010-11-11 07:26:40 +00001047 Optional argument *source* specifies the name of the file being read. If
Fred Drake5a7c11f2010-11-13 05:24:17 +00001048 not given and *f* has a :attr:`name` attribute, that is used for
1049 *source*; the default is ``'<???>'``.
Fred Drakea4923622010-08-09 12:52:45 +00001050
Georg Brandlbb27c122010-11-11 07:26:40 +00001051 .. versionadded:: 3.2
Łukasz Langa43ae6192011-04-27 18:13:42 +02001052 Replaces :meth:`readfp`.
1053
Georg Brandlbb27c122010-11-11 07:26:40 +00001054 .. method:: read_string(string, source='<string>')
Fred Drakea4923622010-08-09 12:52:45 +00001055
Fred Drake5a7c11f2010-11-13 05:24:17 +00001056 Parse configuration data from a string.
Fred Drakea4923622010-08-09 12:52:45 +00001057
Fred Drake5a7c11f2010-11-13 05:24:17 +00001058 Optional argument *source* specifies a context-specific name of the
1059 string passed. If not given, ``'<string>'`` is used. This should
1060 commonly be a filesystem path or a URL.
Fred Drakea4923622010-08-09 12:52:45 +00001061
Georg Brandlbb27c122010-11-11 07:26:40 +00001062 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +00001063
Fred Drakea4923622010-08-09 12:52:45 +00001064
Georg Brandlbb27c122010-11-11 07:26:40 +00001065 .. method:: read_dict(dictionary, source='<dict>')
Fred Drakea4923622010-08-09 12:52:45 +00001066
Łukasz Langa71b37a52010-12-17 21:56:32 +00001067 Load configuration from any object that provides a dict-like ``items()``
1068 method. Keys are section names, values are dictionaries with keys and
1069 values that should be present in the section. If the used dictionary
1070 type preserves order, sections and their keys will be added in order.
1071 Values are automatically converted to strings.
Fred Drakea4923622010-08-09 12:52:45 +00001072
Georg Brandlbb27c122010-11-11 07:26:40 +00001073 Optional argument *source* specifies a context-specific name of the
1074 dictionary passed. If not given, ``<dict>`` is used.
Georg Brandl116aa622007-08-15 14:28:22 +00001075
Łukasz Langa71b37a52010-12-17 21:56:32 +00001076 This method can be used to copy state between parsers.
1077
Georg Brandlbb27c122010-11-11 07:26:40 +00001078 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +00001079
Georg Brandl116aa622007-08-15 14:28:22 +00001080
Ezio Melottie927e252012-09-08 20:46:01 +03001081 .. method:: get(section, option, *, raw=False, vars=None[, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +00001082
Georg Brandlbb27c122010-11-11 07:26:40 +00001083 Get an *option* value for the named *section*. If *vars* is provided, it
1084 must be a dictionary. The *option* is looked up in *vars* (if provided),
1085 *section*, and in *DEFAULTSECT* in that order. If the key is not found
1086 and *fallback* is provided, it is used as a fallback value. ``None`` can
1087 be provided as a *fallback* value.
Georg Brandl470a1232010-07-29 14:17:12 +00001088
Georg Brandlbb27c122010-11-11 07:26:40 +00001089 All the ``'%'`` interpolations are expanded in the return values, unless
1090 the *raw* argument is true. Values for interpolation keys are looked up
1091 in the same manner as the option.
Georg Brandl116aa622007-08-15 14:28:22 +00001092
Georg Brandlbb27c122010-11-11 07:26:40 +00001093 .. versionchanged:: 3.2
1094 Arguments *raw*, *vars* and *fallback* are keyword only to protect
1095 users from trying to use the third argument as the *fallback* fallback
1096 (especially when using the mapping protocol).
Georg Brandl116aa622007-08-15 14:28:22 +00001097
Łukasz Langa26d513c2010-11-10 18:57:39 +00001098
Ezio Melottie927e252012-09-08 20:46:01 +03001099 .. method:: getint(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001100
Georg Brandlbb27c122010-11-11 07:26:40 +00001101 A convenience method which coerces the *option* in the specified *section*
1102 to an integer. See :meth:`get` for explanation of *raw*, *vars* and
1103 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001104
1105
Ezio Melottie927e252012-09-08 20:46:01 +03001106 .. method:: getfloat(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001107
Georg Brandlbb27c122010-11-11 07:26:40 +00001108 A convenience method which coerces the *option* in the specified *section*
1109 to a floating point number. See :meth:`get` for explanation of *raw*,
1110 *vars* and *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001111
1112
Ezio Melottie927e252012-09-08 20:46:01 +03001113 .. method:: getboolean(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001114
Georg Brandlbb27c122010-11-11 07:26:40 +00001115 A convenience method which coerces the *option* in the specified *section*
1116 to a Boolean value. Note that the accepted values for the option are
Fred Drake5a7c11f2010-11-13 05:24:17 +00001117 ``'1'``, ``'yes'``, ``'true'``, and ``'on'``, which cause this method to
1118 return ``True``, and ``'0'``, ``'no'``, ``'false'``, and ``'off'``, which
Georg Brandlbb27c122010-11-11 07:26:40 +00001119 cause it to return ``False``. These string values are checked in a
1120 case-insensitive manner. Any other value will cause it to raise
1121 :exc:`ValueError`. See :meth:`get` for explanation of *raw*, *vars* and
1122 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001123
1124
Ezio Melottie0add762012-09-14 06:32:35 +03001125 .. method:: items(raw=False, vars=None)
1126 items(section, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001127
Łukasz Langa71b37a52010-12-17 21:56:32 +00001128 When *section* is not given, return a list of *section_name*,
1129 *section_proxy* pairs, including DEFAULTSECT.
1130
1131 Otherwise, return a list of *name*, *value* pairs for the options in the
1132 given *section*. Optional arguments have the same meaning as for the
Georg Brandlbb27c122010-11-11 07:26:40 +00001133 :meth:`get` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001134
Andrés Delfino4acc1402018-06-08 21:20:05 -03001135 .. versionchanged:: 3.8
1136 Items present in *vars* no longer appear in the result. The previous
1137 behaviour mixed actual parser options with variables provided for
1138 interpolation.
Chris Bradburye5008392018-04-23 21:56:39 +01001139
Georg Brandl116aa622007-08-15 14:28:22 +00001140
Georg Brandlbb27c122010-11-11 07:26:40 +00001141 .. method:: set(section, option, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001142
Georg Brandlbb27c122010-11-11 07:26:40 +00001143 If the given section exists, set the given option to the specified value;
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001144 otherwise raise :exc:`NoSectionError`. *option* and *value* must be
1145 strings; if not, :exc:`TypeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001146
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001147
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001148 .. method:: write(fileobject, space_around_delimiters=True)
1149
1150 Write a representation of the configuration to the specified :term:`file
1151 object`, which must be opened in text mode (accepting strings). This
1152 representation can be parsed by a future :meth:`read` call. If
1153 *space_around_delimiters* is true, delimiters between
1154 keys and values are surrounded by spaces.
1155
1156
1157 .. method:: remove_option(section, option)
1158
1159 Remove the specified *option* from the specified *section*. If the
1160 section does not exist, raise :exc:`NoSectionError`. If the option
1161 existed to be removed, return :const:`True`; otherwise return
1162 :const:`False`.
1163
1164
1165 .. method:: remove_section(section)
1166
1167 Remove the specified *section* from the configuration. If the section in
1168 fact existed, return ``True``. Otherwise return ``False``.
1169
1170
1171 .. method:: optionxform(option)
1172
1173 Transforms the option name *option* as found in an input file or as passed
1174 in by client code to the form that should be used in the internal
1175 structures. The default implementation returns a lower-case version of
1176 *option*; subclasses may override this or client code can set an attribute
1177 of this name on instances to affect this behavior.
1178
1179 You don't need to subclass the parser to use this method, you can also
1180 set it on an instance, to a function that takes a string argument and
1181 returns a string. Setting it to ``str``, for example, would make option
1182 names case sensitive::
1183
1184 cfgparser = ConfigParser()
1185 cfgparser.optionxform = str
1186
1187 Note that when reading configuration files, whitespace around the option
1188 names is stripped before :meth:`optionxform` is called.
1189
1190
1191 .. method:: readfp(fp, filename=None)
1192
1193 .. deprecated:: 3.2
1194 Use :meth:`read_file` instead.
1195
Łukasz Langaba702da2011-04-28 12:02:05 +02001196 .. versionchanged:: 3.2
Martin Panter1f106712017-01-29 23:33:27 +00001197 :meth:`readfp` now iterates on *fp* instead of calling ``fp.readline()``.
Łukasz Langaba702da2011-04-28 12:02:05 +02001198
1199 For existing code calling :meth:`readfp` with arguments which don't
1200 support iteration, the following generator may be used as a wrapper
1201 around the file-like object::
1202
Martin Panter1f106712017-01-29 23:33:27 +00001203 def readline_generator(fp):
1204 line = fp.readline()
Łukasz Langaba702da2011-04-28 12:02:05 +02001205 while line:
1206 yield line
Martin Panter1f106712017-01-29 23:33:27 +00001207 line = fp.readline()
Łukasz Langaba702da2011-04-28 12:02:05 +02001208
Martin Panter1f106712017-01-29 23:33:27 +00001209 Instead of ``parser.readfp(fp)`` use
1210 ``parser.read_file(readline_generator(fp))``.
Łukasz Langaba702da2011-04-28 12:02:05 +02001211
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001212
1213.. data:: MAX_INTERPOLATION_DEPTH
1214
1215 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
1216 parameter is false. This is relevant only when the default *interpolation*
1217 is used.
1218
1219
1220.. _rawconfigparser-objects:
1221
1222RawConfigParser Objects
1223-----------------------
1224
Andrés Delfino3b0b90c2018-06-08 16:19:21 -03001225.. class:: RawConfigParser(defaults=None, dict_type=dict, \
Ezio Melottie927e252012-09-08 20:46:01 +03001226 allow_no_value=False, *, delimiters=('=', ':'), \
1227 comment_prefixes=('#', ';'), \
1228 inline_comment_prefixes=None, strict=True, \
1229 empty_lines_in_values=True, \
1230 default_section=configparser.DEFAULTSECT[, \
1231 interpolation])
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001232
Łukasz Langaa5fab172017-08-24 09:43:53 -07001233 Legacy variant of the :class:`ConfigParser`. It has interpolation
1234 disabled by default and allows for non-string section names, option
1235 names, and values via its unsafe ``add_section`` and ``set`` methods,
1236 as well as the legacy ``defaults=`` keyword argument handling.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001237
Inada Naoki0897e0c2019-01-31 17:53:48 +09001238 .. versionchanged:: 3.8
Andrés Delfino3b0b90c2018-06-08 16:19:21 -03001239 The default *dict_type* is :class:`dict`, since it now preserves
1240 insertion order.
1241
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001242 .. note::
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001243 Consider using :class:`ConfigParser` instead which checks types of
Łukasz Langa34cea142014-09-14 23:37:03 -07001244 the values to be stored internally. If you don't want interpolation, you
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001245 can use ``ConfigParser(interpolation=None)``.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001246
1247
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001248 .. method:: add_section(section)
1249
1250 Add a section named *section* to the instance. If a section by the given
1251 name already exists, :exc:`DuplicateSectionError` is raised. If the
1252 *default section* name is passed, :exc:`ValueError` is raised.
1253
1254 Type of *section* is not checked which lets users create non-string named
Łukasz Langa34cea142014-09-14 23:37:03 -07001255 sections. This behaviour is unsupported and may cause internal errors.
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001256
1257
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001258 .. method:: set(section, option, value)
1259
1260 If the given section exists, set the given option to the specified value;
1261 otherwise raise :exc:`NoSectionError`. While it is possible to use
1262 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters
1263 set to true) for *internal* storage of non-string values, full
1264 functionality (including interpolation and output to files) can only be
1265 achieved using string values.
1266
1267 This method lets users assign non-string values to keys internally. This
1268 behaviour is unsupported and will cause errors when attempting to write
1269 to a file or get it in non-raw mode. **Use the mapping protocol API**
1270 which does not allow such assignments to take place.
1271
1272
Łukasz Langa26d513c2010-11-10 18:57:39 +00001273Exceptions
1274----------
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001275
Łukasz Langa26d513c2010-11-10 18:57:39 +00001276.. exception:: Error
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001277
Fred Drake5a7c11f2010-11-13 05:24:17 +00001278 Base class for all other :mod:`configparser` exceptions.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001279
Georg Brandl48310cd2009-01-03 21:18:54 +00001280
Łukasz Langa26d513c2010-11-10 18:57:39 +00001281.. exception:: NoSectionError
Georg Brandl48310cd2009-01-03 21:18:54 +00001282
Łukasz Langa26d513c2010-11-10 18:57:39 +00001283 Exception raised when a specified section is not found.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001284
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001285
Łukasz Langa26d513c2010-11-10 18:57:39 +00001286.. exception:: DuplicateSectionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001287
Łukasz Langa26d513c2010-11-10 18:57:39 +00001288 Exception raised if :meth:`add_section` is called with the name of a section
1289 that is already present or in strict parsers when a section if found more
1290 than once in a single input file, string or dictionary.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001291
Łukasz Langa26d513c2010-11-10 18:57:39 +00001292 .. versionadded:: 3.2
1293 Optional ``source`` and ``lineno`` attributes and arguments to
1294 :meth:`__init__` were added.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001295
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001296
Łukasz Langa26d513c2010-11-10 18:57:39 +00001297.. exception:: DuplicateOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001298
Łukasz Langa26d513c2010-11-10 18:57:39 +00001299 Exception raised by strict parsers if a single option appears twice during
1300 reading from a single file, string or dictionary. This catches misspellings
1301 and case sensitivity-related errors, e.g. a dictionary may have two keys
1302 representing the same case-insensitive configuration key.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001303
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001304
Łukasz Langa26d513c2010-11-10 18:57:39 +00001305.. exception:: NoOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001306
Łukasz Langa26d513c2010-11-10 18:57:39 +00001307 Exception raised when a specified option is not found in the specified
1308 section.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001309
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001310
Łukasz Langa26d513c2010-11-10 18:57:39 +00001311.. exception:: InterpolationError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001312
Łukasz Langa26d513c2010-11-10 18:57:39 +00001313 Base class for exceptions raised when problems occur performing string
1314 interpolation.
Georg Brandl48310cd2009-01-03 21:18:54 +00001315
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001316
Łukasz Langa26d513c2010-11-10 18:57:39 +00001317.. exception:: InterpolationDepthError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001318
Łukasz Langa26d513c2010-11-10 18:57:39 +00001319 Exception raised when string interpolation cannot be completed because the
Georg Brandlbb27c122010-11-11 07:26:40 +00001320 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
Łukasz Langa26d513c2010-11-10 18:57:39 +00001321 :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001322
Fred Drake03c44a32010-02-19 06:08:41 +00001323
Łukasz Langa26d513c2010-11-10 18:57:39 +00001324.. exception:: InterpolationMissingOptionError
Fred Drake03c44a32010-02-19 06:08:41 +00001325
Georg Brandlbb27c122010-11-11 07:26:40 +00001326 Exception raised when an option referenced from a value does not exist.
1327 Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001328
Fred Drake03c44a32010-02-19 06:08:41 +00001329
Łukasz Langa26d513c2010-11-10 18:57:39 +00001330.. exception:: InterpolationSyntaxError
Fred Drake03c44a32010-02-19 06:08:41 +00001331
Georg Brandlbb27c122010-11-11 07:26:40 +00001332 Exception raised when the source text into which substitutions are made does
1333 not conform to the required syntax. Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001334
Łukasz Langa26d513c2010-11-10 18:57:39 +00001335
1336.. exception:: MissingSectionHeaderError
1337
Georg Brandlbb27c122010-11-11 07:26:40 +00001338 Exception raised when attempting to parse a file which has no section
1339 headers.
Łukasz Langa26d513c2010-11-10 18:57:39 +00001340
1341
1342.. exception:: ParsingError
1343
1344 Exception raised when errors occur attempting to parse a file.
1345
1346 .. versionchanged:: 3.2
1347 The ``filename`` attribute and :meth:`__init__` argument were renamed to
1348 ``source`` for consistency.
1349
Georg Brandlbb27c122010-11-11 07:26:40 +00001350
1351.. rubric:: Footnotes
1352
1353.. [1] Config parsers allow for heavy customization. If you are interested in
1354 changing the behaviour outlined by the footnote reference, consult the
1355 `Customizing Parser Behaviour`_ section.