blob: 1ebda53ecda0fb9a9b0ec0bf4d9bc7b01574a0ba [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
Fred Drake5a7c11f2010-11-13 05:24:17 +0000270Configuration files may include comments, prefixed by specific
271characters (``#`` and ``;`` by default [1]_). Comments may appear on
Łukasz Langab25a7912010-12-17 01:32:29 +0000272their own on an otherwise empty line, possibly indented. [1]_
Georg Brandl96a60ae2010-07-28 13:13:46 +0000273
Georg Brandlbb27c122010-11-11 07:26:40 +0000274For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000275
Georg Brandlbb27c122010-11-11 07:26:40 +0000276.. code-block:: ini
Georg Brandl116aa622007-08-15 14:28:22 +0000277
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000278 [Simple Values]
Łukasz Langab25a7912010-12-17 01:32:29 +0000279 key=value
280 spaces in keys=allowed
281 spaces in values=allowed as well
282 spaces around the delimiter = obviously
283 you can also use : to delimit keys from values
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000284
285 [All Values Are Strings]
286 values like this: 1000000
287 or this: 3.14159265359
288 are they treated as numbers? : no
289 integers, floats and booleans are held as: strings
290 can use the API to get converted values directly: true
Georg Brandl116aa622007-08-15 14:28:22 +0000291
Georg Brandl96a60ae2010-07-28 13:13:46 +0000292 [Multiline Values]
293 chorus: I'm a lumberjack, and I'm okay
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000294 I sleep all night and I work all day
Georg Brandl116aa622007-08-15 14:28:22 +0000295
Georg Brandl96a60ae2010-07-28 13:13:46 +0000296 [No Values]
297 key_without_value
298 empty string value here =
Georg Brandl116aa622007-08-15 14:28:22 +0000299
Łukasz Langab25a7912010-12-17 01:32:29 +0000300 [You can use comments]
301 # like this
302 ; or this
303
304 # By default only in an empty line.
305 # Inline comments can be harmful because they prevent users
306 # from using the delimiting characters as parts of values.
307 # That being said, this can be customized.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000308
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000309 [Sections Can Be Indented]
310 can_values_be_as_well = True
311 does_that_mean_anything_special = False
312 purpose = formatting for readability
313 multiline_values = are
314 handled just fine as
315 long as they are indented
316 deeper than the first line
317 of a value
318 # Did I mention we can indent comments, too?
Georg Brandl116aa622007-08-15 14:28:22 +0000319
Georg Brandl96a60ae2010-07-28 13:13:46 +0000320
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000321Interpolation of values
322-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000323
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000324On top of the core functionality, :class:`ConfigParser` supports
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000325interpolation. This means values can be preprocessed before returning them
326from ``get()`` calls.
327
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200328.. index:: single: % (percent); interpolation in configuration files
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300329
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000330.. class:: BasicInterpolation()
331
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000332 The default implementation used by :class:`ConfigParser`. It enables
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000333 values to contain format strings which refer to other values in the same
334 section, or values in the special default section [1]_. Additional default
335 values can be provided on initialization.
336
337 For example:
338
339 .. code-block:: ini
340
341 [Paths]
342 home_dir: /Users
343 my_dir: %(home_dir)s/lumberjack
344 my_pictures: %(my_dir)s/Pictures
345
Arun Persaud9a940932019-09-10 05:51:09 -0700346 [Escape]
347 gain: 80%% # use a %% to escape the % sign (% is the only character that needs to be escaped)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000348
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000349 In the example above, :class:`ConfigParser` with *interpolation* set to
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000350 ``BasicInterpolation()`` would resolve ``%(home_dir)s`` to the value of
351 ``home_dir`` (``/Users`` in this case). ``%(my_dir)s`` in effect would
352 resolve to ``/Users/lumberjack``. All interpolations are done on demand so
353 keys used in the chain of references do not have to be specified in any
354 specific order in the configuration file.
355
356 With ``interpolation`` set to ``None``, the parser would simply return
357 ``%(my_dir)s/Pictures`` as the value of ``my_pictures`` and
358 ``%(home_dir)s/lumberjack`` as the value of ``my_dir``.
359
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200360.. index:: single: $ (dollar); interpolation in configuration files
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300361
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000362.. class:: ExtendedInterpolation()
363
364 An alternative handler for interpolation which implements a more advanced
Łukasz Langa34cea142014-09-14 23:37:03 -0700365 syntax, used for instance in ``zc.buildout``. Extended interpolation is
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000366 using ``${section:option}`` to denote a value from a foreign section.
Łukasz Langa34cea142014-09-14 23:37:03 -0700367 Interpolation can span multiple levels. For convenience, if the
368 ``section:`` part is omitted, interpolation defaults to the current section
369 (and possibly the default values from the special section).
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000370
371 For example, the configuration specified above with basic interpolation,
372 would look like this with extended interpolation:
373
374 .. code-block:: ini
375
376 [Paths]
377 home_dir: /Users
378 my_dir: ${home_dir}/lumberjack
379 my_pictures: ${my_dir}/Pictures
380
Arun Persaud9a940932019-09-10 05:51:09 -0700381 [Escape]
382 cost: $$80 # use a $$ to escape the $ sign ($ is the only character that needs to be escaped)
383
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000384 Values from other sections can be fetched as well:
385
386 .. code-block:: ini
387
388 [Common]
389 home_dir: /Users
390 library_dir: /Library
391 system_dir: /System
392 macports_dir: /opt/local
393
394 [Frameworks]
395 Python: 3.2
396 path: ${Common:system_dir}/Library/Frameworks/
397
398 [Arthur]
399 nickname: Two Sheds
400 last_name: Jackson
401 my_dir: ${Common:home_dir}/twosheds
402 my_pictures: ${my_dir}/Pictures
403 python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
Georg Brandlbb27c122010-11-11 07:26:40 +0000404
Łukasz Langa26d513c2010-11-10 18:57:39 +0000405Mapping Protocol Access
406-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000407
Łukasz Langa26d513c2010-11-10 18:57:39 +0000408.. versionadded:: 3.2
Georg Brandl96a60ae2010-07-28 13:13:46 +0000409
Łukasz Langa26d513c2010-11-10 18:57:39 +0000410Mapping protocol access is a generic name for functionality that enables using
Georg Brandlbb27c122010-11-11 07:26:40 +0000411custom objects as if they were dictionaries. In case of :mod:`configparser`,
Łukasz Langa26d513c2010-11-10 18:57:39 +0000412the mapping interface implementation is using the
413``parser['section']['option']`` notation.
414
415``parser['section']`` in particular returns a proxy for the section's data in
Georg Brandlbb27c122010-11-11 07:26:40 +0000416the parser. This means that the values are not copied but they are taken from
417the original parser on demand. What's even more important is that when values
Łukasz Langa26d513c2010-11-10 18:57:39 +0000418are changed on a section proxy, they are actually mutated in the original
419parser.
420
421:mod:`configparser` objects behave as close to actual dictionaries as possible.
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300422The mapping interface is complete and adheres to the
423:class:`~collections.abc.MutableMapping` ABC.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000424However, there are a few differences that should be taken into account:
425
Georg Brandlbb27c122010-11-11 07:26:40 +0000426* By default, all keys in sections are accessible in a case-insensitive manner
427 [1]_. E.g. ``for option in parser["section"]`` yields only ``optionxform``'ed
428 option key names. This means lowercased keys by default. At the same time,
Fred Drake5a7c11f2010-11-13 05:24:17 +0000429 for a section that holds the key ``'a'``, both expressions return ``True``::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000430
Georg Brandlbb27c122010-11-11 07:26:40 +0000431 "a" in parser["section"]
432 "A" in parser["section"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000433
Georg Brandlbb27c122010-11-11 07:26:40 +0000434* All sections include ``DEFAULTSECT`` values as well which means that
435 ``.clear()`` on a section may not leave the section visibly empty. This is
Łukasz Langa26d513c2010-11-10 18:57:39 +0000436 because default values cannot be deleted from the section (because technically
Donald Stufft8b852f12014-05-20 12:58:38 -0400437 they are not there). If they are overridden in the section, deleting causes
Georg Brandlbb27c122010-11-11 07:26:40 +0000438 the default value to be visible again. Trying to delete a default value
Stéphane Wirtele483f022018-10-26 12:52:11 +0200439 causes a :exc:`KeyError`.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000440
Łukasz Langa3a8479a2012-12-31 03:38:39 +0100441* ``DEFAULTSECT`` cannot be removed from the parser:
442
Stéphane Wirtele483f022018-10-26 12:52:11 +0200443 * trying to delete it raises :exc:`ValueError`,
Łukasz Langa3a8479a2012-12-31 03:38:39 +0100444
445 * ``parser.clear()`` leaves it intact,
446
447 * ``parser.popitem()`` never returns it.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000448
Łukasz Langa71b37a52010-12-17 21:56:32 +0000449* ``parser.get(section, option, **kwargs)`` - the second argument is **not**
Łukasz Langa34cea142014-09-14 23:37:03 -0700450 a fallback value. Note however that the section-level ``get()`` methods are
Łukasz Langa71b37a52010-12-17 21:56:32 +0000451 compatible both with the mapping protocol and the classic configparser API.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000452
Łukasz Langa71b37a52010-12-17 21:56:32 +0000453* ``parser.items()`` is compatible with the mapping protocol (returns a list of
454 *section_name*, *section_proxy* pairs including the DEFAULTSECT). However,
455 this method can also be invoked with arguments: ``parser.items(section, raw,
Łukasz Langa34cea142014-09-14 23:37:03 -0700456 vars)``. The latter call returns a list of *option*, *value* pairs for
Łukasz Langa71b37a52010-12-17 21:56:32 +0000457 a specified ``section``, with all interpolations expanded (unless
458 ``raw=True`` is provided).
Łukasz Langa26d513c2010-11-10 18:57:39 +0000459
460The mapping protocol is implemented on top of the existing legacy API so that
Łukasz Langa71b37a52010-12-17 21:56:32 +0000461subclasses overriding the original interface still should have mappings working
462as expected.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000463
Georg Brandlbb27c122010-11-11 07:26:40 +0000464
Łukasz Langa26d513c2010-11-10 18:57:39 +0000465Customizing Parser Behaviour
466----------------------------
467
468There are nearly as many INI format variants as there are applications using it.
469:mod:`configparser` goes a long way to provide support for the largest sensible
Georg Brandlbb27c122010-11-11 07:26:40 +0000470set of INI styles available. The default functionality is mainly dictated by
Łukasz Langa26d513c2010-11-10 18:57:39 +0000471historical background and it's very likely that you will want to customize some
472of the features.
473
Fred Drake5a7c11f2010-11-13 05:24:17 +0000474The most common way to change the way a specific config parser works is to use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000475the :meth:`__init__` options:
476
477* *defaults*, default value: ``None``
478
479 This option accepts a dictionary of key-value pairs which will be initially
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000480 put in the ``DEFAULT`` section. This makes for an elegant way to support
481 concise configuration files that don't specify values which are the same as
482 the documented default.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000483
Fred Drake5a7c11f2010-11-13 05:24:17 +0000484 Hint: if you want to specify default values for a specific section, use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000485 :meth:`read_dict` before you read the actual file.
486
John Reese3a5b0d82018-06-05 16:31:33 -0700487* *dict_type*, default value: :class:`dict`
Łukasz Langa26d513c2010-11-10 18:57:39 +0000488
489 This option has a major impact on how the mapping protocol will behave and how
John Reese3a5b0d82018-06-05 16:31:33 -0700490 the written configuration files look. With the standard dictionary, every
491 section is stored in the order they were added to the parser. Same goes for
492 options within sections.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000493
494 An alternative dictionary type can be used for example to sort sections and
John Reese3a5b0d82018-06-05 16:31:33 -0700495 options on write-back.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000496
497 Please note: there are ways to add a set of key-value pairs in a single
Georg Brandlbb27c122010-11-11 07:26:40 +0000498 operation. When you use a regular dictionary in those operations, the order
John Reese3a5b0d82018-06-05 16:31:33 -0700499 of the keys will be ordered. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000500
Łukasz Langa26d513c2010-11-10 18:57:39 +0000501 .. doctest::
502
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000503 >>> parser = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000504 >>> parser.read_dict({'section1': {'key1': 'value1',
505 ... 'key2': 'value2',
506 ... 'key3': 'value3'},
507 ... 'section2': {'keyA': 'valueA',
508 ... 'keyB': 'valueB',
509 ... 'keyC': 'valueC'},
510 ... 'section3': {'foo': 'x',
511 ... 'bar': 'y',
512 ... 'baz': 'z'}
513 ... })
Inada Naoki0897e0c2019-01-31 17:53:48 +0900514 >>> parser.sections()
John Reese3a5b0d82018-06-05 16:31:33 -0700515 ['section1', 'section2', 'section3']
Inada Naoki0897e0c2019-01-31 17:53:48 +0900516 >>> [option for option in parser['section3']]
John Reese3a5b0d82018-06-05 16:31:33 -0700517 ['foo', 'bar', 'baz']
Łukasz Langa26d513c2010-11-10 18:57:39 +0000518
519* *allow_no_value*, default value: ``False``
520
521 Some configuration files are known to include settings without values, but
522 which otherwise conform to the syntax supported by :mod:`configparser`. The
Fred Drake5a7c11f2010-11-13 05:24:17 +0000523 *allow_no_value* parameter to the constructor can be used to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000524 indicate that such values should be accepted:
525
Łukasz Langa26d513c2010-11-10 18:57:39 +0000526 .. doctest::
527
Georg Brandlbb27c122010-11-11 07:26:40 +0000528 >>> import configparser
Łukasz Langa26d513c2010-11-10 18:57:39 +0000529
Georg Brandlbb27c122010-11-11 07:26:40 +0000530 >>> sample_config = """
531 ... [mysqld]
532 ... user = mysql
533 ... pid-file = /var/run/mysqld/mysqld.pid
534 ... skip-external-locking
535 ... old_passwords = 1
536 ... skip-bdb
Łukasz Langab25a7912010-12-17 01:32:29 +0000537 ... # we don't need ACID today
538 ... skip-innodb
Georg Brandlbb27c122010-11-11 07:26:40 +0000539 ... """
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000540 >>> config = configparser.ConfigParser(allow_no_value=True)
Georg Brandlbb27c122010-11-11 07:26:40 +0000541 >>> config.read_string(sample_config)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000542
Georg Brandlbb27c122010-11-11 07:26:40 +0000543 >>> # Settings with values are treated as before:
544 >>> config["mysqld"]["user"]
545 'mysql'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000546
Georg Brandlbb27c122010-11-11 07:26:40 +0000547 >>> # Settings without values provide None:
548 >>> config["mysqld"]["skip-bdb"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000549
Georg Brandlbb27c122010-11-11 07:26:40 +0000550 >>> # Settings which aren't specified still raise an error:
551 >>> config["mysqld"]["does-not-exist"]
552 Traceback (most recent call last):
553 ...
554 KeyError: 'does-not-exist'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000555
556* *delimiters*, default value: ``('=', ':')``
557
Łukasz Langa34cea142014-09-14 23:37:03 -0700558 Delimiters are substrings that delimit keys from values within a section.
559 The first occurrence of a delimiting substring on a line is considered
560 a delimiter. This means values (but not keys) can contain the delimiters.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000561
562 See also the *space_around_delimiters* argument to
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000563 :meth:`ConfigParser.write`.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000564
Łukasz Langab25a7912010-12-17 01:32:29 +0000565* *comment_prefixes*, default value: ``('#', ';')``
Łukasz Langa26d513c2010-11-10 18:57:39 +0000566
Łukasz Langab25a7912010-12-17 01:32:29 +0000567* *inline_comment_prefixes*, default value: ``None``
568
569 Comment prefixes are strings that indicate the start of a valid comment within
570 a config file. *comment_prefixes* are used only on otherwise empty lines
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700571 (optionally indented) whereas *inline_comment_prefixes* can be used after
572 every valid value (e.g. section names, options and empty lines as well). By
573 default inline comments are disabled and ``'#'`` and ``';'`` are used as
574 prefixes for whole line comments.
Łukasz Langab25a7912010-12-17 01:32:29 +0000575
576 .. versionchanged:: 3.2
577 In previous versions of :mod:`configparser` behaviour matched
578 ``comment_prefixes=('#',';')`` and ``inline_comment_prefixes=(';',)``.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000579
580 Please note that config parsers don't support escaping of comment prefixes so
Łukasz Langab25a7912010-12-17 01:32:29 +0000581 using *inline_comment_prefixes* may prevent users from specifying option
Łukasz Langa34cea142014-09-14 23:37:03 -0700582 values with characters used as comment prefixes. When in doubt, avoid
583 setting *inline_comment_prefixes*. In any circumstances, the only way of
584 storing comment prefix characters at the beginning of a line in multiline
585 values is to interpolate the prefix, for example::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000586
Łukasz Langab25a7912010-12-17 01:32:29 +0000587 >>> from configparser import ConfigParser, ExtendedInterpolation
588 >>> parser = ConfigParser(interpolation=ExtendedInterpolation())
589 >>> # the default BasicInterpolation could be used as well
590 >>> parser.read_string("""
591 ... [DEFAULT]
592 ... hash = #
593 ...
594 ... [hashes]
595 ... shebang =
596 ... ${hash}!/usr/bin/env python
597 ... ${hash} -*- coding: utf-8 -*-
598 ...
599 ... extensions =
600 ... enabled_extension
601 ... another_extension
602 ... #disabled_by_comment
603 ... yet_another_extension
604 ...
605 ... interpolation not necessary = if # is not at line start
606 ... even in multiline values = line #1
607 ... line #2
608 ... line #3
609 ... """)
610 >>> print(parser['hashes']['shebang'])
Marco Buttub2a7c2f2017-03-02 12:02:43 +0100611 <BLANKLINE>
Łukasz Langab25a7912010-12-17 01:32:29 +0000612 #!/usr/bin/env python
613 # -*- coding: utf-8 -*-
614 >>> print(parser['hashes']['extensions'])
Marco Buttub2a7c2f2017-03-02 12:02:43 +0100615 <BLANKLINE>
Łukasz Langab25a7912010-12-17 01:32:29 +0000616 enabled_extension
617 another_extension
618 yet_another_extension
619 >>> print(parser['hashes']['interpolation not necessary'])
620 if # is not at line start
621 >>> print(parser['hashes']['even in multiline values'])
622 line #1
623 line #2
624 line #3
625
626* *strict*, default value: ``True``
627
628 When set to ``True``, the parser will not allow for any section or option
Łukasz Langa26d513c2010-11-10 18:57:39 +0000629 duplicates while reading from a single source (using :meth:`read_file`,
Łukasz Langa34cea142014-09-14 23:37:03 -0700630 :meth:`read_string` or :meth:`read_dict`). It is recommended to use strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000631 parsers in new applications.
632
Łukasz Langab25a7912010-12-17 01:32:29 +0000633 .. versionchanged:: 3.2
634 In previous versions of :mod:`configparser` behaviour matched
635 ``strict=False``.
636
Łukasz Langa26d513c2010-11-10 18:57:39 +0000637* *empty_lines_in_values*, default value: ``True``
638
Fred Drake5a7c11f2010-11-13 05:24:17 +0000639 In config parsers, values can span multiple lines as long as they are
640 indented more than the key that holds them. By default parsers also let
641 empty lines to be parts of values. At the same time, keys can be arbitrarily
642 indented themselves to improve readability. In consequence, when
643 configuration files get big and complex, it is easy for the user to lose
644 track of the file structure. Take for instance:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000645
Georg Brandlbb27c122010-11-11 07:26:40 +0000646 .. code-block:: ini
Łukasz Langa26d513c2010-11-10 18:57:39 +0000647
Georg Brandlbb27c122010-11-11 07:26:40 +0000648 [Section]
649 key = multiline
650 value with a gotcha
Łukasz Langa26d513c2010-11-10 18:57:39 +0000651
Georg Brandlbb27c122010-11-11 07:26:40 +0000652 this = is still a part of the multiline value of 'key'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000653
Georg Brandlbb27c122010-11-11 07:26:40 +0000654 This can be especially problematic for the user to see if she's using a
655 proportional font to edit the file. That is why when your application does
656 not need values with empty lines, you should consider disallowing them. This
657 will make empty lines split keys every time. In the example above, it would
Łukasz Langa26d513c2010-11-10 18:57:39 +0000658 produce two keys, ``key`` and ``this``.
659
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000660* *default_section*, default value: ``configparser.DEFAULTSECT`` (that is:
661 ``"DEFAULT"``)
662
663 The convention of allowing a special section of default values for other
664 sections or interpolation purposes is a powerful concept of this library,
Łukasz Langa34cea142014-09-14 23:37:03 -0700665 letting users create complex declarative configurations. This section is
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000666 normally called ``"DEFAULT"`` but this can be customized to point to any
Łukasz Langa34cea142014-09-14 23:37:03 -0700667 other valid section name. Some typical values include: ``"general"`` or
668 ``"common"``. The name provided is used for recognizing default sections
669 when reading from any source and is used when writing configuration back to
670 a file. Its current value can be retrieved using the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000671 ``parser_instance.default_section`` attribute and may be modified at runtime
672 (i.e. to convert files from one format to another).
673
674* *interpolation*, default value: ``configparser.BasicInterpolation``
675
676 Interpolation behaviour may be customized by providing a custom handler
677 through the *interpolation* argument. ``None`` can be used to turn off
678 interpolation completely, ``ExtendedInterpolation()`` provides a more
Łukasz Langa34cea142014-09-14 23:37:03 -0700679 advanced variant inspired by ``zc.buildout``. More on the subject in the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000680 `dedicated documentation section <#interpolation-of-values>`_.
Łukasz Langab25a7912010-12-17 01:32:29 +0000681 :class:`RawConfigParser` has a default value of ``None``.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000682
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700683* *converters*, default value: not set
684
685 Config parsers provide option value getters that perform type conversion. By
Jesus Cea647680e2016-09-20 00:01:53 +0200686 default :meth:`~ConfigParser.getint`, :meth:`~ConfigParser.getfloat`, and
687 :meth:`~ConfigParser.getboolean` are implemented. Should other getters be
688 desirable, users may define them in a subclass or pass a dictionary where each
689 key is a name of the converter and each value is a callable implementing said
690 conversion. For instance, passing ``{'decimal': decimal.Decimal}`` would add
691 :meth:`getdecimal` on both the parser object and all section proxies. In
692 other words, it will be possible to write both
693 ``parser_instance.getdecimal('section', 'key', fallback=0)`` and
694 ``parser_instance['section'].getdecimal('key', 0)``.
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700695
696 If the converter needs to access the state of the parser, it can be
697 implemented as a method on a config parser subclass. If the name of this
698 method starts with ``get``, it will be available on all section proxies, in
699 the dict-compatible form (see the ``getdecimal()`` example above).
Łukasz Langa26d513c2010-11-10 18:57:39 +0000700
Fred Drake5a7c11f2010-11-13 05:24:17 +0000701More advanced customization may be achieved by overriding default values of
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700702these parser attributes. The defaults are defined on the classes, so they may
703be overridden by subclasses or by attribute assignment.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000704
Ned Batchelder890423f2018-10-24 19:47:01 -0400705.. attribute:: ConfigParser.BOOLEAN_STATES
Łukasz Langa26d513c2010-11-10 18:57:39 +0000706
Victor Stinnerd3ded082020-08-13 21:41:54 +0200707 By default when using :meth:`~ConfigParser.getboolean`, config parsers
708 consider the following values ``True``: ``'1'``, ``'yes'``, ``'true'``,
709 ``'on'`` and the following values ``False``: ``'0'``, ``'no'``, ``'false'``,
710 ``'off'``. You can override this by specifying a custom dictionary of strings
711 and their Boolean outcomes. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000712
Victor Stinnerd3ded082020-08-13 21:41:54 +0200713 .. doctest::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000714
Victor Stinnerd3ded082020-08-13 21:41:54 +0200715 >>> custom = configparser.ConfigParser()
716 >>> custom['section1'] = {'funky': 'nope'}
717 >>> custom['section1'].getboolean('funky')
718 Traceback (most recent call last):
719 ...
720 ValueError: Not a boolean: nope
721 >>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}
722 >>> custom['section1'].getboolean('funky')
723 False
Łukasz Langa26d513c2010-11-10 18:57:39 +0000724
Victor Stinnerd3ded082020-08-13 21:41:54 +0200725 Other typical Boolean pairs include ``accept``/``reject`` or
726 ``enabled``/``disabled``.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000727
Ned Batchelder890423f2018-10-24 19:47:01 -0400728.. method:: ConfigParser.optionxform(option)
Victor Stinnerd3ded082020-08-13 21:41:54 +0200729 :noindex:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000730
Victor Stinnerd3ded082020-08-13 21:41:54 +0200731 This method transforms option names on every read, get, or set
732 operation. The default converts the name to lowercase. This also
733 means that when a configuration file gets written, all keys will be
734 lowercase. Override this method if that's unsuitable.
735 For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000736
Victor Stinnerd3ded082020-08-13 21:41:54 +0200737 .. doctest::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000738
Victor Stinnerd3ded082020-08-13 21:41:54 +0200739 >>> config = """
740 ... [Section1]
741 ... Key = Value
742 ...
743 ... [Section2]
744 ... AnotherKey = Value
745 ... """
746 >>> typical = configparser.ConfigParser()
747 >>> typical.read_string(config)
748 >>> list(typical['Section1'].keys())
749 ['key']
750 >>> list(typical['Section2'].keys())
751 ['anotherkey']
752 >>> custom = configparser.RawConfigParser()
753 >>> custom.optionxform = lambda option: option
754 >>> custom.read_string(config)
755 >>> list(custom['Section1'].keys())
756 ['Key']
757 >>> list(custom['Section2'].keys())
758 ['AnotherKey']
Georg Brandlbb27c122010-11-11 07:26:40 +0000759
Victor Stinnerd3ded082020-08-13 21:41:54 +0200760 .. note::
761 The optionxform function transforms option names to a canonical form.
762 This should be an idempotent function: if the name is already in
763 canonical form, it should be returned unchanged.
Inada Naoki04694a32019-04-02 18:08:46 +0900764
765
Ned Batchelder890423f2018-10-24 19:47:01 -0400766.. attribute:: ConfigParser.SECTCRE
Łukasz Langa66c908e2011-01-28 11:57:30 +0000767
Victor Stinnerd3ded082020-08-13 21:41:54 +0200768 A compiled regular expression used to parse section headers. The default
769 matches ``[section]`` to the name ``"section"``. Whitespace is considered
770 part of the section name, thus ``[ larch ]`` will be read as a section of
771 name ``" larch "``. Override this attribute if that's unsuitable. For
772 example:
Łukasz Langa66c908e2011-01-28 11:57:30 +0000773
Victor Stinnerd3ded082020-08-13 21:41:54 +0200774 .. doctest::
Łukasz Langa66c908e2011-01-28 11:57:30 +0000775
Victor Stinnerd3ded082020-08-13 21:41:54 +0200776 >>> import re
777 >>> config = """
778 ... [Section 1]
779 ... option = value
780 ...
781 ... [ Section 2 ]
782 ... another = val
783 ... """
784 >>> typical = configparser.ConfigParser()
785 >>> typical.read_string(config)
786 >>> typical.sections()
787 ['Section 1', ' Section 2 ']
788 >>> custom = configparser.ConfigParser()
789 >>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]")
790 >>> custom.read_string(config)
791 >>> custom.sections()
792 ['Section 1', 'Section 2']
Łukasz Langa66c908e2011-01-28 11:57:30 +0000793
Victor Stinnerd3ded082020-08-13 21:41:54 +0200794 .. note::
Łukasz Langa66c908e2011-01-28 11:57:30 +0000795
Victor Stinnerd3ded082020-08-13 21:41:54 +0200796 While ConfigParser objects also use an ``OPTCRE`` attribute for recognizing
797 option lines, it's not recommended to override it because that would
798 interfere with constructor options *allow_no_value* and *delimiters*.
Łukasz Langa66c908e2011-01-28 11:57:30 +0000799
Łukasz Langa26d513c2010-11-10 18:57:39 +0000800
801Legacy API Examples
802-------------------
803
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000804Mainly because of backwards compatibility concerns, :mod:`configparser`
805provides also a legacy API with explicit ``get``/``set`` methods. While there
806are valid use cases for the methods outlined below, mapping protocol access is
807preferred for new projects. The legacy API is at times more advanced,
808low-level and downright counterintuitive.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000809
810An example of writing to a configuration file::
811
812 import configparser
813
814 config = configparser.RawConfigParser()
815
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000816 # Please note that using RawConfigParser's set functions, you can assign
817 # non-string values to keys internally, but will receive an error when
818 # attempting to write to a file or when you get it in non-raw mode. Setting
819 # values using the mapping protocol or ConfigParser's set() does not allow
820 # such assignments to take place.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000821 config.add_section('Section1')
R David Murray1a1883d2012-09-29 14:40:23 -0400822 config.set('Section1', 'an_int', '15')
823 config.set('Section1', 'a_bool', 'true')
824 config.set('Section1', 'a_float', '3.1415')
Łukasz Langa26d513c2010-11-10 18:57:39 +0000825 config.set('Section1', 'baz', 'fun')
826 config.set('Section1', 'bar', 'Python')
827 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
828
829 # Writing our configuration file to 'example.cfg'
830 with open('example.cfg', 'w') as configfile:
831 config.write(configfile)
832
833An example of reading the configuration file again::
834
835 import configparser
836
837 config = configparser.RawConfigParser()
838 config.read('example.cfg')
839
840 # getfloat() raises an exception if the value is not a float
841 # getint() and getboolean() also do this for their respective types
R David Murray1a1883d2012-09-29 14:40:23 -0400842 a_float = config.getfloat('Section1', 'a_float')
843 an_int = config.getint('Section1', 'an_int')
844 print(a_float + an_int)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000845
846 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
847 # This is because we are using a RawConfigParser().
R David Murray1a1883d2012-09-29 14:40:23 -0400848 if config.getboolean('Section1', 'a_bool'):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000849 print(config.get('Section1', 'foo'))
850
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000851To get interpolation, use :class:`ConfigParser`::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000852
853 import configparser
854
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000855 cfg = configparser.ConfigParser()
Łukasz Langa26d513c2010-11-10 18:57:39 +0000856 cfg.read('example.cfg')
857
Éric Araujo941afed2011-09-01 02:47:34 +0200858 # Set the optional *raw* argument of get() to True if you wish to disable
Łukasz Langa26d513c2010-11-10 18:57:39 +0000859 # interpolation in a single get operation.
Serhiy Storchakadba90392016-05-10 12:01:23 +0300860 print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!"
861 print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!"
Łukasz Langa26d513c2010-11-10 18:57:39 +0000862
Éric Araujo941afed2011-09-01 02:47:34 +0200863 # The optional *vars* argument is a dict with members that will take
Łukasz Langa26d513c2010-11-10 18:57:39 +0000864 # precedence in interpolation.
865 print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation',
Serhiy Storchakadba90392016-05-10 12:01:23 +0300866 'baz': 'evil'}))
Łukasz Langa26d513c2010-11-10 18:57:39 +0000867
Éric Araujo941afed2011-09-01 02:47:34 +0200868 # The optional *fallback* argument can be used to provide a fallback value
Łukasz Langa26d513c2010-11-10 18:57:39 +0000869 print(cfg.get('Section1', 'foo'))
870 # -> "Python is fun!"
871
872 print(cfg.get('Section1', 'foo', fallback='Monty is not.'))
873 # -> "Python is fun!"
874
875 print(cfg.get('Section1', 'monster', fallback='No such things as monsters.'))
876 # -> "No such things as monsters."
877
878 # A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError
879 # but we can also use:
880
881 print(cfg.get('Section1', 'monster', fallback=None))
882 # -> None
883
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000884Default values are available in both types of ConfigParsers. They are used in
885interpolation if an option used is not defined elsewhere. ::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000886
887 import configparser
888
889 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000890 config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'})
Łukasz Langa26d513c2010-11-10 18:57:39 +0000891 config.read('example.cfg')
892
Serhiy Storchakadba90392016-05-10 12:01:23 +0300893 print(config.get('Section1', 'foo')) # -> "Python is fun!"
Łukasz Langa26d513c2010-11-10 18:57:39 +0000894 config.remove_option('Section1', 'bar')
895 config.remove_option('Section1', 'baz')
Serhiy Storchakadba90392016-05-10 12:01:23 +0300896 print(config.get('Section1', 'foo')) # -> "Life is hard!"
Łukasz Langa26d513c2010-11-10 18:57:39 +0000897
Georg Brandlbb27c122010-11-11 07:26:40 +0000898
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000899.. _configparser-objects:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000900
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000901ConfigParser Objects
902--------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000903
Andrés Delfino3b0b90c2018-06-08 16:19:21 -0300904.. 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 +0000905
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000906 The main configuration parser. When *defaults* is given, it is initialized
Georg Brandl96a60ae2010-07-28 13:13:46 +0000907 into the dictionary of intrinsic defaults. When *dict_type* is given, it
908 will be used to create the dictionary objects for the list of sections, for
909 the options within a section, and for the default values.
910
Fred Drake5a7c11f2010-11-13 05:24:17 +0000911 When *delimiters* is given, it is used as the set of substrings that
Georg Brandl96a60ae2010-07-28 13:13:46 +0000912 divide keys from values. When *comment_prefixes* is given, it will be used
Łukasz Langab25a7912010-12-17 01:32:29 +0000913 as the set of substrings that prefix comments in otherwise empty lines.
Łukasz Langa34cea142014-09-14 23:37:03 -0700914 Comments can be indented. When *inline_comment_prefixes* is given, it will
915 be used as the set of substrings that prefix comments in non-empty lines.
Łukasz Langab25a7912010-12-17 01:32:29 +0000916
Łukasz Langab25a7912010-12-17 01:32:29 +0000917 When *strict* is ``True`` (the default), the parser won't allow for
Fred Drakea4923622010-08-09 12:52:45 +0000918 any section or option duplicates while reading from a single source (file,
919 string or dictionary), raising :exc:`DuplicateSectionError` or
Fred Drake5a7c11f2010-11-13 05:24:17 +0000920 :exc:`DuplicateOptionError`. When *empty_lines_in_values* is ``False``
Fred Drakea4923622010-08-09 12:52:45 +0000921 (default: ``True``), each empty line marks the end of an option. Otherwise,
922 internal empty lines of a multiline option are kept as part of the value.
923 When *allow_no_value* is ``True`` (default: ``False``), options without
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000924 values are accepted; the value held for these is ``None`` and they are
925 serialized without the trailing delimiter.
Fred Drake03c44a32010-02-19 06:08:41 +0000926
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000927 When *default_section* is given, it specifies the name for the special
928 section holding default values for other sections and interpolation purposes
Łukasz Langa34cea142014-09-14 23:37:03 -0700929 (normally named ``"DEFAULT"``). This value can be retrieved and changed on
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000930 runtime using the ``default_section`` instance attribute.
931
932 Interpolation behaviour may be customized by providing a custom handler
933 through the *interpolation* argument. ``None`` can be used to turn off
934 interpolation completely, ``ExtendedInterpolation()`` provides a more
Łukasz Langa34cea142014-09-14 23:37:03 -0700935 advanced variant inspired by ``zc.buildout``. More on the subject in the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000936 `dedicated documentation section <#interpolation-of-values>`_.
937
938 All option names used in interpolation will be passed through the
939 :meth:`optionxform` method just like any other option name reference. For
940 example, using the default implementation of :meth:`optionxform` (which
941 converts option names to lower case), the values ``foo %(bar)s`` and ``foo
942 %(BAR)s`` are equivalent.
Georg Brandl116aa622007-08-15 14:28:22 +0000943
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700944 When *converters* is given, it should be a dictionary where each key
945 represents the name of a type converter and each value is a callable
946 implementing the conversion from string to the desired datatype. Every
947 converter gets its own corresponding :meth:`get*()` method on the parser
948 object and section proxies.
949
Raymond Hettinger231b7f12009-03-03 00:23:19 +0000950 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +0000951 The default *dict_type* is :class:`collections.OrderedDict`.
952
Fred Drake03c44a32010-02-19 06:08:41 +0000953 .. versionchanged:: 3.2
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000954 *allow_no_value*, *delimiters*, *comment_prefixes*, *strict*,
955 *empty_lines_in_values*, *default_section* and *interpolation* were
956 added.
Georg Brandl116aa622007-08-15 14:28:22 +0000957
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700958 .. versionchanged:: 3.5
959 The *converters* argument was added.
960
Łukasz Langaea579232017-08-21 16:23:38 -0700961 .. versionchanged:: 3.7
962 The *defaults* argument is read with :meth:`read_dict()`,
963 providing consistent behavior across the parser: non-string
964 keys and values are implicitly converted to strings.
965
Inada Naoki0897e0c2019-01-31 17:53:48 +0900966 .. versionchanged:: 3.8
Andrés Delfino3b0b90c2018-06-08 16:19:21 -0300967 The default *dict_type* is :class:`dict`, since it now preserves
968 insertion order.
Fred Drake03c44a32010-02-19 06:08:41 +0000969
Georg Brandlbb27c122010-11-11 07:26:40 +0000970 .. method:: defaults()
Georg Brandl116aa622007-08-15 14:28:22 +0000971
Georg Brandlbb27c122010-11-11 07:26:40 +0000972 Return a dictionary containing the instance-wide defaults.
Georg Brandl116aa622007-08-15 14:28:22 +0000973
974
Georg Brandlbb27c122010-11-11 07:26:40 +0000975 .. method:: sections()
Georg Brandl116aa622007-08-15 14:28:22 +0000976
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000977 Return a list of the sections available; the *default section* is not
978 included in the list.
Georg Brandl116aa622007-08-15 14:28:22 +0000979
980
Georg Brandlbb27c122010-11-11 07:26:40 +0000981 .. method:: add_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000982
Georg Brandlbb27c122010-11-11 07:26:40 +0000983 Add a section named *section* to the instance. If a section by the given
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000984 name already exists, :exc:`DuplicateSectionError` is raised. If the
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000985 *default section* name is passed, :exc:`ValueError` is raised. The name
986 of the section must be a string; if not, :exc:`TypeError` is raised.
987
988 .. versionchanged:: 3.2
989 Non-string section names raise :exc:`TypeError`.
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:: has_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000993
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000994 Indicates whether the named *section* is present in the configuration.
995 The *default section* is not acknowledged.
Georg Brandl116aa622007-08-15 14:28:22 +0000996
Georg Brandl116aa622007-08-15 14:28:22 +0000997
Georg Brandlbb27c122010-11-11 07:26:40 +0000998 .. method:: options(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000999
Georg Brandlbb27c122010-11-11 07:26:40 +00001000 Return a list of options available in the specified *section*.
Georg Brandl116aa622007-08-15 14:28:22 +00001001
Georg Brandl116aa622007-08-15 14:28:22 +00001002
Georg Brandlbb27c122010-11-11 07:26:40 +00001003 .. method:: has_option(section, option)
Georg Brandl116aa622007-08-15 14:28:22 +00001004
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001005 If the given *section* exists, and contains the given *option*, return
Łukasz Langa34cea142014-09-14 23:37:03 -07001006 :const:`True`; otherwise return :const:`False`. If the specified
Łukasz Langa71b37a52010-12-17 21:56:32 +00001007 *section* is :const:`None` or an empty string, DEFAULT is assumed.
Georg Brandl116aa622007-08-15 14:28:22 +00001008
Georg Brandl116aa622007-08-15 14:28:22 +00001009
Georg Brandlbb27c122010-11-11 07:26:40 +00001010 .. method:: read(filenames, encoding=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001011
Zackery Spytze45473e2018-09-29 10:15:55 -06001012 Attempt to read and parse an iterable of filenames, returning a list of
David Ellis85b8d012017-03-03 17:14:27 +00001013 filenames which were successfully parsed.
1014
Vincent Michele3148532017-11-02 13:47:04 +01001015 If *filenames* is a string, a :class:`bytes` object or a
1016 :term:`path-like object`, it is treated as
David Ellis85b8d012017-03-03 17:14:27 +00001017 a single filename. If a file named in *filenames* cannot be opened, that
Zackery Spytze45473e2018-09-29 10:15:55 -06001018 file will be ignored. This is designed so that you can specify an
1019 iterable of potential configuration file locations (for example, the
1020 current directory, the user's home directory, and some system-wide
1021 directory), and all existing configuration files in the iterable will be
1022 read.
David Ellis85b8d012017-03-03 17:14:27 +00001023
1024 If none of the named files exist, the :class:`ConfigParser`
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001025 instance will contain an empty dataset. An application which requires
1026 initial values to be loaded from a file should load the required file or
1027 files using :meth:`read_file` before calling :meth:`read` for any
1028 optional files::
Georg Brandl116aa622007-08-15 14:28:22 +00001029
Georg Brandlbb27c122010-11-11 07:26:40 +00001030 import configparser, os
Georg Brandl8dcaa732010-07-29 12:17:40 +00001031
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001032 config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +00001033 config.read_file(open('defaults.cfg'))
1034 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
1035 encoding='cp1250')
Georg Brandl116aa622007-08-15 14:28:22 +00001036
Georg Brandlbb27c122010-11-11 07:26:40 +00001037 .. versionadded:: 3.2
1038 The *encoding* parameter. Previously, all files were read using the
1039 default encoding for :func:`open`.
Georg Brandl116aa622007-08-15 14:28:22 +00001040
David Ellis85b8d012017-03-03 17:14:27 +00001041 .. versionadded:: 3.6.1
1042 The *filenames* parameter accepts a :term:`path-like object`.
1043
Vincent Michele3148532017-11-02 13:47:04 +01001044 .. versionadded:: 3.7
1045 The *filenames* parameter accepts a :class:`bytes` object.
1046
Georg Brandl116aa622007-08-15 14:28:22 +00001047
Georg Brandlbb27c122010-11-11 07:26:40 +00001048 .. method:: read_file(f, source=None)
Georg Brandl73753d32009-09-22 13:53:14 +00001049
Łukasz Langadaab1c82011-04-27 18:10:05 +02001050 Read and parse configuration data from *f* which must be an iterable
Łukasz Langaba702da2011-04-28 12:02:05 +02001051 yielding Unicode strings (for example files opened in text mode).
Georg Brandl116aa622007-08-15 14:28:22 +00001052
Georg Brandlbb27c122010-11-11 07:26:40 +00001053 Optional argument *source* specifies the name of the file being read. If
Fred Drake5a7c11f2010-11-13 05:24:17 +00001054 not given and *f* has a :attr:`name` attribute, that is used for
1055 *source*; the default is ``'<???>'``.
Fred Drakea4923622010-08-09 12:52:45 +00001056
Georg Brandlbb27c122010-11-11 07:26:40 +00001057 .. versionadded:: 3.2
Łukasz Langa43ae6192011-04-27 18:13:42 +02001058 Replaces :meth:`readfp`.
1059
Georg Brandlbb27c122010-11-11 07:26:40 +00001060 .. method:: read_string(string, source='<string>')
Fred Drakea4923622010-08-09 12:52:45 +00001061
Fred Drake5a7c11f2010-11-13 05:24:17 +00001062 Parse configuration data from a string.
Fred Drakea4923622010-08-09 12:52:45 +00001063
Fred Drake5a7c11f2010-11-13 05:24:17 +00001064 Optional argument *source* specifies a context-specific name of the
1065 string passed. If not given, ``'<string>'`` is used. This should
1066 commonly be a filesystem path or a URL.
Fred Drakea4923622010-08-09 12:52:45 +00001067
Georg Brandlbb27c122010-11-11 07:26:40 +00001068 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +00001069
Fred Drakea4923622010-08-09 12:52:45 +00001070
Georg Brandlbb27c122010-11-11 07:26:40 +00001071 .. method:: read_dict(dictionary, source='<dict>')
Fred Drakea4923622010-08-09 12:52:45 +00001072
Łukasz Langa71b37a52010-12-17 21:56:32 +00001073 Load configuration from any object that provides a dict-like ``items()``
1074 method. Keys are section names, values are dictionaries with keys and
1075 values that should be present in the section. If the used dictionary
1076 type preserves order, sections and their keys will be added in order.
1077 Values are automatically converted to strings.
Fred Drakea4923622010-08-09 12:52:45 +00001078
Georg Brandlbb27c122010-11-11 07:26:40 +00001079 Optional argument *source* specifies a context-specific name of the
1080 dictionary passed. If not given, ``<dict>`` is used.
Georg Brandl116aa622007-08-15 14:28:22 +00001081
Łukasz Langa71b37a52010-12-17 21:56:32 +00001082 This method can be used to copy state between parsers.
1083
Georg Brandlbb27c122010-11-11 07:26:40 +00001084 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +00001085
Georg Brandl116aa622007-08-15 14:28:22 +00001086
Ezio Melottie927e252012-09-08 20:46:01 +03001087 .. method:: get(section, option, *, raw=False, vars=None[, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +00001088
Georg Brandlbb27c122010-11-11 07:26:40 +00001089 Get an *option* value for the named *section*. If *vars* is provided, it
1090 must be a dictionary. The *option* is looked up in *vars* (if provided),
1091 *section*, and in *DEFAULTSECT* in that order. If the key is not found
1092 and *fallback* is provided, it is used as a fallback value. ``None`` can
1093 be provided as a *fallback* value.
Georg Brandl470a1232010-07-29 14:17:12 +00001094
Georg Brandlbb27c122010-11-11 07:26:40 +00001095 All the ``'%'`` interpolations are expanded in the return values, unless
1096 the *raw* argument is true. Values for interpolation keys are looked up
1097 in the same manner as the option.
Georg Brandl116aa622007-08-15 14:28:22 +00001098
Georg Brandlbb27c122010-11-11 07:26:40 +00001099 .. versionchanged:: 3.2
1100 Arguments *raw*, *vars* and *fallback* are keyword only to protect
1101 users from trying to use the third argument as the *fallback* fallback
1102 (especially when using the mapping protocol).
Georg Brandl116aa622007-08-15 14:28:22 +00001103
Łukasz Langa26d513c2010-11-10 18:57:39 +00001104
Ezio Melottie927e252012-09-08 20:46:01 +03001105 .. method:: getint(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001106
Georg Brandlbb27c122010-11-11 07:26:40 +00001107 A convenience method which coerces the *option* in the specified *section*
1108 to an integer. See :meth:`get` for explanation of *raw*, *vars* and
1109 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001110
1111
Ezio Melottie927e252012-09-08 20:46:01 +03001112 .. method:: getfloat(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001113
Georg Brandlbb27c122010-11-11 07:26:40 +00001114 A convenience method which coerces the *option* in the specified *section*
1115 to a floating point number. See :meth:`get` for explanation of *raw*,
1116 *vars* and *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001117
1118
Ezio Melottie927e252012-09-08 20:46:01 +03001119 .. method:: getboolean(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001120
Georg Brandlbb27c122010-11-11 07:26:40 +00001121 A convenience method which coerces the *option* in the specified *section*
1122 to a Boolean value. Note that the accepted values for the option are
Fred Drake5a7c11f2010-11-13 05:24:17 +00001123 ``'1'``, ``'yes'``, ``'true'``, and ``'on'``, which cause this method to
1124 return ``True``, and ``'0'``, ``'no'``, ``'false'``, and ``'off'``, which
Georg Brandlbb27c122010-11-11 07:26:40 +00001125 cause it to return ``False``. These string values are checked in a
1126 case-insensitive manner. Any other value will cause it to raise
1127 :exc:`ValueError`. See :meth:`get` for explanation of *raw*, *vars* and
1128 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001129
1130
Ezio Melottie0add762012-09-14 06:32:35 +03001131 .. method:: items(raw=False, vars=None)
1132 items(section, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001133
Łukasz Langa71b37a52010-12-17 21:56:32 +00001134 When *section* is not given, return a list of *section_name*,
1135 *section_proxy* pairs, including DEFAULTSECT.
1136
1137 Otherwise, return a list of *name*, *value* pairs for the options in the
1138 given *section*. Optional arguments have the same meaning as for the
Georg Brandlbb27c122010-11-11 07:26:40 +00001139 :meth:`get` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001140
Andrés Delfino4acc1402018-06-08 21:20:05 -03001141 .. versionchanged:: 3.8
1142 Items present in *vars* no longer appear in the result. The previous
1143 behaviour mixed actual parser options with variables provided for
1144 interpolation.
Chris Bradburye5008392018-04-23 21:56:39 +01001145
Georg Brandl116aa622007-08-15 14:28:22 +00001146
Georg Brandlbb27c122010-11-11 07:26:40 +00001147 .. method:: set(section, option, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001148
Georg Brandlbb27c122010-11-11 07:26:40 +00001149 If the given section exists, set the given option to the specified value;
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001150 otherwise raise :exc:`NoSectionError`. *option* and *value* must be
1151 strings; if not, :exc:`TypeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001152
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001153
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001154 .. method:: write(fileobject, space_around_delimiters=True)
1155
1156 Write a representation of the configuration to the specified :term:`file
1157 object`, which must be opened in text mode (accepting strings). This
1158 representation can be parsed by a future :meth:`read` call. If
1159 *space_around_delimiters* is true, delimiters between
1160 keys and values are surrounded by spaces.
1161
Łukasz Langa4d17c932021-05-18 19:03:09 +02001162 .. note::
1163
1164 Comments in the original configuration file are not preserved when
1165 writing the configuration back.
1166 What is considered a comment, depends on the given values for
1167 *comment_prefix* and *inline_comment_prefix*.
1168
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001169
1170 .. method:: remove_option(section, option)
1171
1172 Remove the specified *option* from the specified *section*. If the
1173 section does not exist, raise :exc:`NoSectionError`. If the option
1174 existed to be removed, return :const:`True`; otherwise return
1175 :const:`False`.
1176
1177
1178 .. method:: remove_section(section)
1179
1180 Remove the specified *section* from the configuration. If the section in
1181 fact existed, return ``True``. Otherwise return ``False``.
1182
1183
1184 .. method:: optionxform(option)
1185
1186 Transforms the option name *option* as found in an input file or as passed
1187 in by client code to the form that should be used in the internal
1188 structures. The default implementation returns a lower-case version of
1189 *option*; subclasses may override this or client code can set an attribute
1190 of this name on instances to affect this behavior.
1191
1192 You don't need to subclass the parser to use this method, you can also
1193 set it on an instance, to a function that takes a string argument and
1194 returns a string. Setting it to ``str``, for example, would make option
1195 names case sensitive::
1196
1197 cfgparser = ConfigParser()
1198 cfgparser.optionxform = str
1199
1200 Note that when reading configuration files, whitespace around the option
1201 names is stripped before :meth:`optionxform` is called.
1202
1203
1204 .. method:: readfp(fp, filename=None)
1205
1206 .. deprecated:: 3.2
1207 Use :meth:`read_file` instead.
1208
Łukasz Langaba702da2011-04-28 12:02:05 +02001209 .. versionchanged:: 3.2
Martin Panter1f106712017-01-29 23:33:27 +00001210 :meth:`readfp` now iterates on *fp* instead of calling ``fp.readline()``.
Łukasz Langaba702da2011-04-28 12:02:05 +02001211
1212 For existing code calling :meth:`readfp` with arguments which don't
1213 support iteration, the following generator may be used as a wrapper
1214 around the file-like object::
1215
Martin Panter1f106712017-01-29 23:33:27 +00001216 def readline_generator(fp):
1217 line = fp.readline()
Łukasz Langaba702da2011-04-28 12:02:05 +02001218 while line:
1219 yield line
Martin Panter1f106712017-01-29 23:33:27 +00001220 line = fp.readline()
Łukasz Langaba702da2011-04-28 12:02:05 +02001221
Martin Panter1f106712017-01-29 23:33:27 +00001222 Instead of ``parser.readfp(fp)`` use
1223 ``parser.read_file(readline_generator(fp))``.
Łukasz Langaba702da2011-04-28 12:02:05 +02001224
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001225
1226.. data:: MAX_INTERPOLATION_DEPTH
1227
1228 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
1229 parameter is false. This is relevant only when the default *interpolation*
1230 is used.
1231
1232
1233.. _rawconfigparser-objects:
1234
1235RawConfigParser Objects
1236-----------------------
1237
Andrés Delfino3b0b90c2018-06-08 16:19:21 -03001238.. class:: RawConfigParser(defaults=None, dict_type=dict, \
Ezio Melottie927e252012-09-08 20:46:01 +03001239 allow_no_value=False, *, delimiters=('=', ':'), \
1240 comment_prefixes=('#', ';'), \
1241 inline_comment_prefixes=None, strict=True, \
1242 empty_lines_in_values=True, \
1243 default_section=configparser.DEFAULTSECT[, \
1244 interpolation])
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001245
Łukasz Langaa5fab172017-08-24 09:43:53 -07001246 Legacy variant of the :class:`ConfigParser`. It has interpolation
1247 disabled by default and allows for non-string section names, option
1248 names, and values via its unsafe ``add_section`` and ``set`` methods,
1249 as well as the legacy ``defaults=`` keyword argument handling.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001250
Inada Naoki0897e0c2019-01-31 17:53:48 +09001251 .. versionchanged:: 3.8
Andrés Delfino3b0b90c2018-06-08 16:19:21 -03001252 The default *dict_type* is :class:`dict`, since it now preserves
1253 insertion order.
1254
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001255 .. note::
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001256 Consider using :class:`ConfigParser` instead which checks types of
Łukasz Langa34cea142014-09-14 23:37:03 -07001257 the values to be stored internally. If you don't want interpolation, you
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001258 can use ``ConfigParser(interpolation=None)``.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001259
1260
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001261 .. method:: add_section(section)
1262
1263 Add a section named *section* to the instance. If a section by the given
1264 name already exists, :exc:`DuplicateSectionError` is raised. If the
1265 *default section* name is passed, :exc:`ValueError` is raised.
1266
1267 Type of *section* is not checked which lets users create non-string named
Łukasz Langa34cea142014-09-14 23:37:03 -07001268 sections. This behaviour is unsupported and may cause internal errors.
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001269
1270
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001271 .. method:: set(section, option, value)
1272
1273 If the given section exists, set the given option to the specified value;
1274 otherwise raise :exc:`NoSectionError`. While it is possible to use
1275 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters
1276 set to true) for *internal* storage of non-string values, full
1277 functionality (including interpolation and output to files) can only be
1278 achieved using string values.
1279
1280 This method lets users assign non-string values to keys internally. This
1281 behaviour is unsupported and will cause errors when attempting to write
1282 to a file or get it in non-raw mode. **Use the mapping protocol API**
1283 which does not allow such assignments to take place.
1284
1285
Łukasz Langa26d513c2010-11-10 18:57:39 +00001286Exceptions
1287----------
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001288
Łukasz Langa26d513c2010-11-10 18:57:39 +00001289.. exception:: Error
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001290
Fred Drake5a7c11f2010-11-13 05:24:17 +00001291 Base class for all other :mod:`configparser` exceptions.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001292
Georg Brandl48310cd2009-01-03 21:18:54 +00001293
Łukasz Langa26d513c2010-11-10 18:57:39 +00001294.. exception:: NoSectionError
Georg Brandl48310cd2009-01-03 21:18:54 +00001295
Łukasz Langa26d513c2010-11-10 18:57:39 +00001296 Exception raised when a specified section is not found.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001297
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001298
Łukasz Langa26d513c2010-11-10 18:57:39 +00001299.. exception:: DuplicateSectionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001300
Łukasz Langa26d513c2010-11-10 18:57:39 +00001301 Exception raised if :meth:`add_section` is called with the name of a section
1302 that is already present or in strict parsers when a section if found more
1303 than once in a single input file, string or dictionary.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001304
Łukasz Langa26d513c2010-11-10 18:57:39 +00001305 .. versionadded:: 3.2
1306 Optional ``source`` and ``lineno`` attributes and arguments to
1307 :meth:`__init__` were added.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001308
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001309
Łukasz Langa26d513c2010-11-10 18:57:39 +00001310.. exception:: DuplicateOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001311
Łukasz Langa26d513c2010-11-10 18:57:39 +00001312 Exception raised by strict parsers if a single option appears twice during
1313 reading from a single file, string or dictionary. This catches misspellings
1314 and case sensitivity-related errors, e.g. a dictionary may have two keys
1315 representing the same case-insensitive configuration key.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001316
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001317
Łukasz Langa26d513c2010-11-10 18:57:39 +00001318.. exception:: NoOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001319
Łukasz Langa26d513c2010-11-10 18:57:39 +00001320 Exception raised when a specified option is not found in the specified
1321 section.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001322
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001323
Łukasz Langa26d513c2010-11-10 18:57:39 +00001324.. exception:: InterpolationError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001325
Łukasz Langa26d513c2010-11-10 18:57:39 +00001326 Base class for exceptions raised when problems occur performing string
1327 interpolation.
Georg Brandl48310cd2009-01-03 21:18:54 +00001328
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001329
Łukasz Langa26d513c2010-11-10 18:57:39 +00001330.. exception:: InterpolationDepthError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001331
Łukasz Langa26d513c2010-11-10 18:57:39 +00001332 Exception raised when string interpolation cannot be completed because the
Georg Brandlbb27c122010-11-11 07:26:40 +00001333 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
Łukasz Langa26d513c2010-11-10 18:57:39 +00001334 :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001335
Fred Drake03c44a32010-02-19 06:08:41 +00001336
Łukasz Langa26d513c2010-11-10 18:57:39 +00001337.. exception:: InterpolationMissingOptionError
Fred Drake03c44a32010-02-19 06:08:41 +00001338
Georg Brandlbb27c122010-11-11 07:26:40 +00001339 Exception raised when an option referenced from a value does not exist.
1340 Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001341
Fred Drake03c44a32010-02-19 06:08:41 +00001342
Łukasz Langa26d513c2010-11-10 18:57:39 +00001343.. exception:: InterpolationSyntaxError
Fred Drake03c44a32010-02-19 06:08:41 +00001344
Georg Brandlbb27c122010-11-11 07:26:40 +00001345 Exception raised when the source text into which substitutions are made does
1346 not conform to the required syntax. Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001347
Łukasz Langa26d513c2010-11-10 18:57:39 +00001348
1349.. exception:: MissingSectionHeaderError
1350
Georg Brandlbb27c122010-11-11 07:26:40 +00001351 Exception raised when attempting to parse a file which has no section
1352 headers.
Łukasz Langa26d513c2010-11-10 18:57:39 +00001353
1354
1355.. exception:: ParsingError
1356
1357 Exception raised when errors occur attempting to parse a file.
1358
1359 .. versionchanged:: 3.2
1360 The ``filename`` attribute and :meth:`__init__` argument were renamed to
1361 ``source`` for consistency.
1362
Georg Brandlbb27c122010-11-11 07:26:40 +00001363
1364.. rubric:: Footnotes
1365
1366.. [1] Config parsers allow for heavy customization. If you are interested in
1367 changing the behaviour outlined by the footnote reference, consult the
1368 `Customizing Parser Behaviour`_ section.