blob: 323dd2affc78fc9a987d2927a125e7b07db9816c [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
Miss Islington (bot)f514add2021-07-13 07:34:10 -070049.. testcleanup::
50
51 import os
52 os.remove("example.ini")
53
Marco Buttub2a7c2f2017-03-02 12:02:43 +010054
Łukasz Langa26d513c2010-11-10 18:57:39 +000055Quick Start
56-----------
57
Georg Brandlbb27c122010-11-11 07:26:40 +000058Let's take a very basic configuration file that looks like this:
Łukasz Langa26d513c2010-11-10 18:57:39 +000059
Georg Brandlbb27c122010-11-11 07:26:40 +000060.. code-block:: ini
Łukasz Langa26d513c2010-11-10 18:57:39 +000061
Georg Brandlbb27c122010-11-11 07:26:40 +000062 [DEFAULT]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000063 ServerAliveInterval = 45
64 Compression = yes
65 CompressionLevel = 9
66 ForwardX11 = yes
Łukasz Langa26d513c2010-11-10 18:57:39 +000067
Georg Brandlbb27c122010-11-11 07:26:40 +000068 [bitbucket.org]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000069 User = hg
Łukasz Langa26d513c2010-11-10 18:57:39 +000070
Georg Brandlbb27c122010-11-11 07:26:40 +000071 [topsecret.server.com]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000072 Port = 50022
73 ForwardX11 = no
Łukasz Langa26d513c2010-11-10 18:57:39 +000074
Fred Drake5a7c11f2010-11-13 05:24:17 +000075The structure of INI files is described `in the following section
76<#supported-ini-file-structure>`_. Essentially, the file
Łukasz Langa26d513c2010-11-10 18:57:39 +000077consists of sections, each of which contains keys with values.
Georg Brandlbb27c122010-11-11 07:26:40 +000078:mod:`configparser` classes can read and write such files. Let's start by
Martin Pantereb995702016-07-28 01:11:04 +000079creating the above configuration file programmatically.
Łukasz Langa26d513c2010-11-10 18:57:39 +000080
Łukasz Langa26d513c2010-11-10 18:57:39 +000081.. doctest::
82
Georg Brandlbb27c122010-11-11 07:26:40 +000083 >>> import configparser
Łukasz Langa7f64c8a2010-12-16 01:16:22 +000084 >>> config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +000085 >>> config['DEFAULT'] = {'ServerAliveInterval': '45',
86 ... 'Compression': 'yes',
87 ... 'CompressionLevel': '9'}
88 >>> config['bitbucket.org'] = {}
89 >>> config['bitbucket.org']['User'] = 'hg'
90 >>> config['topsecret.server.com'] = {}
91 >>> topsecret = config['topsecret.server.com']
92 >>> topsecret['Port'] = '50022' # mutates the parser
93 >>> topsecret['ForwardX11'] = 'no' # same here
94 >>> config['DEFAULT']['ForwardX11'] = 'yes'
95 >>> with open('example.ini', 'w') as configfile:
96 ... config.write(configfile)
97 ...
Łukasz Langa26d513c2010-11-10 18:57:39 +000098
Fred Drake5a7c11f2010-11-13 05:24:17 +000099As you can see, we can treat a config parser much like a dictionary.
100There are differences, `outlined later <#mapping-protocol-access>`_, but
101the behavior is very close to what you would expect from a dictionary.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000102
Fred Drake5a7c11f2010-11-13 05:24:17 +0000103Now that we have created and saved a configuration file, let's read it
104back and explore the data it holds.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000105
Łukasz Langa26d513c2010-11-10 18:57:39 +0000106.. doctest::
107
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000108 >>> config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000109 >>> config.sections()
110 []
111 >>> config.read('example.ini')
112 ['example.ini']
113 >>> config.sections()
114 ['bitbucket.org', 'topsecret.server.com']
115 >>> 'bitbucket.org' in config
116 True
117 >>> 'bytebong.com' in config
118 False
119 >>> config['bitbucket.org']['User']
120 'hg'
121 >>> config['DEFAULT']['Compression']
122 'yes'
123 >>> topsecret = config['topsecret.server.com']
124 >>> topsecret['ForwardX11']
125 'no'
126 >>> topsecret['Port']
127 '50022'
Marco Buttub2a7c2f2017-03-02 12:02:43 +0100128 >>> for key in config['bitbucket.org']: # doctest: +SKIP
129 ... print(key)
Georg Brandlbb27c122010-11-11 07:26:40 +0000130 user
131 compressionlevel
132 serveraliveinterval
133 compression
134 forwardx11
135 >>> config['bitbucket.org']['ForwardX11']
136 'yes'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000137
Fred Drake5a7c11f2010-11-13 05:24:17 +0000138As we can see above, the API is pretty straightforward. The only bit of magic
Łukasz Langa26d513c2010-11-10 18:57:39 +0000139involves the ``DEFAULT`` section which provides default values for all other
Fred Drake5a7c11f2010-11-13 05:24:17 +0000140sections [1]_. Note also that keys in sections are
141case-insensitive and stored in lowercase [1]_.
Georg Brandlbb27c122010-11-11 07:26:40 +0000142
sblondon48b0b1b2020-09-23 14:28:58 +0200143It is possible to read several configurations into a single
144:class:`ConfigParser`, where the most recently added configuration has the
145highest priority. Any conflicting keys are taken from the more recent
146configuration while the previously existing keys are retained.
147
148.. doctest::
149
150 >>> another_config = configparser.ConfigParser()
151 >>> another_config.read('example.ini')
152 ['example.ini']
153 >>> another_config['topsecret.server.com']['Port']
154 '50022'
155 >>> another_config.read_string("[topsecret.server.com]\nPort=48484")
156 >>> another_config['topsecret.server.com']['Port']
157 '48484'
158 >>> another_config.read_dict({"topsecret.server.com": {"Port": 21212}})
159 >>> another_config['topsecret.server.com']['Port']
160 '21212'
161 >>> another_config['topsecret.server.com']['ForwardX11']
162 'no'
163
164This behaviour is equivalent to a :meth:`ConfigParser.read` call with several
165files passed to the *filenames* parameter.
166
Łukasz Langa26d513c2010-11-10 18:57:39 +0000167
168Supported Datatypes
169-------------------
170
171Config parsers do not guess datatypes of values in configuration files, always
Georg Brandlbb27c122010-11-11 07:26:40 +0000172storing them internally as strings. This means that if you need other
173datatypes, you should convert on your own:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000174
Łukasz Langa26d513c2010-11-10 18:57:39 +0000175.. doctest::
176
Georg Brandlbb27c122010-11-11 07:26:40 +0000177 >>> int(topsecret['Port'])
178 50022
179 >>> float(topsecret['CompressionLevel'])
180 9.0
Łukasz Langa26d513c2010-11-10 18:57:39 +0000181
Łukasz Langa34cea142014-09-14 23:37:03 -0700182Since this task is so common, config parsers provide a range of handy getter
183methods to handle integers, floats and booleans. The last one is the most
184interesting because simply passing the value to ``bool()`` would do no good
185since ``bool('False')`` is still ``True``. This is why config parsers also
Jesus Cea647680e2016-09-20 00:01:53 +0200186provide :meth:`~ConfigParser.getboolean`. This method is case-insensitive and
187recognizes Boolean values from ``'yes'``/``'no'``, ``'on'``/``'off'``,
Łukasz Langa34cea142014-09-14 23:37:03 -0700188``'true'``/``'false'`` and ``'1'``/``'0'`` [1]_. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000189
Łukasz Langa26d513c2010-11-10 18:57:39 +0000190.. doctest::
191
Georg Brandlbb27c122010-11-11 07:26:40 +0000192 >>> topsecret.getboolean('ForwardX11')
193 False
194 >>> config['bitbucket.org'].getboolean('ForwardX11')
195 True
196 >>> config.getboolean('bitbucket.org', 'Compression')
197 True
Łukasz Langa26d513c2010-11-10 18:57:39 +0000198
Jesus Cea647680e2016-09-20 00:01:53 +0200199Apart from :meth:`~ConfigParser.getboolean`, config parsers also
200provide equivalent :meth:`~ConfigParser.getint` and
201:meth:`~ConfigParser.getfloat` methods. You can register your own
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700202converters and customize the provided ones. [1]_
Georg Brandlbb27c122010-11-11 07:26:40 +0000203
Łukasz Langa26d513c2010-11-10 18:57:39 +0000204Fallback Values
205---------------
206
Fred Drake5a7c11f2010-11-13 05:24:17 +0000207As with a dictionary, you can use a section's :meth:`get` method to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000208provide fallback values:
209
Łukasz Langa26d513c2010-11-10 18:57:39 +0000210.. doctest::
211
Georg Brandlbb27c122010-11-11 07:26:40 +0000212 >>> topsecret.get('Port')
213 '50022'
214 >>> topsecret.get('CompressionLevel')
215 '9'
216 >>> topsecret.get('Cipher')
217 >>> topsecret.get('Cipher', '3des-cbc')
218 '3des-cbc'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000219
Fred Drake5a7c11f2010-11-13 05:24:17 +0000220Please note that default values have precedence over fallback values.
221For instance, in our example the ``'CompressionLevel'`` key was
222specified only in the ``'DEFAULT'`` section. If we try to get it from
223the section ``'topsecret.server.com'``, we will always get the default,
224even if we specify a fallback:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000225
Łukasz Langa26d513c2010-11-10 18:57:39 +0000226.. doctest::
227
Georg Brandlbb27c122010-11-11 07:26:40 +0000228 >>> topsecret.get('CompressionLevel', '3')
229 '9'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000230
231One more thing to be aware of is that the parser-level :meth:`get` method
232provides a custom, more complex interface, maintained for backwards
Fred Drake5a7c11f2010-11-13 05:24:17 +0000233compatibility. When using this method, a fallback value can be provided via
234the ``fallback`` keyword-only argument:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000235
Łukasz Langa26d513c2010-11-10 18:57:39 +0000236.. doctest::
237
Georg Brandlbb27c122010-11-11 07:26:40 +0000238 >>> config.get('bitbucket.org', 'monster',
239 ... fallback='No such things as monsters')
240 'No such things as monsters'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000241
Jesus Cea647680e2016-09-20 00:01:53 +0200242The same ``fallback`` argument can be used with the
243:meth:`~ConfigParser.getint`, :meth:`~ConfigParser.getfloat` and
244:meth:`~ConfigParser.getboolean` methods, for example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000245
Łukasz Langa26d513c2010-11-10 18:57:39 +0000246.. doctest::
247
Georg Brandlbb27c122010-11-11 07:26:40 +0000248 >>> 'BatchMode' in topsecret
249 False
250 >>> topsecret.getboolean('BatchMode', fallback=True)
251 True
252 >>> config['DEFAULT']['BatchMode'] = 'no'
253 >>> topsecret.getboolean('BatchMode', fallback=True)
254 False
255
Łukasz Langa26d513c2010-11-10 18:57:39 +0000256
257Supported INI File Structure
258----------------------------
259
Georg Brandl96a60ae2010-07-28 13:13:46 +0000260A configuration file consists of sections, each led by a ``[section]`` header,
Fred Drakea4923622010-08-09 12:52:45 +0000261followed by key/value entries separated by a specific string (``=`` or ``:`` by
Georg Brandlbb27c122010-11-11 07:26:40 +0000262default [1]_). By default, section names are case sensitive but keys are not
Fred Drake5a7c11f2010-11-13 05:24:17 +0000263[1]_. Leading and trailing whitespace is removed from keys and values.
Miss Islington (bot)a10726d2021-09-17 06:10:28 -0700264Values can be omitted if the parser is configured to allow it [1]_,
265in which case the key/value delimiter may also be left
Łukasz Langa26d513c2010-11-10 18:57:39 +0000266out. Values can also span multiple lines, as long as they are indented deeper
267than the first line of the value. Depending on the parser's mode, blank lines
268may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000269
Miss Islington (bot)a7af34d2022-02-22 10:28:34 -0800270By default, a valid section name can be any string that does not contain '\\n' or ']'.
271To change this, see :attr:`ConfigParser.SECTCRE`.
272
Fred Drake5a7c11f2010-11-13 05:24:17 +0000273Configuration files may include comments, prefixed by specific
274characters (``#`` and ``;`` by default [1]_). Comments may appear on
Łukasz Langab25a7912010-12-17 01:32:29 +0000275their own on an otherwise empty line, possibly indented. [1]_
Georg Brandl96a60ae2010-07-28 13:13:46 +0000276
Georg Brandlbb27c122010-11-11 07:26:40 +0000277For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000278
Georg Brandlbb27c122010-11-11 07:26:40 +0000279.. code-block:: ini
Georg Brandl116aa622007-08-15 14:28:22 +0000280
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000281 [Simple Values]
Łukasz Langab25a7912010-12-17 01:32:29 +0000282 key=value
283 spaces in keys=allowed
284 spaces in values=allowed as well
285 spaces around the delimiter = obviously
286 you can also use : to delimit keys from values
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000287
288 [All Values Are Strings]
289 values like this: 1000000
290 or this: 3.14159265359
291 are they treated as numbers? : no
292 integers, floats and booleans are held as: strings
293 can use the API to get converted values directly: true
Georg Brandl116aa622007-08-15 14:28:22 +0000294
Georg Brandl96a60ae2010-07-28 13:13:46 +0000295 [Multiline Values]
296 chorus: I'm a lumberjack, and I'm okay
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000297 I sleep all night and I work all day
Georg Brandl116aa622007-08-15 14:28:22 +0000298
Georg Brandl96a60ae2010-07-28 13:13:46 +0000299 [No Values]
300 key_without_value
301 empty string value here =
Georg Brandl116aa622007-08-15 14:28:22 +0000302
Łukasz Langab25a7912010-12-17 01:32:29 +0000303 [You can use comments]
304 # like this
305 ; or this
306
307 # By default only in an empty line.
308 # Inline comments can be harmful because they prevent users
309 # from using the delimiting characters as parts of values.
310 # That being said, this can be customized.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000311
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000312 [Sections Can Be Indented]
313 can_values_be_as_well = True
314 does_that_mean_anything_special = False
315 purpose = formatting for readability
316 multiline_values = are
317 handled just fine as
318 long as they are indented
319 deeper than the first line
320 of a value
321 # Did I mention we can indent comments, too?
Georg Brandl116aa622007-08-15 14:28:22 +0000322
Georg Brandl96a60ae2010-07-28 13:13:46 +0000323
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000324Interpolation of values
325-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000326
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000327On top of the core functionality, :class:`ConfigParser` supports
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000328interpolation. This means values can be preprocessed before returning them
329from ``get()`` calls.
330
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200331.. index:: single: % (percent); interpolation in configuration files
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300332
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000333.. class:: BasicInterpolation()
334
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000335 The default implementation used by :class:`ConfigParser`. It enables
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000336 values to contain format strings which refer to other values in the same
337 section, or values in the special default section [1]_. Additional default
338 values can be provided on initialization.
339
340 For example:
341
342 .. code-block:: ini
343
344 [Paths]
345 home_dir: /Users
346 my_dir: %(home_dir)s/lumberjack
347 my_pictures: %(my_dir)s/Pictures
348
Arun Persaud9a940932019-09-10 05:51:09 -0700349 [Escape]
350 gain: 80%% # use a %% to escape the % sign (% is the only character that needs to be escaped)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000351
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000352 In the example above, :class:`ConfigParser` with *interpolation* set to
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000353 ``BasicInterpolation()`` would resolve ``%(home_dir)s`` to the value of
354 ``home_dir`` (``/Users`` in this case). ``%(my_dir)s`` in effect would
355 resolve to ``/Users/lumberjack``. All interpolations are done on demand so
356 keys used in the chain of references do not have to be specified in any
357 specific order in the configuration file.
358
359 With ``interpolation`` set to ``None``, the parser would simply return
360 ``%(my_dir)s/Pictures`` as the value of ``my_pictures`` and
361 ``%(home_dir)s/lumberjack`` as the value of ``my_dir``.
362
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200363.. index:: single: $ (dollar); interpolation in configuration files
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300364
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000365.. class:: ExtendedInterpolation()
366
367 An alternative handler for interpolation which implements a more advanced
Łukasz Langa34cea142014-09-14 23:37:03 -0700368 syntax, used for instance in ``zc.buildout``. Extended interpolation is
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000369 using ``${section:option}`` to denote a value from a foreign section.
Łukasz Langa34cea142014-09-14 23:37:03 -0700370 Interpolation can span multiple levels. For convenience, if the
371 ``section:`` part is omitted, interpolation defaults to the current section
372 (and possibly the default values from the special section).
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000373
374 For example, the configuration specified above with basic interpolation,
375 would look like this with extended interpolation:
376
377 .. code-block:: ini
378
379 [Paths]
380 home_dir: /Users
381 my_dir: ${home_dir}/lumberjack
382 my_pictures: ${my_dir}/Pictures
383
Arun Persaud9a940932019-09-10 05:51:09 -0700384 [Escape]
385 cost: $$80 # use a $$ to escape the $ sign ($ is the only character that needs to be escaped)
386
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000387 Values from other sections can be fetched as well:
388
389 .. code-block:: ini
390
391 [Common]
392 home_dir: /Users
393 library_dir: /Library
394 system_dir: /System
395 macports_dir: /opt/local
396
397 [Frameworks]
398 Python: 3.2
399 path: ${Common:system_dir}/Library/Frameworks/
400
401 [Arthur]
402 nickname: Two Sheds
403 last_name: Jackson
404 my_dir: ${Common:home_dir}/twosheds
405 my_pictures: ${my_dir}/Pictures
406 python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
Georg Brandlbb27c122010-11-11 07:26:40 +0000407
Łukasz Langa26d513c2010-11-10 18:57:39 +0000408Mapping Protocol Access
409-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000410
Łukasz Langa26d513c2010-11-10 18:57:39 +0000411.. versionadded:: 3.2
Georg Brandl96a60ae2010-07-28 13:13:46 +0000412
Łukasz Langa26d513c2010-11-10 18:57:39 +0000413Mapping protocol access is a generic name for functionality that enables using
Georg Brandlbb27c122010-11-11 07:26:40 +0000414custom objects as if they were dictionaries. In case of :mod:`configparser`,
Łukasz Langa26d513c2010-11-10 18:57:39 +0000415the mapping interface implementation is using the
416``parser['section']['option']`` notation.
417
418``parser['section']`` in particular returns a proxy for the section's data in
Georg Brandlbb27c122010-11-11 07:26:40 +0000419the parser. This means that the values are not copied but they are taken from
420the original parser on demand. What's even more important is that when values
Łukasz Langa26d513c2010-11-10 18:57:39 +0000421are changed on a section proxy, they are actually mutated in the original
422parser.
423
424:mod:`configparser` objects behave as close to actual dictionaries as possible.
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300425The mapping interface is complete and adheres to the
426:class:`~collections.abc.MutableMapping` ABC.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000427However, there are a few differences that should be taken into account:
428
Georg Brandlbb27c122010-11-11 07:26:40 +0000429* By default, all keys in sections are accessible in a case-insensitive manner
430 [1]_. E.g. ``for option in parser["section"]`` yields only ``optionxform``'ed
431 option key names. This means lowercased keys by default. At the same time,
Fred Drake5a7c11f2010-11-13 05:24:17 +0000432 for a section that holds the key ``'a'``, both expressions return ``True``::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000433
Georg Brandlbb27c122010-11-11 07:26:40 +0000434 "a" in parser["section"]
435 "A" in parser["section"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000436
Georg Brandlbb27c122010-11-11 07:26:40 +0000437* All sections include ``DEFAULTSECT`` values as well which means that
438 ``.clear()`` on a section may not leave the section visibly empty. This is
Łukasz Langa26d513c2010-11-10 18:57:39 +0000439 because default values cannot be deleted from the section (because technically
Donald Stufft8b852f12014-05-20 12:58:38 -0400440 they are not there). If they are overridden in the section, deleting causes
Georg Brandlbb27c122010-11-11 07:26:40 +0000441 the default value to be visible again. Trying to delete a default value
Stéphane Wirtele483f022018-10-26 12:52:11 +0200442 causes a :exc:`KeyError`.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000443
Łukasz Langa3a8479a2012-12-31 03:38:39 +0100444* ``DEFAULTSECT`` cannot be removed from the parser:
445
Stéphane Wirtele483f022018-10-26 12:52:11 +0200446 * trying to delete it raises :exc:`ValueError`,
Łukasz Langa3a8479a2012-12-31 03:38:39 +0100447
448 * ``parser.clear()`` leaves it intact,
449
450 * ``parser.popitem()`` never returns it.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000451
Łukasz Langa71b37a52010-12-17 21:56:32 +0000452* ``parser.get(section, option, **kwargs)`` - the second argument is **not**
Łukasz Langa34cea142014-09-14 23:37:03 -0700453 a fallback value. Note however that the section-level ``get()`` methods are
Łukasz Langa71b37a52010-12-17 21:56:32 +0000454 compatible both with the mapping protocol and the classic configparser API.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000455
Łukasz Langa71b37a52010-12-17 21:56:32 +0000456* ``parser.items()`` is compatible with the mapping protocol (returns a list of
457 *section_name*, *section_proxy* pairs including the DEFAULTSECT). However,
458 this method can also be invoked with arguments: ``parser.items(section, raw,
Łukasz Langa34cea142014-09-14 23:37:03 -0700459 vars)``. The latter call returns a list of *option*, *value* pairs for
Łukasz Langa71b37a52010-12-17 21:56:32 +0000460 a specified ``section``, with all interpolations expanded (unless
461 ``raw=True`` is provided).
Łukasz Langa26d513c2010-11-10 18:57:39 +0000462
463The mapping protocol is implemented on top of the existing legacy API so that
Łukasz Langa71b37a52010-12-17 21:56:32 +0000464subclasses overriding the original interface still should have mappings working
465as expected.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000466
Georg Brandlbb27c122010-11-11 07:26:40 +0000467
Łukasz Langa26d513c2010-11-10 18:57:39 +0000468Customizing Parser Behaviour
469----------------------------
470
471There are nearly as many INI format variants as there are applications using it.
472:mod:`configparser` goes a long way to provide support for the largest sensible
Georg Brandlbb27c122010-11-11 07:26:40 +0000473set of INI styles available. The default functionality is mainly dictated by
Łukasz Langa26d513c2010-11-10 18:57:39 +0000474historical background and it's very likely that you will want to customize some
475of the features.
476
Fred Drake5a7c11f2010-11-13 05:24:17 +0000477The most common way to change the way a specific config parser works is to use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000478the :meth:`__init__` options:
479
480* *defaults*, default value: ``None``
481
482 This option accepts a dictionary of key-value pairs which will be initially
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000483 put in the ``DEFAULT`` section. This makes for an elegant way to support
484 concise configuration files that don't specify values which are the same as
485 the documented default.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000486
Fred Drake5a7c11f2010-11-13 05:24:17 +0000487 Hint: if you want to specify default values for a specific section, use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000488 :meth:`read_dict` before you read the actual file.
489
John Reese3a5b0d82018-06-05 16:31:33 -0700490* *dict_type*, default value: :class:`dict`
Łukasz Langa26d513c2010-11-10 18:57:39 +0000491
492 This option has a major impact on how the mapping protocol will behave and how
John Reese3a5b0d82018-06-05 16:31:33 -0700493 the written configuration files look. With the standard dictionary, every
494 section is stored in the order they were added to the parser. Same goes for
495 options within sections.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000496
497 An alternative dictionary type can be used for example to sort sections and
John Reese3a5b0d82018-06-05 16:31:33 -0700498 options on write-back.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000499
500 Please note: there are ways to add a set of key-value pairs in a single
Georg Brandlbb27c122010-11-11 07:26:40 +0000501 operation. When you use a regular dictionary in those operations, the order
John Reese3a5b0d82018-06-05 16:31:33 -0700502 of the keys will be ordered. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000503
Łukasz Langa26d513c2010-11-10 18:57:39 +0000504 .. doctest::
505
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000506 >>> parser = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000507 >>> parser.read_dict({'section1': {'key1': 'value1',
508 ... 'key2': 'value2',
509 ... 'key3': 'value3'},
510 ... 'section2': {'keyA': 'valueA',
511 ... 'keyB': 'valueB',
512 ... 'keyC': 'valueC'},
513 ... 'section3': {'foo': 'x',
514 ... 'bar': 'y',
515 ... 'baz': 'z'}
516 ... })
Inada Naoki0897e0c2019-01-31 17:53:48 +0900517 >>> parser.sections()
John Reese3a5b0d82018-06-05 16:31:33 -0700518 ['section1', 'section2', 'section3']
Inada Naoki0897e0c2019-01-31 17:53:48 +0900519 >>> [option for option in parser['section3']]
John Reese3a5b0d82018-06-05 16:31:33 -0700520 ['foo', 'bar', 'baz']
Łukasz Langa26d513c2010-11-10 18:57:39 +0000521
522* *allow_no_value*, default value: ``False``
523
524 Some configuration files are known to include settings without values, but
525 which otherwise conform to the syntax supported by :mod:`configparser`. The
Fred Drake5a7c11f2010-11-13 05:24:17 +0000526 *allow_no_value* parameter to the constructor can be used to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000527 indicate that such values should be accepted:
528
Łukasz Langa26d513c2010-11-10 18:57:39 +0000529 .. doctest::
530
Georg Brandlbb27c122010-11-11 07:26:40 +0000531 >>> import configparser
Łukasz Langa26d513c2010-11-10 18:57:39 +0000532
Georg Brandlbb27c122010-11-11 07:26:40 +0000533 >>> sample_config = """
534 ... [mysqld]
535 ... user = mysql
536 ... pid-file = /var/run/mysqld/mysqld.pid
537 ... skip-external-locking
538 ... old_passwords = 1
539 ... skip-bdb
Łukasz Langab25a7912010-12-17 01:32:29 +0000540 ... # we don't need ACID today
541 ... skip-innodb
Georg Brandlbb27c122010-11-11 07:26:40 +0000542 ... """
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000543 >>> config = configparser.ConfigParser(allow_no_value=True)
Georg Brandlbb27c122010-11-11 07:26:40 +0000544 >>> config.read_string(sample_config)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000545
Georg Brandlbb27c122010-11-11 07:26:40 +0000546 >>> # Settings with values are treated as before:
547 >>> config["mysqld"]["user"]
548 'mysql'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000549
Georg Brandlbb27c122010-11-11 07:26:40 +0000550 >>> # Settings without values provide None:
551 >>> config["mysqld"]["skip-bdb"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000552
Georg Brandlbb27c122010-11-11 07:26:40 +0000553 >>> # Settings which aren't specified still raise an error:
554 >>> config["mysqld"]["does-not-exist"]
555 Traceback (most recent call last):
556 ...
557 KeyError: 'does-not-exist'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000558
559* *delimiters*, default value: ``('=', ':')``
560
Łukasz Langa34cea142014-09-14 23:37:03 -0700561 Delimiters are substrings that delimit keys from values within a section.
562 The first occurrence of a delimiting substring on a line is considered
563 a delimiter. This means values (but not keys) can contain the delimiters.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000564
565 See also the *space_around_delimiters* argument to
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000566 :meth:`ConfigParser.write`.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000567
Łukasz Langab25a7912010-12-17 01:32:29 +0000568* *comment_prefixes*, default value: ``('#', ';')``
Łukasz Langa26d513c2010-11-10 18:57:39 +0000569
Łukasz Langab25a7912010-12-17 01:32:29 +0000570* *inline_comment_prefixes*, default value: ``None``
571
572 Comment prefixes are strings that indicate the start of a valid comment within
573 a config file. *comment_prefixes* are used only on otherwise empty lines
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700574 (optionally indented) whereas *inline_comment_prefixes* can be used after
575 every valid value (e.g. section names, options and empty lines as well). By
576 default inline comments are disabled and ``'#'`` and ``';'`` are used as
577 prefixes for whole line comments.
Łukasz Langab25a7912010-12-17 01:32:29 +0000578
579 .. versionchanged:: 3.2
580 In previous versions of :mod:`configparser` behaviour matched
581 ``comment_prefixes=('#',';')`` and ``inline_comment_prefixes=(';',)``.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000582
583 Please note that config parsers don't support escaping of comment prefixes so
Łukasz Langab25a7912010-12-17 01:32:29 +0000584 using *inline_comment_prefixes* may prevent users from specifying option
Łukasz Langa34cea142014-09-14 23:37:03 -0700585 values with characters used as comment prefixes. When in doubt, avoid
586 setting *inline_comment_prefixes*. In any circumstances, the only way of
587 storing comment prefix characters at the beginning of a line in multiline
588 values is to interpolate the prefix, for example::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000589
Łukasz Langab25a7912010-12-17 01:32:29 +0000590 >>> from configparser import ConfigParser, ExtendedInterpolation
591 >>> parser = ConfigParser(interpolation=ExtendedInterpolation())
592 >>> # the default BasicInterpolation could be used as well
593 >>> parser.read_string("""
594 ... [DEFAULT]
595 ... hash = #
596 ...
597 ... [hashes]
598 ... shebang =
599 ... ${hash}!/usr/bin/env python
600 ... ${hash} -*- coding: utf-8 -*-
601 ...
602 ... extensions =
603 ... enabled_extension
604 ... another_extension
605 ... #disabled_by_comment
606 ... yet_another_extension
607 ...
608 ... interpolation not necessary = if # is not at line start
609 ... even in multiline values = line #1
610 ... line #2
611 ... line #3
612 ... """)
613 >>> print(parser['hashes']['shebang'])
Marco Buttub2a7c2f2017-03-02 12:02:43 +0100614 <BLANKLINE>
Łukasz Langab25a7912010-12-17 01:32:29 +0000615 #!/usr/bin/env python
616 # -*- coding: utf-8 -*-
617 >>> print(parser['hashes']['extensions'])
Marco Buttub2a7c2f2017-03-02 12:02:43 +0100618 <BLANKLINE>
Łukasz Langab25a7912010-12-17 01:32:29 +0000619 enabled_extension
620 another_extension
621 yet_another_extension
622 >>> print(parser['hashes']['interpolation not necessary'])
623 if # is not at line start
624 >>> print(parser['hashes']['even in multiline values'])
625 line #1
626 line #2
627 line #3
628
629* *strict*, default value: ``True``
630
631 When set to ``True``, the parser will not allow for any section or option
Łukasz Langa26d513c2010-11-10 18:57:39 +0000632 duplicates while reading from a single source (using :meth:`read_file`,
Łukasz Langa34cea142014-09-14 23:37:03 -0700633 :meth:`read_string` or :meth:`read_dict`). It is recommended to use strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000634 parsers in new applications.
635
Łukasz Langab25a7912010-12-17 01:32:29 +0000636 .. versionchanged:: 3.2
637 In previous versions of :mod:`configparser` behaviour matched
638 ``strict=False``.
639
Łukasz Langa26d513c2010-11-10 18:57:39 +0000640* *empty_lines_in_values*, default value: ``True``
641
Fred Drake5a7c11f2010-11-13 05:24:17 +0000642 In config parsers, values can span multiple lines as long as they are
643 indented more than the key that holds them. By default parsers also let
644 empty lines to be parts of values. At the same time, keys can be arbitrarily
645 indented themselves to improve readability. In consequence, when
646 configuration files get big and complex, it is easy for the user to lose
647 track of the file structure. Take for instance:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000648
Georg Brandlbb27c122010-11-11 07:26:40 +0000649 .. code-block:: ini
Łukasz Langa26d513c2010-11-10 18:57:39 +0000650
Georg Brandlbb27c122010-11-11 07:26:40 +0000651 [Section]
652 key = multiline
653 value with a gotcha
Łukasz Langa26d513c2010-11-10 18:57:39 +0000654
Georg Brandlbb27c122010-11-11 07:26:40 +0000655 this = is still a part of the multiline value of 'key'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000656
Georg Brandlbb27c122010-11-11 07:26:40 +0000657 This can be especially problematic for the user to see if she's using a
658 proportional font to edit the file. That is why when your application does
659 not need values with empty lines, you should consider disallowing them. This
660 will make empty lines split keys every time. In the example above, it would
Łukasz Langa26d513c2010-11-10 18:57:39 +0000661 produce two keys, ``key`` and ``this``.
662
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000663* *default_section*, default value: ``configparser.DEFAULTSECT`` (that is:
664 ``"DEFAULT"``)
665
666 The convention of allowing a special section of default values for other
667 sections or interpolation purposes is a powerful concept of this library,
Łukasz Langa34cea142014-09-14 23:37:03 -0700668 letting users create complex declarative configurations. This section is
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000669 normally called ``"DEFAULT"`` but this can be customized to point to any
Łukasz Langa34cea142014-09-14 23:37:03 -0700670 other valid section name. Some typical values include: ``"general"`` or
671 ``"common"``. The name provided is used for recognizing default sections
672 when reading from any source and is used when writing configuration back to
673 a file. Its current value can be retrieved using the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000674 ``parser_instance.default_section`` attribute and may be modified at runtime
675 (i.e. to convert files from one format to another).
676
677* *interpolation*, default value: ``configparser.BasicInterpolation``
678
679 Interpolation behaviour may be customized by providing a custom handler
680 through the *interpolation* argument. ``None`` can be used to turn off
681 interpolation completely, ``ExtendedInterpolation()`` provides a more
Łukasz Langa34cea142014-09-14 23:37:03 -0700682 advanced variant inspired by ``zc.buildout``. More on the subject in the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000683 `dedicated documentation section <#interpolation-of-values>`_.
Łukasz Langab25a7912010-12-17 01:32:29 +0000684 :class:`RawConfigParser` has a default value of ``None``.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000685
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700686* *converters*, default value: not set
687
688 Config parsers provide option value getters that perform type conversion. By
Jesus Cea647680e2016-09-20 00:01:53 +0200689 default :meth:`~ConfigParser.getint`, :meth:`~ConfigParser.getfloat`, and
690 :meth:`~ConfigParser.getboolean` are implemented. Should other getters be
691 desirable, users may define them in a subclass or pass a dictionary where each
692 key is a name of the converter and each value is a callable implementing said
693 conversion. For instance, passing ``{'decimal': decimal.Decimal}`` would add
694 :meth:`getdecimal` on both the parser object and all section proxies. In
695 other words, it will be possible to write both
696 ``parser_instance.getdecimal('section', 'key', fallback=0)`` and
697 ``parser_instance['section'].getdecimal('key', 0)``.
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700698
699 If the converter needs to access the state of the parser, it can be
700 implemented as a method on a config parser subclass. If the name of this
701 method starts with ``get``, it will be available on all section proxies, in
702 the dict-compatible form (see the ``getdecimal()`` example above).
Łukasz Langa26d513c2010-11-10 18:57:39 +0000703
Fred Drake5a7c11f2010-11-13 05:24:17 +0000704More advanced customization may be achieved by overriding default values of
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700705these parser attributes. The defaults are defined on the classes, so they may
706be overridden by subclasses or by attribute assignment.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000707
Ned Batchelder890423f2018-10-24 19:47:01 -0400708.. attribute:: ConfigParser.BOOLEAN_STATES
Łukasz Langa26d513c2010-11-10 18:57:39 +0000709
Victor Stinnerd3ded082020-08-13 21:41:54 +0200710 By default when using :meth:`~ConfigParser.getboolean`, config parsers
711 consider the following values ``True``: ``'1'``, ``'yes'``, ``'true'``,
712 ``'on'`` and the following values ``False``: ``'0'``, ``'no'``, ``'false'``,
713 ``'off'``. You can override this by specifying a custom dictionary of strings
714 and their Boolean outcomes. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000715
Victor Stinnerd3ded082020-08-13 21:41:54 +0200716 .. doctest::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000717
Victor Stinnerd3ded082020-08-13 21:41:54 +0200718 >>> custom = configparser.ConfigParser()
719 >>> custom['section1'] = {'funky': 'nope'}
720 >>> custom['section1'].getboolean('funky')
721 Traceback (most recent call last):
722 ...
723 ValueError: Not a boolean: nope
724 >>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}
725 >>> custom['section1'].getboolean('funky')
726 False
Łukasz Langa26d513c2010-11-10 18:57:39 +0000727
Victor Stinnerd3ded082020-08-13 21:41:54 +0200728 Other typical Boolean pairs include ``accept``/``reject`` or
729 ``enabled``/``disabled``.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000730
Ned Batchelder890423f2018-10-24 19:47:01 -0400731.. method:: ConfigParser.optionxform(option)
Victor Stinnerd3ded082020-08-13 21:41:54 +0200732 :noindex:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000733
Victor Stinnerd3ded082020-08-13 21:41:54 +0200734 This method transforms option names on every read, get, or set
735 operation. The default converts the name to lowercase. This also
736 means that when a configuration file gets written, all keys will be
737 lowercase. Override this method if that's unsuitable.
738 For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000739
Victor Stinnerd3ded082020-08-13 21:41:54 +0200740 .. doctest::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000741
Victor Stinnerd3ded082020-08-13 21:41:54 +0200742 >>> config = """
743 ... [Section1]
744 ... Key = Value
745 ...
746 ... [Section2]
747 ... AnotherKey = Value
748 ... """
749 >>> typical = configparser.ConfigParser()
750 >>> typical.read_string(config)
751 >>> list(typical['Section1'].keys())
752 ['key']
753 >>> list(typical['Section2'].keys())
754 ['anotherkey']
755 >>> custom = configparser.RawConfigParser()
756 >>> custom.optionxform = lambda option: option
757 >>> custom.read_string(config)
758 >>> list(custom['Section1'].keys())
759 ['Key']
760 >>> list(custom['Section2'].keys())
761 ['AnotherKey']
Georg Brandlbb27c122010-11-11 07:26:40 +0000762
Victor Stinnerd3ded082020-08-13 21:41:54 +0200763 .. note::
764 The optionxform function transforms option names to a canonical form.
765 This should be an idempotent function: if the name is already in
766 canonical form, it should be returned unchanged.
Inada Naoki04694a32019-04-02 18:08:46 +0900767
768
Ned Batchelder890423f2018-10-24 19:47:01 -0400769.. attribute:: ConfigParser.SECTCRE
Łukasz Langa66c908e2011-01-28 11:57:30 +0000770
Victor Stinnerd3ded082020-08-13 21:41:54 +0200771 A compiled regular expression used to parse section headers. The default
772 matches ``[section]`` to the name ``"section"``. Whitespace is considered
773 part of the section name, thus ``[ larch ]`` will be read as a section of
774 name ``" larch "``. Override this attribute if that's unsuitable. For
775 example:
Łukasz Langa66c908e2011-01-28 11:57:30 +0000776
Victor Stinnerd3ded082020-08-13 21:41:54 +0200777 .. doctest::
Łukasz Langa66c908e2011-01-28 11:57:30 +0000778
Victor Stinnerd3ded082020-08-13 21:41:54 +0200779 >>> import re
780 >>> config = """
781 ... [Section 1]
782 ... option = value
783 ...
784 ... [ Section 2 ]
785 ... another = val
786 ... """
787 >>> typical = configparser.ConfigParser()
788 >>> typical.read_string(config)
789 >>> typical.sections()
790 ['Section 1', ' Section 2 ']
791 >>> custom = configparser.ConfigParser()
792 >>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]")
793 >>> custom.read_string(config)
794 >>> custom.sections()
795 ['Section 1', 'Section 2']
Łukasz Langa66c908e2011-01-28 11:57:30 +0000796
Victor Stinnerd3ded082020-08-13 21:41:54 +0200797 .. note::
Łukasz Langa66c908e2011-01-28 11:57:30 +0000798
Victor Stinnerd3ded082020-08-13 21:41:54 +0200799 While ConfigParser objects also use an ``OPTCRE`` attribute for recognizing
800 option lines, it's not recommended to override it because that would
801 interfere with constructor options *allow_no_value* and *delimiters*.
Łukasz Langa66c908e2011-01-28 11:57:30 +0000802
Łukasz Langa26d513c2010-11-10 18:57:39 +0000803
804Legacy API Examples
805-------------------
806
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000807Mainly because of backwards compatibility concerns, :mod:`configparser`
808provides also a legacy API with explicit ``get``/``set`` methods. While there
809are valid use cases for the methods outlined below, mapping protocol access is
810preferred for new projects. The legacy API is at times more advanced,
811low-level and downright counterintuitive.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000812
813An example of writing to a configuration file::
814
815 import configparser
816
817 config = configparser.RawConfigParser()
818
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000819 # Please note that using RawConfigParser's set functions, you can assign
820 # non-string values to keys internally, but will receive an error when
821 # attempting to write to a file or when you get it in non-raw mode. Setting
822 # values using the mapping protocol or ConfigParser's set() does not allow
823 # such assignments to take place.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000824 config.add_section('Section1')
R David Murray1a1883d2012-09-29 14:40:23 -0400825 config.set('Section1', 'an_int', '15')
826 config.set('Section1', 'a_bool', 'true')
827 config.set('Section1', 'a_float', '3.1415')
Łukasz Langa26d513c2010-11-10 18:57:39 +0000828 config.set('Section1', 'baz', 'fun')
829 config.set('Section1', 'bar', 'Python')
830 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
831
832 # Writing our configuration file to 'example.cfg'
833 with open('example.cfg', 'w') as configfile:
834 config.write(configfile)
835
836An example of reading the configuration file again::
837
838 import configparser
839
840 config = configparser.RawConfigParser()
841 config.read('example.cfg')
842
843 # getfloat() raises an exception if the value is not a float
844 # getint() and getboolean() also do this for their respective types
R David Murray1a1883d2012-09-29 14:40:23 -0400845 a_float = config.getfloat('Section1', 'a_float')
846 an_int = config.getint('Section1', 'an_int')
847 print(a_float + an_int)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000848
849 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
850 # This is because we are using a RawConfigParser().
R David Murray1a1883d2012-09-29 14:40:23 -0400851 if config.getboolean('Section1', 'a_bool'):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000852 print(config.get('Section1', 'foo'))
853
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000854To get interpolation, use :class:`ConfigParser`::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000855
856 import configparser
857
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000858 cfg = configparser.ConfigParser()
Łukasz Langa26d513c2010-11-10 18:57:39 +0000859 cfg.read('example.cfg')
860
Éric Araujo941afed2011-09-01 02:47:34 +0200861 # Set the optional *raw* argument of get() to True if you wish to disable
Łukasz Langa26d513c2010-11-10 18:57:39 +0000862 # interpolation in a single get operation.
Serhiy Storchakadba90392016-05-10 12:01:23 +0300863 print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!"
864 print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!"
Łukasz Langa26d513c2010-11-10 18:57:39 +0000865
Éric Araujo941afed2011-09-01 02:47:34 +0200866 # The optional *vars* argument is a dict with members that will take
Łukasz Langa26d513c2010-11-10 18:57:39 +0000867 # precedence in interpolation.
868 print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation',
Serhiy Storchakadba90392016-05-10 12:01:23 +0300869 'baz': 'evil'}))
Łukasz Langa26d513c2010-11-10 18:57:39 +0000870
Éric Araujo941afed2011-09-01 02:47:34 +0200871 # The optional *fallback* argument can be used to provide a fallback value
Łukasz Langa26d513c2010-11-10 18:57:39 +0000872 print(cfg.get('Section1', 'foo'))
873 # -> "Python is fun!"
874
875 print(cfg.get('Section1', 'foo', fallback='Monty is not.'))
876 # -> "Python is fun!"
877
878 print(cfg.get('Section1', 'monster', fallback='No such things as monsters.'))
879 # -> "No such things as monsters."
880
881 # A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError
882 # but we can also use:
883
884 print(cfg.get('Section1', 'monster', fallback=None))
885 # -> None
886
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000887Default values are available in both types of ConfigParsers. They are used in
888interpolation if an option used is not defined elsewhere. ::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000889
890 import configparser
891
892 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000893 config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'})
Łukasz Langa26d513c2010-11-10 18:57:39 +0000894 config.read('example.cfg')
895
Serhiy Storchakadba90392016-05-10 12:01:23 +0300896 print(config.get('Section1', 'foo')) # -> "Python is fun!"
Łukasz Langa26d513c2010-11-10 18:57:39 +0000897 config.remove_option('Section1', 'bar')
898 config.remove_option('Section1', 'baz')
Serhiy Storchakadba90392016-05-10 12:01:23 +0300899 print(config.get('Section1', 'foo')) # -> "Life is hard!"
Łukasz Langa26d513c2010-11-10 18:57:39 +0000900
Georg Brandlbb27c122010-11-11 07:26:40 +0000901
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000902.. _configparser-objects:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000903
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000904ConfigParser Objects
905--------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000906
Andrés Delfino3b0b90c2018-06-08 16:19:21 -0300907.. 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 +0000908
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000909 The main configuration parser. When *defaults* is given, it is initialized
Georg Brandl96a60ae2010-07-28 13:13:46 +0000910 into the dictionary of intrinsic defaults. When *dict_type* is given, it
911 will be used to create the dictionary objects for the list of sections, for
912 the options within a section, and for the default values.
913
Fred Drake5a7c11f2010-11-13 05:24:17 +0000914 When *delimiters* is given, it is used as the set of substrings that
Georg Brandl96a60ae2010-07-28 13:13:46 +0000915 divide keys from values. When *comment_prefixes* is given, it will be used
Łukasz Langab25a7912010-12-17 01:32:29 +0000916 as the set of substrings that prefix comments in otherwise empty lines.
Łukasz Langa34cea142014-09-14 23:37:03 -0700917 Comments can be indented. When *inline_comment_prefixes* is given, it will
918 be used as the set of substrings that prefix comments in non-empty lines.
Łukasz Langab25a7912010-12-17 01:32:29 +0000919
Łukasz Langab25a7912010-12-17 01:32:29 +0000920 When *strict* is ``True`` (the default), the parser won't allow for
Fred Drakea4923622010-08-09 12:52:45 +0000921 any section or option duplicates while reading from a single source (file,
922 string or dictionary), raising :exc:`DuplicateSectionError` or
Fred Drake5a7c11f2010-11-13 05:24:17 +0000923 :exc:`DuplicateOptionError`. When *empty_lines_in_values* is ``False``
Fred Drakea4923622010-08-09 12:52:45 +0000924 (default: ``True``), each empty line marks the end of an option. Otherwise,
925 internal empty lines of a multiline option are kept as part of the value.
926 When *allow_no_value* is ``True`` (default: ``False``), options without
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000927 values are accepted; the value held for these is ``None`` and they are
928 serialized without the trailing delimiter.
Fred Drake03c44a32010-02-19 06:08:41 +0000929
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000930 When *default_section* is given, it specifies the name for the special
931 section holding default values for other sections and interpolation purposes
Łukasz Langa34cea142014-09-14 23:37:03 -0700932 (normally named ``"DEFAULT"``). This value can be retrieved and changed on
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000933 runtime using the ``default_section`` instance attribute.
934
935 Interpolation behaviour may be customized by providing a custom handler
936 through the *interpolation* argument. ``None`` can be used to turn off
937 interpolation completely, ``ExtendedInterpolation()`` provides a more
Łukasz Langa34cea142014-09-14 23:37:03 -0700938 advanced variant inspired by ``zc.buildout``. More on the subject in the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000939 `dedicated documentation section <#interpolation-of-values>`_.
940
941 All option names used in interpolation will be passed through the
942 :meth:`optionxform` method just like any other option name reference. For
943 example, using the default implementation of :meth:`optionxform` (which
944 converts option names to lower case), the values ``foo %(bar)s`` and ``foo
945 %(BAR)s`` are equivalent.
Georg Brandl116aa622007-08-15 14:28:22 +0000946
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700947 When *converters* is given, it should be a dictionary where each key
948 represents the name of a type converter and each value is a callable
949 implementing the conversion from string to the desired datatype. Every
950 converter gets its own corresponding :meth:`get*()` method on the parser
951 object and section proxies.
952
Raymond Hettinger231b7f12009-03-03 00:23:19 +0000953 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +0000954 The default *dict_type* is :class:`collections.OrderedDict`.
955
Fred Drake03c44a32010-02-19 06:08:41 +0000956 .. versionchanged:: 3.2
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000957 *allow_no_value*, *delimiters*, *comment_prefixes*, *strict*,
958 *empty_lines_in_values*, *default_section* and *interpolation* were
959 added.
Georg Brandl116aa622007-08-15 14:28:22 +0000960
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700961 .. versionchanged:: 3.5
962 The *converters* argument was added.
963
Łukasz Langaea579232017-08-21 16:23:38 -0700964 .. versionchanged:: 3.7
965 The *defaults* argument is read with :meth:`read_dict()`,
966 providing consistent behavior across the parser: non-string
967 keys and values are implicitly converted to strings.
968
Inada Naoki0897e0c2019-01-31 17:53:48 +0900969 .. versionchanged:: 3.8
Andrés Delfino3b0b90c2018-06-08 16:19:21 -0300970 The default *dict_type* is :class:`dict`, since it now preserves
971 insertion order.
Fred Drake03c44a32010-02-19 06:08:41 +0000972
Georg Brandlbb27c122010-11-11 07:26:40 +0000973 .. method:: defaults()
Georg Brandl116aa622007-08-15 14:28:22 +0000974
Georg Brandlbb27c122010-11-11 07:26:40 +0000975 Return a dictionary containing the instance-wide defaults.
Georg Brandl116aa622007-08-15 14:28:22 +0000976
977
Georg Brandlbb27c122010-11-11 07:26:40 +0000978 .. method:: sections()
Georg Brandl116aa622007-08-15 14:28:22 +0000979
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000980 Return a list of the sections available; the *default section* is not
981 included in the list.
Georg Brandl116aa622007-08-15 14:28:22 +0000982
983
Georg Brandlbb27c122010-11-11 07:26:40 +0000984 .. method:: add_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000985
Georg Brandlbb27c122010-11-11 07:26:40 +0000986 Add a section named *section* to the instance. If a section by the given
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000987 name already exists, :exc:`DuplicateSectionError` is raised. If the
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000988 *default section* name is passed, :exc:`ValueError` is raised. The name
989 of the section must be a string; if not, :exc:`TypeError` is raised.
990
991 .. versionchanged:: 3.2
992 Non-string section names raise :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000993
Georg Brandl116aa622007-08-15 14:28:22 +0000994
Georg Brandlbb27c122010-11-11 07:26:40 +0000995 .. method:: has_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000996
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000997 Indicates whether the named *section* is present in the configuration.
998 The *default section* is not acknowledged.
Georg Brandl116aa622007-08-15 14:28:22 +0000999
Georg Brandl116aa622007-08-15 14:28:22 +00001000
Georg Brandlbb27c122010-11-11 07:26:40 +00001001 .. method:: options(section)
Georg Brandl116aa622007-08-15 14:28:22 +00001002
Georg Brandlbb27c122010-11-11 07:26:40 +00001003 Return a list of options available in the specified *section*.
Georg Brandl116aa622007-08-15 14:28:22 +00001004
Georg Brandl116aa622007-08-15 14:28:22 +00001005
Georg Brandlbb27c122010-11-11 07:26:40 +00001006 .. method:: has_option(section, option)
Georg Brandl116aa622007-08-15 14:28:22 +00001007
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001008 If the given *section* exists, and contains the given *option*, return
Łukasz Langa34cea142014-09-14 23:37:03 -07001009 :const:`True`; otherwise return :const:`False`. If the specified
Łukasz Langa71b37a52010-12-17 21:56:32 +00001010 *section* is :const:`None` or an empty string, DEFAULT is assumed.
Georg Brandl116aa622007-08-15 14:28:22 +00001011
Georg Brandl116aa622007-08-15 14:28:22 +00001012
Georg Brandlbb27c122010-11-11 07:26:40 +00001013 .. method:: read(filenames, encoding=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001014
Zackery Spytze45473e2018-09-29 10:15:55 -06001015 Attempt to read and parse an iterable of filenames, returning a list of
David Ellis85b8d012017-03-03 17:14:27 +00001016 filenames which were successfully parsed.
1017
Vincent Michele3148532017-11-02 13:47:04 +01001018 If *filenames* is a string, a :class:`bytes` object or a
1019 :term:`path-like object`, it is treated as
David Ellis85b8d012017-03-03 17:14:27 +00001020 a single filename. If a file named in *filenames* cannot be opened, that
Zackery Spytze45473e2018-09-29 10:15:55 -06001021 file will be ignored. This is designed so that you can specify an
1022 iterable of potential configuration file locations (for example, the
1023 current directory, the user's home directory, and some system-wide
1024 directory), and all existing configuration files in the iterable will be
1025 read.
David Ellis85b8d012017-03-03 17:14:27 +00001026
1027 If none of the named files exist, the :class:`ConfigParser`
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001028 instance will contain an empty dataset. An application which requires
1029 initial values to be loaded from a file should load the required file or
1030 files using :meth:`read_file` before calling :meth:`read` for any
1031 optional files::
Georg Brandl116aa622007-08-15 14:28:22 +00001032
Georg Brandlbb27c122010-11-11 07:26:40 +00001033 import configparser, os
Georg Brandl8dcaa732010-07-29 12:17:40 +00001034
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001035 config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +00001036 config.read_file(open('defaults.cfg'))
1037 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
1038 encoding='cp1250')
Georg Brandl116aa622007-08-15 14:28:22 +00001039
Georg Brandlbb27c122010-11-11 07:26:40 +00001040 .. versionadded:: 3.2
1041 The *encoding* parameter. Previously, all files were read using the
1042 default encoding for :func:`open`.
Georg Brandl116aa622007-08-15 14:28:22 +00001043
David Ellis85b8d012017-03-03 17:14:27 +00001044 .. versionadded:: 3.6.1
1045 The *filenames* parameter accepts a :term:`path-like object`.
1046
Vincent Michele3148532017-11-02 13:47:04 +01001047 .. versionadded:: 3.7
1048 The *filenames* parameter accepts a :class:`bytes` object.
1049
Georg Brandl116aa622007-08-15 14:28:22 +00001050
Georg Brandlbb27c122010-11-11 07:26:40 +00001051 .. method:: read_file(f, source=None)
Georg Brandl73753d32009-09-22 13:53:14 +00001052
Łukasz Langadaab1c82011-04-27 18:10:05 +02001053 Read and parse configuration data from *f* which must be an iterable
Łukasz Langaba702da2011-04-28 12:02:05 +02001054 yielding Unicode strings (for example files opened in text mode).
Georg Brandl116aa622007-08-15 14:28:22 +00001055
Georg Brandlbb27c122010-11-11 07:26:40 +00001056 Optional argument *source* specifies the name of the file being read. If
Fred Drake5a7c11f2010-11-13 05:24:17 +00001057 not given and *f* has a :attr:`name` attribute, that is used for
1058 *source*; the default is ``'<???>'``.
Fred Drakea4923622010-08-09 12:52:45 +00001059
Georg Brandlbb27c122010-11-11 07:26:40 +00001060 .. versionadded:: 3.2
Łukasz Langa43ae6192011-04-27 18:13:42 +02001061 Replaces :meth:`readfp`.
1062
Georg Brandlbb27c122010-11-11 07:26:40 +00001063 .. method:: read_string(string, source='<string>')
Fred Drakea4923622010-08-09 12:52:45 +00001064
Fred Drake5a7c11f2010-11-13 05:24:17 +00001065 Parse configuration data from a string.
Fred Drakea4923622010-08-09 12:52:45 +00001066
Fred Drake5a7c11f2010-11-13 05:24:17 +00001067 Optional argument *source* specifies a context-specific name of the
1068 string passed. If not given, ``'<string>'`` is used. This should
1069 commonly be a filesystem path or a URL.
Fred Drakea4923622010-08-09 12:52:45 +00001070
Georg Brandlbb27c122010-11-11 07:26:40 +00001071 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +00001072
Fred Drakea4923622010-08-09 12:52:45 +00001073
Georg Brandlbb27c122010-11-11 07:26:40 +00001074 .. method:: read_dict(dictionary, source='<dict>')
Fred Drakea4923622010-08-09 12:52:45 +00001075
Łukasz Langa71b37a52010-12-17 21:56:32 +00001076 Load configuration from any object that provides a dict-like ``items()``
1077 method. Keys are section names, values are dictionaries with keys and
1078 values that should be present in the section. If the used dictionary
1079 type preserves order, sections and their keys will be added in order.
1080 Values are automatically converted to strings.
Fred Drakea4923622010-08-09 12:52:45 +00001081
Georg Brandlbb27c122010-11-11 07:26:40 +00001082 Optional argument *source* specifies a context-specific name of the
1083 dictionary passed. If not given, ``<dict>`` is used.
Georg Brandl116aa622007-08-15 14:28:22 +00001084
Łukasz Langa71b37a52010-12-17 21:56:32 +00001085 This method can be used to copy state between parsers.
1086
Georg Brandlbb27c122010-11-11 07:26:40 +00001087 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +00001088
Georg Brandl116aa622007-08-15 14:28:22 +00001089
Ezio Melottie927e252012-09-08 20:46:01 +03001090 .. method:: get(section, option, *, raw=False, vars=None[, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +00001091
Georg Brandlbb27c122010-11-11 07:26:40 +00001092 Get an *option* value for the named *section*. If *vars* is provided, it
1093 must be a dictionary. The *option* is looked up in *vars* (if provided),
1094 *section*, and in *DEFAULTSECT* in that order. If the key is not found
1095 and *fallback* is provided, it is used as a fallback value. ``None`` can
1096 be provided as a *fallback* value.
Georg Brandl470a1232010-07-29 14:17:12 +00001097
Georg Brandlbb27c122010-11-11 07:26:40 +00001098 All the ``'%'`` interpolations are expanded in the return values, unless
1099 the *raw* argument is true. Values for interpolation keys are looked up
1100 in the same manner as the option.
Georg Brandl116aa622007-08-15 14:28:22 +00001101
Georg Brandlbb27c122010-11-11 07:26:40 +00001102 .. versionchanged:: 3.2
1103 Arguments *raw*, *vars* and *fallback* are keyword only to protect
1104 users from trying to use the third argument as the *fallback* fallback
1105 (especially when using the mapping protocol).
Georg Brandl116aa622007-08-15 14:28:22 +00001106
Łukasz Langa26d513c2010-11-10 18:57:39 +00001107
Ezio Melottie927e252012-09-08 20:46:01 +03001108 .. method:: getint(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001109
Georg Brandlbb27c122010-11-11 07:26:40 +00001110 A convenience method which coerces the *option* in the specified *section*
1111 to an integer. See :meth:`get` for explanation of *raw*, *vars* and
1112 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001113
1114
Ezio Melottie927e252012-09-08 20:46:01 +03001115 .. method:: getfloat(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001116
Georg Brandlbb27c122010-11-11 07:26:40 +00001117 A convenience method which coerces the *option* in the specified *section*
1118 to a floating point number. See :meth:`get` for explanation of *raw*,
1119 *vars* and *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001120
1121
Ezio Melottie927e252012-09-08 20:46:01 +03001122 .. method:: getboolean(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001123
Georg Brandlbb27c122010-11-11 07:26:40 +00001124 A convenience method which coerces the *option* in the specified *section*
1125 to a Boolean value. Note that the accepted values for the option are
Fred Drake5a7c11f2010-11-13 05:24:17 +00001126 ``'1'``, ``'yes'``, ``'true'``, and ``'on'``, which cause this method to
1127 return ``True``, and ``'0'``, ``'no'``, ``'false'``, and ``'off'``, which
Georg Brandlbb27c122010-11-11 07:26:40 +00001128 cause it to return ``False``. These string values are checked in a
1129 case-insensitive manner. Any other value will cause it to raise
1130 :exc:`ValueError`. See :meth:`get` for explanation of *raw*, *vars* and
1131 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001132
1133
Ezio Melottie0add762012-09-14 06:32:35 +03001134 .. method:: items(raw=False, vars=None)
1135 items(section, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001136
Łukasz Langa71b37a52010-12-17 21:56:32 +00001137 When *section* is not given, return a list of *section_name*,
1138 *section_proxy* pairs, including DEFAULTSECT.
1139
1140 Otherwise, return a list of *name*, *value* pairs for the options in the
1141 given *section*. Optional arguments have the same meaning as for the
Georg Brandlbb27c122010-11-11 07:26:40 +00001142 :meth:`get` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001143
Andrés Delfino4acc1402018-06-08 21:20:05 -03001144 .. versionchanged:: 3.8
1145 Items present in *vars* no longer appear in the result. The previous
1146 behaviour mixed actual parser options with variables provided for
1147 interpolation.
Chris Bradburye5008392018-04-23 21:56:39 +01001148
Georg Brandl116aa622007-08-15 14:28:22 +00001149
Georg Brandlbb27c122010-11-11 07:26:40 +00001150 .. method:: set(section, option, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001151
Georg Brandlbb27c122010-11-11 07:26:40 +00001152 If the given section exists, set the given option to the specified value;
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001153 otherwise raise :exc:`NoSectionError`. *option* and *value* must be
1154 strings; if not, :exc:`TypeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001155
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001156
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001157 .. method:: write(fileobject, space_around_delimiters=True)
1158
1159 Write a representation of the configuration to the specified :term:`file
1160 object`, which must be opened in text mode (accepting strings). This
1161 representation can be parsed by a future :meth:`read` call. If
1162 *space_around_delimiters* is true, delimiters between
1163 keys and values are surrounded by spaces.
1164
Łukasz Langa4d17c932021-05-18 19:03:09 +02001165 .. note::
1166
1167 Comments in the original configuration file are not preserved when
1168 writing the configuration back.
1169 What is considered a comment, depends on the given values for
1170 *comment_prefix* and *inline_comment_prefix*.
1171
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001172
1173 .. method:: remove_option(section, option)
1174
1175 Remove the specified *option* from the specified *section*. If the
1176 section does not exist, raise :exc:`NoSectionError`. If the option
1177 existed to be removed, return :const:`True`; otherwise return
1178 :const:`False`.
1179
1180
1181 .. method:: remove_section(section)
1182
1183 Remove the specified *section* from the configuration. If the section in
1184 fact existed, return ``True``. Otherwise return ``False``.
1185
1186
1187 .. method:: optionxform(option)
1188
1189 Transforms the option name *option* as found in an input file or as passed
1190 in by client code to the form that should be used in the internal
1191 structures. The default implementation returns a lower-case version of
1192 *option*; subclasses may override this or client code can set an attribute
1193 of this name on instances to affect this behavior.
1194
1195 You don't need to subclass the parser to use this method, you can also
1196 set it on an instance, to a function that takes a string argument and
1197 returns a string. Setting it to ``str``, for example, would make option
1198 names case sensitive::
1199
1200 cfgparser = ConfigParser()
1201 cfgparser.optionxform = str
1202
1203 Note that when reading configuration files, whitespace around the option
1204 names is stripped before :meth:`optionxform` is called.
1205
1206
1207 .. method:: readfp(fp, filename=None)
1208
1209 .. deprecated:: 3.2
1210 Use :meth:`read_file` instead.
1211
Łukasz Langaba702da2011-04-28 12:02:05 +02001212 .. versionchanged:: 3.2
Martin Panter1f106712017-01-29 23:33:27 +00001213 :meth:`readfp` now iterates on *fp* instead of calling ``fp.readline()``.
Łukasz Langaba702da2011-04-28 12:02:05 +02001214
1215 For existing code calling :meth:`readfp` with arguments which don't
1216 support iteration, the following generator may be used as a wrapper
1217 around the file-like object::
1218
Martin Panter1f106712017-01-29 23:33:27 +00001219 def readline_generator(fp):
1220 line = fp.readline()
Łukasz Langaba702da2011-04-28 12:02:05 +02001221 while line:
1222 yield line
Martin Panter1f106712017-01-29 23:33:27 +00001223 line = fp.readline()
Łukasz Langaba702da2011-04-28 12:02:05 +02001224
Martin Panter1f106712017-01-29 23:33:27 +00001225 Instead of ``parser.readfp(fp)`` use
1226 ``parser.read_file(readline_generator(fp))``.
Łukasz Langaba702da2011-04-28 12:02:05 +02001227
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001228
1229.. data:: MAX_INTERPOLATION_DEPTH
1230
1231 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
1232 parameter is false. This is relevant only when the default *interpolation*
1233 is used.
1234
1235
1236.. _rawconfigparser-objects:
1237
1238RawConfigParser Objects
1239-----------------------
1240
Andrés Delfino3b0b90c2018-06-08 16:19:21 -03001241.. class:: RawConfigParser(defaults=None, dict_type=dict, \
Ezio Melottie927e252012-09-08 20:46:01 +03001242 allow_no_value=False, *, delimiters=('=', ':'), \
1243 comment_prefixes=('#', ';'), \
1244 inline_comment_prefixes=None, strict=True, \
1245 empty_lines_in_values=True, \
1246 default_section=configparser.DEFAULTSECT[, \
1247 interpolation])
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001248
Łukasz Langaa5fab172017-08-24 09:43:53 -07001249 Legacy variant of the :class:`ConfigParser`. It has interpolation
1250 disabled by default and allows for non-string section names, option
1251 names, and values via its unsafe ``add_section`` and ``set`` methods,
1252 as well as the legacy ``defaults=`` keyword argument handling.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001253
Inada Naoki0897e0c2019-01-31 17:53:48 +09001254 .. versionchanged:: 3.8
Andrés Delfino3b0b90c2018-06-08 16:19:21 -03001255 The default *dict_type* is :class:`dict`, since it now preserves
1256 insertion order.
1257
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001258 .. note::
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001259 Consider using :class:`ConfigParser` instead which checks types of
Łukasz Langa34cea142014-09-14 23:37:03 -07001260 the values to be stored internally. If you don't want interpolation, you
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001261 can use ``ConfigParser(interpolation=None)``.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001262
1263
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001264 .. method:: add_section(section)
1265
1266 Add a section named *section* to the instance. If a section by the given
1267 name already exists, :exc:`DuplicateSectionError` is raised. If the
1268 *default section* name is passed, :exc:`ValueError` is raised.
1269
1270 Type of *section* is not checked which lets users create non-string named
Łukasz Langa34cea142014-09-14 23:37:03 -07001271 sections. This behaviour is unsupported and may cause internal errors.
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001272
1273
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001274 .. method:: set(section, option, value)
1275
1276 If the given section exists, set the given option to the specified value;
1277 otherwise raise :exc:`NoSectionError`. While it is possible to use
1278 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters
1279 set to true) for *internal* storage of non-string values, full
1280 functionality (including interpolation and output to files) can only be
1281 achieved using string values.
1282
1283 This method lets users assign non-string values to keys internally. This
1284 behaviour is unsupported and will cause errors when attempting to write
1285 to a file or get it in non-raw mode. **Use the mapping protocol API**
1286 which does not allow such assignments to take place.
1287
1288
Łukasz Langa26d513c2010-11-10 18:57:39 +00001289Exceptions
1290----------
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001291
Łukasz Langa26d513c2010-11-10 18:57:39 +00001292.. exception:: Error
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001293
Fred Drake5a7c11f2010-11-13 05:24:17 +00001294 Base class for all other :mod:`configparser` exceptions.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001295
Georg Brandl48310cd2009-01-03 21:18:54 +00001296
Łukasz Langa26d513c2010-11-10 18:57:39 +00001297.. exception:: NoSectionError
Georg Brandl48310cd2009-01-03 21:18:54 +00001298
Łukasz Langa26d513c2010-11-10 18:57:39 +00001299 Exception raised when a specified section is not found.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001300
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001301
Łukasz Langa26d513c2010-11-10 18:57:39 +00001302.. exception:: DuplicateSectionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001303
Łukasz Langa26d513c2010-11-10 18:57:39 +00001304 Exception raised if :meth:`add_section` is called with the name of a section
1305 that is already present or in strict parsers when a section if found more
1306 than once in a single input file, string or dictionary.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001307
Łukasz Langa26d513c2010-11-10 18:57:39 +00001308 .. versionadded:: 3.2
1309 Optional ``source`` and ``lineno`` attributes and arguments to
1310 :meth:`__init__` were added.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001311
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001312
Łukasz Langa26d513c2010-11-10 18:57:39 +00001313.. exception:: DuplicateOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001314
Łukasz Langa26d513c2010-11-10 18:57:39 +00001315 Exception raised by strict parsers if a single option appears twice during
1316 reading from a single file, string or dictionary. This catches misspellings
1317 and case sensitivity-related errors, e.g. a dictionary may have two keys
1318 representing the same case-insensitive configuration key.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001319
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001320
Łukasz Langa26d513c2010-11-10 18:57:39 +00001321.. exception:: NoOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001322
Łukasz Langa26d513c2010-11-10 18:57:39 +00001323 Exception raised when a specified option is not found in the specified
1324 section.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001325
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001326
Łukasz Langa26d513c2010-11-10 18:57:39 +00001327.. exception:: InterpolationError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001328
Łukasz Langa26d513c2010-11-10 18:57:39 +00001329 Base class for exceptions raised when problems occur performing string
1330 interpolation.
Georg Brandl48310cd2009-01-03 21:18:54 +00001331
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001332
Łukasz Langa26d513c2010-11-10 18:57:39 +00001333.. exception:: InterpolationDepthError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001334
Łukasz Langa26d513c2010-11-10 18:57:39 +00001335 Exception raised when string interpolation cannot be completed because the
Georg Brandlbb27c122010-11-11 07:26:40 +00001336 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
Łukasz Langa26d513c2010-11-10 18:57:39 +00001337 :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001338
Fred Drake03c44a32010-02-19 06:08:41 +00001339
Łukasz Langa26d513c2010-11-10 18:57:39 +00001340.. exception:: InterpolationMissingOptionError
Fred Drake03c44a32010-02-19 06:08:41 +00001341
Georg Brandlbb27c122010-11-11 07:26:40 +00001342 Exception raised when an option referenced from a value does not exist.
1343 Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001344
Fred Drake03c44a32010-02-19 06:08:41 +00001345
Łukasz Langa26d513c2010-11-10 18:57:39 +00001346.. exception:: InterpolationSyntaxError
Fred Drake03c44a32010-02-19 06:08:41 +00001347
Georg Brandlbb27c122010-11-11 07:26:40 +00001348 Exception raised when the source text into which substitutions are made does
1349 not conform to the required syntax. Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001350
Łukasz Langa26d513c2010-11-10 18:57:39 +00001351
1352.. exception:: MissingSectionHeaderError
1353
Georg Brandlbb27c122010-11-11 07:26:40 +00001354 Exception raised when attempting to parse a file which has no section
1355 headers.
Łukasz Langa26d513c2010-11-10 18:57:39 +00001356
1357
1358.. exception:: ParsingError
1359
1360 Exception raised when errors occur attempting to parse a file.
1361
1362 .. versionchanged:: 3.2
1363 The ``filename`` attribute and :meth:`__init__` argument were renamed to
1364 ``source`` for consistency.
1365
Georg Brandlbb27c122010-11-11 07:26:40 +00001366
1367.. rubric:: Footnotes
1368
1369.. [1] Config parsers allow for heavy customization. If you are interested in
1370 changing the behaviour outlined by the footnote reference, consult the
1371 `Customizing Parser Behaviour`_ section.