<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>14.2. configparser — Configuration file parser — Python v3.3.2 documentation</title> <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '3.3.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python v3.3.2 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="top" title="Python v3.3.2 documentation" href="../index.html" /> <link rel="up" title="14. File Formats" href="fileformats.html" /> <link rel="next" title="14.3. netrc — netrc file processing" href="netrc.html" /> <link rel="prev" title="14.1. csv — CSV File Reading and Writing" href="csv.html" /> <link rel="shortcut icon" type="image/png" href="../_static/py.png" /> <script type="text/javascript" src="../_static/copybutton.js"></script> </head> <body> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="netrc.html" title="14.3. netrc — netrc file processing" accesskey="N">next</a> |</li> <li class="right" > <a href="csv.html" title="14.1. csv — CSV File Reading and Writing" accesskey="P">previous</a> |</li> <li><img src="../_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="http://www.python.org/">Python</a> »</li> <li> <a href="../index.html">3.3.2 Documentation</a> » </li> <li><a href="index.html" >The Python Standard Library</a> »</li> <li><a href="fileformats.html" accesskey="U">14. File Formats</a> »</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <div class="section" id="module-configparser"> <span id="configparser-configuration-file-parser"></span><h1>14.2. <a class="reference internal" href="#module-configparser" title="configparser: Configuration file parser."><tt class="xref py py-mod docutils literal"><span class="pre">configparser</span></tt></a> — Configuration file parser<a class="headerlink" href="#module-configparser" title="Permalink to this headline">¶</a></h1> <p id="index-0">This module provides the <a class="reference internal" href="#configparser.ConfigParser" title="configparser.ConfigParser"><tt class="xref py py-class docutils literal"><span class="pre">ConfigParser</span></tt></a> class which implements a basic configuration language which provides a structure similar to what’s found in Microsoft Windows INI files. You can use this to write Python programs which can be customized by end users easily.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">This library does <em>not</em> interpret or write the value-type prefixes used in the Windows Registry extended version of INI syntax.</p> </div> <div class="admonition-see-also admonition seealso"> <p class="first admonition-title">See also</p> <dl class="last docutils"> <dt>Module <a class="reference internal" href="shlex.html#module-shlex" title="shlex: Simple lexical analysis for Unix shell-like languages."><tt class="xref py py-mod docutils literal"><span class="pre">shlex</span></tt></a></dt> <dd>Support for a creating Unix shell-like mini-languages which can be used as an alternate format for application configuration files.</dd> <dt>Module <a class="reference internal" href="json.html#module-json" title="json: Encode and decode the JSON format."><tt class="xref py py-mod docutils literal"><span class="pre">json</span></tt></a></dt> <dd>The json module implements a subset of JavaScript syntax which can also be used for this purpose.</dd> </dl> </div> <div class="section" id="quick-start"> <h2>14.2.1. Quick Start<a class="headerlink" href="#quick-start" title="Permalink to this headline">¶</a></h2> <p>Let’s take a very basic configuration file that looks like this:</p> <div class="highlight-ini"><div class="highlight"><pre><span class="k">[DEFAULT]</span> <span class="na">ServerAliveInterval</span> <span class="o">=</span> <span class="s">45</span> <span class="na">Compression</span> <span class="o">=</span> <span class="s">yes</span> <span class="na">CompressionLevel</span> <span class="o">=</span> <span class="s">9</span> <span class="na">ForwardX11</span> <span class="o">=</span> <span class="s">yes</span> <span class="k">[bitbucket.org]</span> <span class="na">User</span> <span class="o">=</span> <span class="s">hg</span> <span class="k">[topsecret.server.com]</span> <span class="na">Port</span> <span class="o">=</span> <span class="s">50022</span> <span class="na">ForwardX11</span> <span class="o">=</span> <span class="s">no</span> </pre></div> </div> <p>The structure of INI files is described <a class="reference external" href="#supported-ini-file-structure">in the following section</a>. Essentially, the file consists of sections, each of which contains keys with values. <a class="reference internal" href="#module-configparser" title="configparser: Configuration file parser."><tt class="xref py py-mod docutils literal"><span class="pre">configparser</span></tt></a> classes can read and write such files. Let’s start by creating the above configuration file programatically.</p> <div class="highlight-python3"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">configparser</span> <span class="gp">>>> </span><span class="n">config</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">ConfigParser</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">config</span><span class="p">[</span><span class="s">'DEFAULT'</span><span class="p">]</span> <span class="o">=</span> <span class="p">{</span><span class="s">'ServerAliveInterval'</span><span class="p">:</span> <span class="s">'45'</span><span class="p">,</span> <span class="gp">... </span> <span class="s">'Compression'</span><span class="p">:</span> <span class="s">'yes'</span><span class="p">,</span> <span class="gp">... </span> <span class="s">'CompressionLevel'</span><span class="p">:</span> <span class="s">'9'</span><span class="p">}</span> <span class="gp">>>> </span><span class="n">config</span><span class="p">[</span><span class="s">'bitbucket.org'</span><span class="p">]</span> <span class="o">=</span> <span class="p">{}</span> <span class="gp">>>> </span><span class="n">config</span><span class="p">[</span><span class="s">'bitbucket.org'</span><span class="p">][</span><span class="s">'User'</span><span class="p">]</span> <span class="o">=</span> <span class="s">'hg'</span> <span class="gp">>>> </span><span class="n">config</span><span class="p">[</span><span class="s">'topsecret.server.com'</span><span class="p">]</span> <span class="o">=</span> <span class="p">{}</span> <span class="gp">>>> </span><span class="n">topsecret</span> <span class="o">=</span> <span class="n">config</span><span class="p">[</span><span class="s">'topsecret.server.com'</span><span class="p">]</span> <span class="gp">>>> </span><span class="n">topsecret</span><span class="p">[</span><span class="s">'Port'</span><span class="p">]</span> <span class="o">=</span> <span class="s">'50022'</span> <span class="c"># mutates the parser</span> <span class="gp">>>> </span><span class="n">topsecret</span><span class="p">[</span><span class="s">'ForwardX11'</span><span class="p">]</span> <span class="o">=</span> <span class="s">'no'</span> <span class="c"># same here</span> <span class="gp">>>> </span><span class="n">config</span><span class="p">[</span><span class="s">'DEFAULT'</span><span class="p">][</span><span class="s">'ForwardX11'</span><span class="p">]</span> <span class="o">=</span> <span class="s">'yes'</span> <span class="gp">>>> </span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s">'example.ini'</span><span class="p">,</span> <span class="s">'w'</span><span class="p">)</span> <span class="k">as</span> <span class="n">configfile</span><span class="p">:</span> <span class="gp">... </span> <span class="n">config</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">configfile</span><span class="p">)</span> <span class="gp">...</span> </pre></div> </div> <p>As you can see, we can treat a config parser much like a dictionary. There are differences, <a class="reference external" href="#mapping-protocol-access">outlined later</a>, but the behavior is very close to what you would expect from a dictionary.</p> <p>Now that we have created and saved a configuration file, let’s read it back and explore the data it holds.</p> <div class="highlight-python3"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">configparser</span> <span class="gp">>>> </span><span class="n">config</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">ConfigParser</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">config</span><span class="o">.</span><span class="n">sections</span><span class="p">()</span> <span class="go">[]</span> <span class="gp">>>> </span><span class="n">config</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="s">'example.ini'</span><span class="p">)</span> <span class="go">['example.ini']</span> <span class="gp">>>> </span><span class="n">config</span><span class="o">.</span><span class="n">sections</span><span class="p">()</span> <span class="go">['bitbucket.org', 'topsecret.server.com']</span> <span class="gp">>>> </span><span class="s">'bitbucket.org'</span> <span class="ow">in</span> <span class="n">config</span> <span class="go">True</span> <span class="gp">>>> </span><span class="s">'bytebong.com'</span> <span class="ow">in</span> <span class="n">config</span> <span class="go">False</span> <span class="gp">>>> </span><span class="n">config</span><span class="p">[</span><span class="s">'bitbucket.org'</span><span class="p">][</span><span class="s">'User'</span><span class="p">]</span> <span class="go">'hg'</span> <span class="gp">>>> </span><span class="n">config</span><span class="p">[</span><span class="s">'DEFAULT'</span><span class="p">][</span><span class="s">'Compression'</span><span class="p">]</span> <span class="go">'yes'</span> <span class="gp">>>> </span><span class="n">topsecret</span> <span class="o">=</span> <span class="n">config</span><span class="p">[</span><span class="s">'topsecret.server.com'</span><span class="p">]</span> <span class="gp">>>> </span><span class="n">topsecret</span><span class="p">[</span><span class="s">'ForwardX11'</span><span class="p">]</span> <span class="go">'no'</span> <span class="gp">>>> </span><span class="n">topsecret</span><span class="p">[</span><span class="s">'Port'</span><span class="p">]</span> <span class="go">'50022'</span> <span class="gp">>>> </span><span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">config</span><span class="p">[</span><span class="s">'bitbucket.org'</span><span class="p">]:</span> <span class="nb">print</span><span class="p">(</span><span class="n">key</span><span class="p">)</span> <span class="gp">...</span> <span class="go">user</span> <span class="go">compressionlevel</span> <span class="go">serveraliveinterval</span> <span class="go">compression</span> <span class="go">forwardx11</span> <span class="gp">>>> </span><span class="n">config</span><span class="p">[</span><span class="s">'bitbucket.org'</span><span class="p">][</span><span class="s">'ForwardX11'</span><span class="p">]</span> <span class="go">'yes'</span> </pre></div> </div> <p>As we can see above, the API is pretty straightforward. The only bit of magic involves the <tt class="docutils literal"><span class="pre">DEFAULT</span></tt> section which provides default values for all other sections <a class="footnote-reference" href="#id13" id="id1">[1]</a>. Note also that keys in sections are case-insensitive and stored in lowercase <a class="footnote-reference" href="#id13" id="id2">[1]</a>.</p> </div> <div class="section" id="supported-datatypes"> <h2>14.2.2. Supported Datatypes<a class="headerlink" href="#supported-datatypes" title="Permalink to this headline">¶</a></h2> <p>Config parsers do not guess datatypes of values in configuration files, always storing them internally as strings. This means that if you need other datatypes, you should convert on your own:</p> <div class="highlight-python3"><div class="highlight"><pre><span class="gp">>>> </span><span class="nb">int</span><span class="p">(</span><span class="n">topsecret</span><span class="p">[</span><span class="s">'Port'</span><span class="p">])</span> <span class="go">50022</span> <span class="gp">>>> </span><span class="nb">float</span><span class="p">(</span><span class="n">topsecret</span><span class="p">[</span><span class="s">'CompressionLevel'</span><span class="p">])</span> <span class="go">9.0</span> </pre></div> </div> <p>Extracting Boolean values is not that simple, though. Passing the value to <tt class="docutils literal"><span class="pre">bool()</span></tt> would do no good since <tt class="docutils literal"><span class="pre">bool('False')</span></tt> is still <tt class="xref docutils literal"><span class="pre">True</span></tt>. This is why config parsers also provide <tt class="xref py py-meth docutils literal"><span class="pre">getboolean()</span></tt>. This method is case-insensitive and recognizes Boolean values from <tt class="docutils literal"><span class="pre">'yes'</span></tt>/<tt class="docutils literal"><span class="pre">'no'</span></tt>, <tt class="docutils literal"><span class="pre">'on'</span></tt>/<tt class="docutils literal"><span class="pre">'off'</span></tt> and <tt class="docutils literal"><span class="pre">'1'</span></tt>/<tt class="docutils literal"><span class="pre">'0'</span></tt> <a class="footnote-reference" href="#id13" id="id3">[1]</a>. For example:</p> <div class="highlight-python3"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">topsecret</span><span class="o">.</span><span class="n">getboolean</span><span class="p">(</span><span class="s">'ForwardX11'</span><span class="p">)</span> <span class="go">False</span> <span class="gp">>>> </span><span class="n">config</span><span class="p">[</span><span class="s">'bitbucket.org'</span><span class="p">]</span><span class="o">.</span><span class="n">getboolean</span><span class="p">(</span><span class="s">'ForwardX11'</span><span class="p">)</span> <span class="go">True</span> <span class="gp">>>> </span><span class="n">config</span><span class="o">.</span><span class="n">getboolean</span><span class="p">(</span><span class="s">'bitbucket.org'</span><span class="p">,</span> <span class="s">'Compression'</span><span class="p">)</span> <span class="go">True</span> </pre></div> </div> <p>Apart from <tt class="xref py py-meth docutils literal"><span class="pre">getboolean()</span></tt>, config parsers also provide equivalent <tt class="xref py py-meth docutils literal"><span class="pre">getint()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">getfloat()</span></tt> methods, but these are far less useful since conversion using <a class="reference internal" href="functions.html#int" title="int"><tt class="xref py py-func docutils literal"><span class="pre">int()</span></tt></a> and <a class="reference internal" href="functions.html#float" title="float"><tt class="xref py py-func docutils literal"><span class="pre">float()</span></tt></a> is sufficient for these types.</p> </div> <div class="section" id="fallback-values"> <h2>14.2.3. Fallback Values<a class="headerlink" href="#fallback-values" title="Permalink to this headline">¶</a></h2> <p>As with a dictionary, you can use a section’s <tt class="xref py py-meth docutils literal"><span class="pre">get()</span></tt> method to provide fallback values:</p> <div class="highlight-python3"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">topsecret</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'Port'</span><span class="p">)</span> <span class="go">'50022'</span> <span class="gp">>>> </span><span class="n">topsecret</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'CompressionLevel'</span><span class="p">)</span> <span class="go">'9'</span> <span class="gp">>>> </span><span class="n">topsecret</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'Cipher'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">topsecret</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'Cipher'</span><span class="p">,</span> <span class="s">'3des-cbc'</span><span class="p">)</span> <span class="go">'3des-cbc'</span> </pre></div> </div> <p>Please note that default values have precedence over fallback values. For instance, in our example the <tt class="docutils literal"><span class="pre">'CompressionLevel'</span></tt> key was specified only in the <tt class="docutils literal"><span class="pre">'DEFAULT'</span></tt> section. If we try to get it from the section <tt class="docutils literal"><span class="pre">'topsecret.server.com'</span></tt>, we will always get the default, even if we specify a fallback:</p> <div class="highlight-python3"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">topsecret</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'CompressionLevel'</span><span class="p">,</span> <span class="s">'3'</span><span class="p">)</span> <span class="go">'9'</span> </pre></div> </div> <p>One more thing to be aware of is that the parser-level <tt class="xref py py-meth docutils literal"><span class="pre">get()</span></tt> method provides a custom, more complex interface, maintained for backwards compatibility. When using this method, a fallback value can be provided via the <tt class="docutils literal"><span class="pre">fallback</span></tt> keyword-only argument:</p> <div class="highlight-python3"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">config</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'bitbucket.org'</span><span class="p">,</span> <span class="s">'monster'</span><span class="p">,</span> <span class="gp">... </span> <span class="n">fallback</span><span class="o">=</span><span class="s">'No such things as monsters'</span><span class="p">)</span> <span class="go">'No such things as monsters'</span> </pre></div> </div> <p>The same <tt class="docutils literal"><span class="pre">fallback</span></tt> argument can be used with the <tt class="xref py py-meth docutils literal"><span class="pre">getint()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">getfloat()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">getboolean()</span></tt> methods, for example:</p> <div class="highlight-python3"><div class="highlight"><pre><span class="gp">>>> </span><span class="s">'BatchMode'</span> <span class="ow">in</span> <span class="n">topsecret</span> <span class="go">False</span> <span class="gp">>>> </span><span class="n">topsecret</span><span class="o">.</span><span class="n">getboolean</span><span class="p">(</span><span class="s">'BatchMode'</span><span class="p">,</span> <span class="n">fallback</span><span class="o">=</span><span class="k">True</span><span class="p">)</span> <span class="go">True</span> <span class="gp">>>> </span><span class="n">config</span><span class="p">[</span><span class="s">'DEFAULT'</span><span class="p">][</span><span class="s">'BatchMode'</span><span class="p">]</span> <span class="o">=</span> <span class="s">'no'</span> <span class="gp">>>> </span><span class="n">topsecret</span><span class="o">.</span><span class="n">getboolean</span><span class="p">(</span><span class="s">'BatchMode'</span><span class="p">,</span> <span class="n">fallback</span><span class="o">=</span><span class="k">True</span><span class="p">)</span> <span class="go">False</span> </pre></div> </div> </div> <div class="section" id="supported-ini-file-structure"> <h2>14.2.4. Supported INI File Structure<a class="headerlink" href="#supported-ini-file-structure" title="Permalink to this headline">¶</a></h2> <p>A configuration file consists of sections, each led by a <tt class="docutils literal"><span class="pre">[section]</span></tt> header, followed by key/value entries separated by a specific string (<tt class="docutils literal"><span class="pre">=</span></tt> or <tt class="docutils literal"><span class="pre">:</span></tt> by default <a class="footnote-reference" href="#id13" id="id4">[1]</a>). By default, section names are case sensitive but keys are not <a class="footnote-reference" href="#id13" id="id5">[1]</a>. Leading and trailing whitespace is removed from keys and values. Values can be omitted, in which case the key/value delimiter may also be left out. Values can also span multiple lines, as long as they are indented deeper than the first line of the value. Depending on the parser’s mode, blank lines may be treated as parts of multiline values or ignored.</p> <p>Configuration files may include comments, prefixed by specific characters (<tt class="docutils literal"><span class="pre">#</span></tt> and <tt class="docutils literal"><span class="pre">;</span></tt> by default <a class="footnote-reference" href="#id13" id="id6">[1]</a>). Comments may appear on their own on an otherwise empty line, possibly indented. <a class="footnote-reference" href="#id13" id="id7">[1]</a></p> <p>For example:</p> <div class="highlight-ini"><pre>[Simple Values] key=value spaces in keys=allowed spaces in values=allowed as well spaces around the delimiter = obviously you can also use : to delimit keys from values [All Values Are Strings] values like this: 1000000 or this: 3.14159265359 are they treated as numbers? : no integers, floats and booleans are held as: strings can use the API to get converted values directly: true [Multiline Values] chorus: I'm a lumberjack, and I'm okay I sleep all night and I work all day [No Values] key_without_value empty string value here = [You can use comments] # like this ; or this # By default only in an empty line. # Inline comments can be harmful because they prevent users # from using the delimiting characters as parts of values. # That being said, this can be customized. [Sections Can Be Indented] can_values_be_as_well = True does_that_mean_anything_special = False purpose = formatting for readability multiline_values = are handled just fine as long as they are indented deeper than the first line of a value # Did I mention we can indent comments, too?</pre> </div> </div> <div class="section" id="interpolation-of-values"> <h2>14.2.5. Interpolation of values<a class="headerlink" href="#interpolation-of-values" title="Permalink to this headline">¶</a></h2> <p>On top of the core functionality, <a class="reference internal" href="#configparser.ConfigParser" title="configparser.ConfigParser"><tt class="xref py py-class docutils literal"><span class="pre">ConfigParser</span></tt></a> supports interpolation. This means values can be preprocessed before returning them from <tt class="docutils literal"><span class="pre">get()</span></tt> calls.</p> <dl class="class"> <dt id="configparser.BasicInterpolation"> <em class="property">class </em><tt class="descclassname">configparser.</tt><tt class="descname">BasicInterpolation</tt><a class="headerlink" href="#configparser.BasicInterpolation" title="Permalink to this definition">¶</a></dt> <dd><p>The default implementation used by <a class="reference internal" href="#configparser.ConfigParser" title="configparser.ConfigParser"><tt class="xref py py-class docutils literal"><span class="pre">ConfigParser</span></tt></a>. It enables values to contain format strings which refer to other values in the same section, or values in the special default section <a class="footnote-reference" href="#id13" id="id8">[1]</a>. Additional default values can be provided on initialization.</p> <p>For example:</p> <div class="highlight-ini"><pre>[Paths] home_dir: /Users my_dir: %(home_dir)s/lumberjack my_pictures: %(my_dir)s/Pictures</pre> </div> <p>In the example above, <a class="reference internal" href="#configparser.ConfigParser" title="configparser.ConfigParser"><tt class="xref py py-class docutils literal"><span class="pre">ConfigParser</span></tt></a> with <em>interpolation</em> set to <tt class="docutils literal"><span class="pre">BasicInterpolation()</span></tt> would resolve <tt class="docutils literal"><span class="pre">%(home_dir)s</span></tt> to the value of <tt class="docutils literal"><span class="pre">home_dir</span></tt> (<tt class="docutils literal"><span class="pre">/Users</span></tt> in this case). <tt class="docutils literal"><span class="pre">%(my_dir)s</span></tt> in effect would resolve to <tt class="docutils literal"><span class="pre">/Users/lumberjack</span></tt>. All interpolations are done on demand so keys used in the chain of references do not have to be specified in any specific order in the configuration file.</p> <p>With <tt class="docutils literal"><span class="pre">interpolation</span></tt> set to <tt class="xref docutils literal"><span class="pre">None</span></tt>, the parser would simply return <tt class="docutils literal"><span class="pre">%(my_dir)s/Pictures</span></tt> as the value of <tt class="docutils literal"><span class="pre">my_pictures</span></tt> and <tt class="docutils literal"><span class="pre">%(home_dir)s/lumberjack</span></tt> as the value of <tt class="docutils literal"><span class="pre">my_dir</span></tt>.</p> </dd></dl> <dl class="class"> <dt id="configparser.ExtendedInterpolation"> <em class="property">class </em><tt class="descclassname">configparser.</tt><tt class="descname">ExtendedInterpolation</tt><a class="headerlink" href="#configparser.ExtendedInterpolation" title="Permalink to this definition">¶</a></dt> <dd><p>An alternative handler for interpolation which implements a more advanced syntax, used for instance in <tt class="docutils literal"><span class="pre">zc.buildout</span></tt>. Extended interpolation is using <tt class="docutils literal"><span class="pre">${section:option}</span></tt> to denote a value from a foreign section. Interpolation can span multiple levels. For convenience, if the <tt class="docutils literal"><span class="pre">section:</span></tt> part is omitted, interpolation defaults to the current section (and possibly the default values from the special section).</p> <p>For example, the configuration specified above with basic interpolation, would look like this with extended interpolation:</p> <div class="highlight-ini"><pre>[Paths] home_dir: /Users my_dir: ${home_dir}/lumberjack my_pictures: ${my_dir}/Pictures</pre> </div> <p>Values from other sections can be fetched as well:</p> <div class="highlight-ini"><pre>[Common] home_dir: /Users library_dir: /Library system_dir: /System macports_dir: /opt/local [Frameworks] Python: 3.2 path: ${Common:system_dir}/Library/Frameworks/ [Arthur] nickname: Two Sheds last_name: Jackson my_dir: ${Common:home_dir}/twosheds my_pictures: ${my_dir}/Pictures python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}</pre> </div> </dd></dl> </div> <div class="section" id="mapping-protocol-access"> <h2>14.2.6. Mapping Protocol Access<a class="headerlink" href="#mapping-protocol-access" title="Permalink to this headline">¶</a></h2> <p class="versionadded"> <span class="versionmodified">New in version 3.2.</span> </p> <p>Mapping protocol access is a generic name for functionality that enables using custom objects as if they were dictionaries. In case of <a class="reference internal" href="#module-configparser" title="configparser: Configuration file parser."><tt class="xref py py-mod docutils literal"><span class="pre">configparser</span></tt></a>, the mapping interface implementation is using the <tt class="docutils literal"><span class="pre">parser['section']['option']</span></tt> notation.</p> <p><tt class="docutils literal"><span class="pre">parser['section']</span></tt> in particular returns a proxy for the section’s data in the parser. This means that the values are not copied but they are taken from the original parser on demand. What’s even more important is that when values are changed on a section proxy, they are actually mutated in the original parser.</p> <p><a class="reference internal" href="#module-configparser" title="configparser: Configuration file parser."><tt class="xref py py-mod docutils literal"><span class="pre">configparser</span></tt></a> objects behave as close to actual dictionaries as possible. The mapping interface is complete and adheres to the <tt class="docutils literal"><span class="pre">MutableMapping</span></tt> ABC. However, there are a few differences that should be taken into account:</p> <ul> <li><p class="first">By default, all keys in sections are accessible in a case-insensitive manner <a class="footnote-reference" href="#id13" id="id9">[1]</a>. E.g. <tt class="docutils literal"><span class="pre">for</span> <span class="pre">option</span> <span class="pre">in</span> <span class="pre">parser["section"]</span></tt> yields only <tt class="docutils literal"><span class="pre">optionxform</span></tt>‘ed option key names. This means lowercased keys by default. At the same time, for a section that holds the key <tt class="docutils literal"><span class="pre">'a'</span></tt>, both expressions return <tt class="xref docutils literal"><span class="pre">True</span></tt>:</p> <div class="highlight-python3"><div class="highlight"><pre><span class="s">"a"</span> <span class="ow">in</span> <span class="n">parser</span><span class="p">[</span><span class="s">"section"</span><span class="p">]</span> <span class="s">"A"</span> <span class="ow">in</span> <span class="n">parser</span><span class="p">[</span><span class="s">"section"</span><span class="p">]</span> </pre></div> </div> </li> <li><p class="first">All sections include <tt class="docutils literal"><span class="pre">DEFAULTSECT</span></tt> values as well which means that <tt class="docutils literal"><span class="pre">.clear()</span></tt> on a section may not leave the section visibly empty. This is because default values cannot be deleted from the section (because technically they are not there). If they are overriden in the section, deleting causes the default value to be visible again. Trying to delete a default value causes a <tt class="docutils literal"><span class="pre">KeyError</span></tt>.</p> </li> <li><p class="first"><tt class="docutils literal"><span class="pre">DEFAULTSECT</span></tt> cannot be removed from the parser:</p> <ul class="simple"> <li>trying to delete it raises <tt class="docutils literal"><span class="pre">ValueError</span></tt>,</li> <li><tt class="docutils literal"><span class="pre">parser.clear()</span></tt> leaves it intact,</li> <li><tt class="docutils literal"><span class="pre">parser.popitem()</span></tt> never returns it.</li> </ul> </li> <li><p class="first"><tt class="docutils literal"><span class="pre">parser.get(section,</span> <span class="pre">option,</span> <span class="pre">**kwargs)</span></tt> - the second argument is <strong>not</strong> a fallback value. Note however that the section-level <tt class="docutils literal"><span class="pre">get()</span></tt> methods are compatible both with the mapping protocol and the classic configparser API.</p> </li> <li><p class="first"><tt class="docutils literal"><span class="pre">parser.items()</span></tt> is compatible with the mapping protocol (returns a list of <em>section_name</em>, <em>section_proxy</em> pairs including the DEFAULTSECT). However, this method can also be invoked with arguments: <tt class="docutils literal"><span class="pre">parser.items(section,</span> <span class="pre">raw,</span> <span class="pre">vars)</span></tt>. The latter call returns a list of <em>option</em>, <em>value</em> pairs for a specified <tt class="docutils literal"><span class="pre">section</span></tt>, with all interpolations expanded (unless <tt class="docutils literal"><span class="pre">raw=True</span></tt> is provided).</p> </li> </ul> <p>The mapping protocol is implemented on top of the existing legacy API so that subclasses overriding the original interface still should have mappings working as expected.</p> </div> <div class="section" id="customizing-parser-behaviour"> <h2>14.2.7. Customizing Parser Behaviour<a class="headerlink" href="#customizing-parser-behaviour" title="Permalink to this headline">¶</a></h2> <p>There are nearly as many INI format variants as there are applications using it. <a class="reference internal" href="#module-configparser" title="configparser: Configuration file parser."><tt class="xref py py-mod docutils literal"><span class="pre">configparser</span></tt></a> goes a long way to provide support for the largest sensible set of INI styles available. The default functionality is mainly dictated by historical background and it’s very likely that you will want to customize some of the features.</p> <p>The most common way to change the way a specific config parser works is to use the <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> options:</p> <ul> <li><p class="first"><em>defaults</em>, default value: <tt class="xref docutils literal"><span class="pre">None</span></tt></p> <p>This option accepts a dictionary of key-value pairs which will be initially put in the <tt class="docutils literal"><span class="pre">DEFAULT</span></tt> section. This makes for an elegant way to support concise configuration files that don’t specify values which are the same as the documented default.</p> <p>Hint: if you want to specify default values for a specific section, use <tt class="xref py py-meth docutils literal"><span class="pre">read_dict()</span></tt> before you read the actual file.</p> </li> <li><p class="first"><em>dict_type</em>, default value: <a class="reference internal" href="collections.html#collections.OrderedDict" title="collections.OrderedDict"><tt class="xref py py-class docutils literal"><span class="pre">collections.OrderedDict</span></tt></a></p> <p>This option has a major impact on how the mapping protocol will behave and how the written configuration files look. With the default ordered dictionary, every section is stored in the order they were added to the parser. Same goes for options within sections.</p> <p>An alternative dictionary type can be used for example to sort sections and options on write-back. You can also use a regular dictionary for performance reasons.</p> <p>Please note: there are ways to add a set of key-value pairs in a single operation. When you use a regular dictionary in those operations, the order of the keys may be random. For example:</p> <div class="highlight-python3"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">parser</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">ConfigParser</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">parser</span><span class="o">.</span><span class="n">read_dict</span><span class="p">({</span><span class="s">'section1'</span><span class="p">:</span> <span class="p">{</span><span class="s">'key1'</span><span class="p">:</span> <span class="s">'value1'</span><span class="p">,</span> <span class="gp">... </span> <span class="s">'key2'</span><span class="p">:</span> <span class="s">'value2'</span><span class="p">,</span> <span class="gp">... </span> <span class="s">'key3'</span><span class="p">:</span> <span class="s">'value3'</span><span class="p">},</span> <span class="gp">... </span> <span class="s">'section2'</span><span class="p">:</span> <span class="p">{</span><span class="s">'keyA'</span><span class="p">:</span> <span class="s">'valueA'</span><span class="p">,</span> <span class="gp">... </span> <span class="s">'keyB'</span><span class="p">:</span> <span class="s">'valueB'</span><span class="p">,</span> <span class="gp">... </span> <span class="s">'keyC'</span><span class="p">:</span> <span class="s">'valueC'</span><span class="p">},</span> <span class="gp">... </span> <span class="s">'section3'</span><span class="p">:</span> <span class="p">{</span><span class="s">'foo'</span><span class="p">:</span> <span class="s">'x'</span><span class="p">,</span> <span class="gp">... </span> <span class="s">'bar'</span><span class="p">:</span> <span class="s">'y'</span><span class="p">,</span> <span class="gp">... </span> <span class="s">'baz'</span><span class="p">:</span> <span class="s">'z'</span><span class="p">}</span> <span class="gp">... </span><span class="p">})</span> <span class="gp">>>> </span><span class="n">parser</span><span class="o">.</span><span class="n">sections</span><span class="p">()</span> <span class="go">['section3', 'section2', 'section1']</span> <span class="gp">>>> </span><span class="p">[</span><span class="n">option</span> <span class="k">for</span> <span class="n">option</span> <span class="ow">in</span> <span class="n">parser</span><span class="p">[</span><span class="s">'section3'</span><span class="p">]]</span> <span class="go">['baz', 'foo', 'bar']</span> </pre></div> </div> <p>In these operations you need to use an ordered dictionary as well:</p> <div class="highlight-python3"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">collections</span> <span class="k">import</span> <span class="n">OrderedDict</span> <span class="gp">>>> </span><span class="n">parser</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">ConfigParser</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">parser</span><span class="o">.</span><span class="n">read_dict</span><span class="p">(</span> <span class="gp">... </span> <span class="n">OrderedDict</span><span class="p">((</span> <span class="gp">... </span> <span class="p">(</span><span class="s">'s1'</span><span class="p">,</span> <span class="gp">... </span> <span class="n">OrderedDict</span><span class="p">((</span> <span class="gp">... </span> <span class="p">(</span><span class="s">'1'</span><span class="p">,</span> <span class="s">'2'</span><span class="p">),</span> <span class="gp">... </span> <span class="p">(</span><span class="s">'3'</span><span class="p">,</span> <span class="s">'4'</span><span class="p">),</span> <span class="gp">... </span> <span class="p">(</span><span class="s">'5'</span><span class="p">,</span> <span class="s">'6'</span><span class="p">),</span> <span class="gp">... </span> <span class="p">))</span> <span class="gp">... </span> <span class="p">),</span> <span class="gp">... </span> <span class="p">(</span><span class="s">'s2'</span><span class="p">,</span> <span class="gp">... </span> <span class="n">OrderedDict</span><span class="p">((</span> <span class="gp">... </span> <span class="p">(</span><span class="s">'a'</span><span class="p">,</span> <span class="s">'b'</span><span class="p">),</span> <span class="gp">... </span> <span class="p">(</span><span class="s">'c'</span><span class="p">,</span> <span class="s">'d'</span><span class="p">),</span> <span class="gp">... </span> <span class="p">(</span><span class="s">'e'</span><span class="p">,</span> <span class="s">'f'</span><span class="p">),</span> <span class="gp">... </span> <span class="p">))</span> <span class="gp">... </span> <span class="p">),</span> <span class="gp">... </span> <span class="p">))</span> <span class="gp">... </span><span class="p">)</span> <span class="gp">>>> </span><span class="n">parser</span><span class="o">.</span><span class="n">sections</span><span class="p">()</span> <span class="go">['s1', 's2']</span> <span class="gp">>>> </span><span class="p">[</span><span class="n">option</span> <span class="k">for</span> <span class="n">option</span> <span class="ow">in</span> <span class="n">parser</span><span class="p">[</span><span class="s">'s1'</span><span class="p">]]</span> <span class="go">['1', '3', '5']</span> <span class="gp">>>> </span><span class="p">[</span><span class="n">option</span> <span class="k">for</span> <span class="n">option</span> <span class="ow">in</span> <span class="n">parser</span><span class="p">[</span><span class="s">'s2'</span><span class="p">]</span><span class="o">.</span><span class="n">values</span><span class="p">()]</span> <span class="go">['b', 'd', 'f']</span> </pre></div> </div> </li> <li><p class="first"><em>allow_no_value</em>, default value: <tt class="xref docutils literal"><span class="pre">False</span></tt></p> <p>Some configuration files are known to include settings without values, but which otherwise conform to the syntax supported by <a class="reference internal" href="#module-configparser" title="configparser: Configuration file parser."><tt class="xref py py-mod docutils literal"><span class="pre">configparser</span></tt></a>. The <em>allow_no_value</em> parameter to the constructor can be used to indicate that such values should be accepted:</p> <div class="highlight-python3"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">configparser</span> <span class="gp">>>> </span><span class="n">sample_config</span> <span class="o">=</span> <span class="s">"""</span> <span class="gp">... </span><span class="s">[mysqld]</span> <span class="gp">... </span><span class="s"> user = mysql</span> <span class="gp">... </span><span class="s"> pid-file = /var/run/mysqld/mysqld.pid</span> <span class="gp">... </span><span class="s"> skip-external-locking</span> <span class="gp">... </span><span class="s"> old_passwords = 1</span> <span class="gp">... </span><span class="s"> skip-bdb</span> <span class="gp">... </span><span class="s"> # we don't need ACID today</span> <span class="gp">... </span><span class="s"> skip-innodb</span> <span class="gp">... </span><span class="s">"""</span> <span class="gp">>>> </span><span class="n">config</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">ConfigParser</span><span class="p">(</span><span class="n">allow_no_value</span><span class="o">=</span><span class="k">True</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">config</span><span class="o">.</span><span class="n">read_string</span><span class="p">(</span><span class="n">sample_config</span><span class="p">)</span> <span class="gp">>>> </span><span class="c"># Settings with values are treated as before:</span> <span class="gp">>>> </span><span class="n">config</span><span class="p">[</span><span class="s">"mysqld"</span><span class="p">][</span><span class="s">"user"</span><span class="p">]</span> <span class="go">'mysql'</span> <span class="gp">>>> </span><span class="c"># Settings without values provide None:</span> <span class="gp">>>> </span><span class="n">config</span><span class="p">[</span><span class="s">"mysqld"</span><span class="p">][</span><span class="s">"skip-bdb"</span><span class="p">]</span> <span class="gp">>>> </span><span class="c"># Settings which aren't specified still raise an error:</span> <span class="gp">>>> </span><span class="n">config</span><span class="p">[</span><span class="s">"mysqld"</span><span class="p">][</span><span class="s">"does-not-exist"</span><span class="p">]</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">KeyError</span>: <span class="n">'does-not-exist'</span> </pre></div> </div> </li> <li><p class="first"><em>delimiters</em>, default value: <tt class="docutils literal"><span class="pre">('=',</span> <span class="pre">':')</span></tt></p> <p>Delimiters are substrings that delimit keys from values within a section. The first occurence of a delimiting substring on a line is considered a delimiter. This means values (but not keys) can contain the delimiters.</p> <p>See also the <em>space_around_delimiters</em> argument to <a class="reference internal" href="#configparser.ConfigParser.write" title="configparser.ConfigParser.write"><tt class="xref py py-meth docutils literal"><span class="pre">ConfigParser.write()</span></tt></a>.</p> </li> <li><p class="first"><em>comment_prefixes</em>, default value: <tt class="docutils literal"><span class="pre">('#',</span> <span class="pre">';')</span></tt></p> </li> <li><p class="first"><em>inline_comment_prefixes</em>, default value: <tt class="xref docutils literal"><span class="pre">None</span></tt></p> <p>Comment prefixes are strings that indicate the start of a valid comment within a config file. <em>comment_prefixes</em> are used only on otherwise empty lines (optionally indented) whereas <em>inline_comment_prefixes</em> can be used after every valid value (e.g. section names, options and empty lines as well). By default inline comments are disabled and <tt class="docutils literal"><span class="pre">'#'</span></tt> and <tt class="docutils literal"><span class="pre">';'</span></tt> are used as prefixes for whole line comments.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 3.2:</span> In previous versions of <a class="reference internal" href="#module-configparser" title="configparser: Configuration file parser."><tt class="xref py py-mod docutils literal"><span class="pre">configparser</span></tt></a> behaviour matched <tt class="docutils literal"><span class="pre">comment_prefixes=('#',';')</span></tt> and <tt class="docutils literal"><span class="pre">inline_comment_prefixes=(';',)</span></tt>.</p> <p>Please note that config parsers don’t support escaping of comment prefixes so using <em>inline_comment_prefixes</em> may prevent users from specifying option values with characters used as comment prefixes. When in doubt, avoid setting <em>inline_comment_prefixes</em>. In any circumstances, the only way of storing comment prefix characters at the beginning of a line in multiline values is to interpolate the prefix, for example:</p> <div class="highlight-python3"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">configparser</span> <span class="k">import</span> <span class="n">ConfigParser</span><span class="p">,</span> <span class="n">ExtendedInterpolation</span> <span class="gp">>>> </span><span class="n">parser</span> <span class="o">=</span> <span class="n">ConfigParser</span><span class="p">(</span><span class="n">interpolation</span><span class="o">=</span><span class="n">ExtendedInterpolation</span><span class="p">())</span> <span class="gp">>>> </span><span class="c"># the default BasicInterpolation could be used as well</span> <span class="gp">>>> </span><span class="n">parser</span><span class="o">.</span><span class="n">read_string</span><span class="p">(</span><span class="s">"""</span> <span class="gp">... </span><span class="s">[DEFAULT]</span> <span class="gp">... </span><span class="s">hash = #</span> <span class="gp">...</span><span class="s"></span> <span class="gp">... </span><span class="s">[hashes]</span> <span class="gp">... </span><span class="s">shebang =</span> <span class="gp">... </span><span class="s"> ${hash}!/usr/bin/env python</span> <span class="gp">... </span><span class="s"> ${hash} -*- coding: utf-8 -*-</span> <span class="gp">...</span><span class="s"></span> <span class="gp">... </span><span class="s">extensions =</span> <span class="gp">... </span><span class="s"> enabled_extension</span> <span class="gp">... </span><span class="s"> another_extension</span> <span class="gp">... </span><span class="s"> #disabled_by_comment</span> <span class="gp">... </span><span class="s"> yet_another_extension</span> <span class="gp">...</span><span class="s"></span> <span class="gp">... </span><span class="s">interpolation not necessary = if # is not at line start</span> <span class="gp">... </span><span class="s">even in multiline values = line #1</span> <span class="gp">... </span><span class="s"> line #2</span> <span class="gp">... </span><span class="s"> line #3</span> <span class="gp">... </span><span class="s">"""</span><span class="p">)</span> <span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">parser</span><span class="p">[</span><span class="s">'hashes'</span><span class="p">][</span><span class="s">'shebang'</span><span class="p">])</span> <span class="go">#!/usr/bin/env python</span> <span class="go"># -*- coding: utf-8 -*-</span> <span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">parser</span><span class="p">[</span><span class="s">'hashes'</span><span class="p">][</span><span class="s">'extensions'</span><span class="p">])</span> <span class="go">enabled_extension</span> <span class="go">another_extension</span> <span class="go">yet_another_extension</span> <span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">parser</span><span class="p">[</span><span class="s">'hashes'</span><span class="p">][</span><span class="s">'interpolation not necessary'</span><span class="p">])</span> <span class="go">if # is not at line start</span> <span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">parser</span><span class="p">[</span><span class="s">'hashes'</span><span class="p">][</span><span class="s">'even in multiline values'</span><span class="p">])</span> <span class="go">line #1</span> <span class="go">line #2</span> <span class="go">line #3</span> </pre></div> </div> </li> <li><p class="first"><em>strict</em>, default value: <tt class="xref docutils literal"><span class="pre">True</span></tt></p> <p>When set to <tt class="xref docutils literal"><span class="pre">True</span></tt>, the parser will not allow for any section or option duplicates while reading from a single source (using <tt class="xref py py-meth docutils literal"><span class="pre">read_file()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">read_string()</span></tt> or <tt class="xref py py-meth docutils literal"><span class="pre">read_dict()</span></tt>). It is recommended to use strict parsers in new applications.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 3.2:</span> In previous versions of <a class="reference internal" href="#module-configparser" title="configparser: Configuration file parser."><tt class="xref py py-mod docutils literal"><span class="pre">configparser</span></tt></a> behaviour matched <tt class="docutils literal"><span class="pre">strict=False</span></tt>.</p> </li> <li><p class="first"><em>empty_lines_in_values</em>, default value: <tt class="xref docutils literal"><span class="pre">True</span></tt></p> <p>In config parsers, values can span multiple lines as long as they are indented more than the key that holds them. By default parsers also let empty lines to be parts of values. At the same time, keys can be arbitrarily indented themselves to improve readability. In consequence, when configuration files get big and complex, it is easy for the user to lose track of the file structure. Take for instance:</p> <div class="highlight-ini"><div class="highlight"><pre><span class="k">[Section]</span> <span class="na">key</span> <span class="o">=</span> <span class="s">multiline</span> <span class="s"> value with a gotcha</span> <span class="na">this</span> <span class="o">=</span> <span class="s">is still a part of the multiline value of 'key'</span> </pre></div> </div> <p>This can be especially problematic for the user to see if she’s using a proportional font to edit the file. That is why when your application does not need values with empty lines, you should consider disallowing them. This will make empty lines split keys every time. In the example above, it would produce two keys, <tt class="docutils literal"><span class="pre">key</span></tt> and <tt class="docutils literal"><span class="pre">this</span></tt>.</p> </li> <li><p class="first"><em>default_section</em>, default value: <tt class="docutils literal"><span class="pre">configparser.DEFAULTSECT</span></tt> (that is: <tt class="docutils literal"><span class="pre">"DEFAULT"</span></tt>)</p> <p>The convention of allowing a special section of default values for other sections or interpolation purposes is a powerful concept of this library, letting users create complex declarative configurations. This section is normally called <tt class="docutils literal"><span class="pre">"DEFAULT"</span></tt> but this can be customized to point to any other valid section name. Some typical values include: <tt class="docutils literal"><span class="pre">"general"</span></tt> or <tt class="docutils literal"><span class="pre">"common"</span></tt>. The name provided is used for recognizing default sections when reading from any source and is used when writing configuration back to a file. Its current value can be retrieved using the <tt class="docutils literal"><span class="pre">parser_instance.default_section</span></tt> attribute and may be modified at runtime (i.e. to convert files from one format to another).</p> </li> <li><p class="first"><em>interpolation</em>, default value: <tt class="docutils literal"><span class="pre">configparser.BasicInterpolation</span></tt></p> <p>Interpolation behaviour may be customized by providing a custom handler through the <em>interpolation</em> argument. <tt class="xref docutils literal"><span class="pre">None</span></tt> can be used to turn off interpolation completely, <tt class="docutils literal"><span class="pre">ExtendedInterpolation()</span></tt> provides a more advanced variant inspired by <tt class="docutils literal"><span class="pre">zc.buildout</span></tt>. More on the subject in the <a class="reference external" href="#interpolation-of-values">dedicated documentation section</a>. <a class="reference internal" href="#configparser.RawConfigParser" title="configparser.RawConfigParser"><tt class="xref py py-class docutils literal"><span class="pre">RawConfigParser</span></tt></a> has a default value of <tt class="xref docutils literal"><span class="pre">None</span></tt>.</p> </li> </ul> <p>More advanced customization may be achieved by overriding default values of these parser attributes. The defaults are defined on the classes, so they may be overriden by subclasses or by attribute assignment.</p> <dl class="attribute"> <dt id="configparser.BOOLEAN_STATES"> <tt class="descclassname">configparser.</tt><tt class="descname">BOOLEAN_STATES</tt><a class="headerlink" href="#configparser.BOOLEAN_STATES" title="Permalink to this definition">¶</a></dt> <dd><p>By default when using <tt class="xref py py-meth docutils literal"><span class="pre">getboolean()</span></tt>, config parsers consider the following values <tt class="xref docutils literal"><span class="pre">True</span></tt>: <tt class="docutils literal"><span class="pre">'1'</span></tt>, <tt class="docutils literal"><span class="pre">'yes'</span></tt>, <tt class="docutils literal"><span class="pre">'true'</span></tt>, <tt class="docutils literal"><span class="pre">'on'</span></tt> and the following values <tt class="xref docutils literal"><span class="pre">False</span></tt>: <tt class="docutils literal"><span class="pre">'0'</span></tt>, <tt class="docutils literal"><span class="pre">'no'</span></tt>, <tt class="docutils literal"><span class="pre">'false'</span></tt>, <tt class="docutils literal"><span class="pre">'off'</span></tt>. You can override this by specifying a custom dictionary of strings and their Boolean outcomes. For example:</p> <div class="highlight-python3"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">custom</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">ConfigParser</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">custom</span><span class="p">[</span><span class="s">'section1'</span><span class="p">]</span> <span class="o">=</span> <span class="p">{</span><span class="s">'funky'</span><span class="p">:</span> <span class="s">'nope'</span><span class="p">}</span> <span class="gp">>>> </span><span class="n">custom</span><span class="p">[</span><span class="s">'section1'</span><span class="p">]</span><span class="o">.</span><span class="n">getboolean</span><span class="p">(</span><span class="s">'funky'</span><span class="p">)</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">ValueError: Not a boolean</span>: <span class="n">nope</span> <span class="gp">>>> </span><span class="n">custom</span><span class="o">.</span><span class="n">BOOLEAN_STATES</span> <span class="o">=</span> <span class="p">{</span><span class="s">'sure'</span><span class="p">:</span> <span class="k">True</span><span class="p">,</span> <span class="s">'nope'</span><span class="p">:</span> <span class="k">False</span><span class="p">}</span> <span class="gp">>>> </span><span class="n">custom</span><span class="p">[</span><span class="s">'section1'</span><span class="p">]</span><span class="o">.</span><span class="n">getboolean</span><span class="p">(</span><span class="s">'funky'</span><span class="p">)</span> <span class="go">False</span> </pre></div> </div> <p>Other typical Boolean pairs include <tt class="docutils literal"><span class="pre">accept</span></tt>/<tt class="docutils literal"><span class="pre">reject</span></tt> or <tt class="docutils literal"><span class="pre">enabled</span></tt>/<tt class="docutils literal"><span class="pre">disabled</span></tt>.</p> </dd></dl> <dl class="method"> <dt id="configparser.optionxform"> <tt class="descclassname">configparser.</tt><tt class="descname">optionxform</tt><big>(</big><em>option</em><big>)</big><a class="headerlink" href="#configparser.optionxform" title="Permalink to this definition">¶</a></dt> <dd><p>This method transforms option names on every read, get, or set operation. The default converts the name to lowercase. This also means that when a configuration file gets written, all keys will be lowercase. Override this method if that’s unsuitable. For example:</p> <div class="highlight-python3"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">config</span> <span class="o">=</span> <span class="s">"""</span> <span class="gp">... </span><span class="s">[Section1]</span> <span class="gp">... </span><span class="s">Key = Value</span> <span class="gp">...</span><span class="s"></span> <span class="gp">... </span><span class="s">[Section2]</span> <span class="gp">... </span><span class="s">AnotherKey = Value</span> <span class="gp">... </span><span class="s">"""</span> <span class="gp">>>> </span><span class="n">typical</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">ConfigParser</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">typical</span><span class="o">.</span><span class="n">read_string</span><span class="p">(</span><span class="n">config</span><span class="p">)</span> <span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">typical</span><span class="p">[</span><span class="s">'Section1'</span><span class="p">]</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span> <span class="go">['key']</span> <span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">typical</span><span class="p">[</span><span class="s">'Section2'</span><span class="p">]</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span> <span class="go">['anotherkey']</span> <span class="gp">>>> </span><span class="n">custom</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">RawConfigParser</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">custom</span><span class="o">.</span><span class="n">optionxform</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">option</span><span class="p">:</span> <span class="n">option</span> <span class="gp">>>> </span><span class="n">custom</span><span class="o">.</span><span class="n">read_string</span><span class="p">(</span><span class="n">config</span><span class="p">)</span> <span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">custom</span><span class="p">[</span><span class="s">'Section1'</span><span class="p">]</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span> <span class="go">['Key']</span> <span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">custom</span><span class="p">[</span><span class="s">'Section2'</span><span class="p">]</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span> <span class="go">['AnotherKey']</span> </pre></div> </div> </dd></dl> <dl class="attribute"> <dt id="configparser.SECTCRE"> <tt class="descclassname">configparser.</tt><tt class="descname">SECTCRE</tt><a class="headerlink" href="#configparser.SECTCRE" title="Permalink to this definition">¶</a></dt> <dd><p>A compiled regular expression used to parse section headers. The default matches <tt class="docutils literal"><span class="pre">[section]</span></tt> to the name <tt class="docutils literal"><span class="pre">"section"</span></tt>. Whitespace is considered part of the section name, thus <tt class="docutils literal"><span class="pre">[</span> <span class="pre">larch</span> <span class="pre">]</span></tt> will be read as a section of name <tt class="docutils literal"><span class="pre">"</span> <span class="pre">larch</span> <span class="pre">"</span></tt>. Override this attribute if that’s unsuitable. For example:</p> <div class="highlight-python3"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">config</span> <span class="o">=</span> <span class="s">"""</span> <span class="gp">... </span><span class="s">[Section 1]</span> <span class="gp">... </span><span class="s">option = value</span> <span class="gp">...</span><span class="s"></span> <span class="gp">... </span><span class="s">[ Section 2 ]</span> <span class="gp">... </span><span class="s">another = val</span> <span class="gp">... </span><span class="s">"""</span> <span class="gp">>>> </span><span class="n">typical</span> <span class="o">=</span> <span class="n">ConfigParser</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">typical</span><span class="o">.</span><span class="n">read_string</span><span class="p">(</span><span class="n">config</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">typical</span><span class="o">.</span><span class="n">sections</span><span class="p">()</span> <span class="go">['Section 1', ' Section 2 ']</span> <span class="gp">>>> </span><span class="n">custom</span> <span class="o">=</span> <span class="n">ConfigParser</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">custom</span><span class="o">.</span><span class="n">SECTCRE</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s">r"\[ *(?P<header>[^]]+?) *\]"</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">custom</span><span class="o">.</span><span class="n">read_string</span><span class="p">(</span><span class="n">config</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">custom</span><span class="o">.</span><span class="n">sections</span><span class="p">()</span> <span class="go">['Section 1', 'Section 2']</span> </pre></div> </div> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">While ConfigParser objects also use an <tt class="docutils literal"><span class="pre">OPTCRE</span></tt> attribute for recognizing option lines, it’s not recommended to override it because that would interfere with constructor options <em>allow_no_value</em> and <em>delimiters</em>.</p> </div> </dd></dl> </div> <div class="section" id="legacy-api-examples"> <h2>14.2.8. Legacy API Examples<a class="headerlink" href="#legacy-api-examples" title="Permalink to this headline">¶</a></h2> <p>Mainly because of backwards compatibility concerns, <a class="reference internal" href="#module-configparser" title="configparser: Configuration file parser."><tt class="xref py py-mod docutils literal"><span class="pre">configparser</span></tt></a> provides also a legacy API with explicit <tt class="docutils literal"><span class="pre">get</span></tt>/<tt class="docutils literal"><span class="pre">set</span></tt> methods. While there are valid use cases for the methods outlined below, mapping protocol access is preferred for new projects. The legacy API is at times more advanced, low-level and downright counterintuitive.</p> <p>An example of writing to a configuration file:</p> <div class="highlight-python3"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">configparser</span> <span class="n">config</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">RawConfigParser</span><span class="p">()</span> <span class="c"># Please note that using RawConfigParser's set functions, you can assign</span> <span class="c"># non-string values to keys internally, but will receive an error when</span> <span class="c"># attempting to write to a file or when you get it in non-raw mode. Setting</span> <span class="c"># values using the mapping protocol or ConfigParser's set() does not allow</span> <span class="c"># such assignments to take place.</span> <span class="n">config</span><span class="o">.</span><span class="n">add_section</span><span class="p">(</span><span class="s">'Section1'</span><span class="p">)</span> <span class="n">config</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s">'Section1'</span><span class="p">,</span> <span class="s">'an_int'</span><span class="p">,</span> <span class="s">'15'</span><span class="p">)</span> <span class="n">config</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s">'Section1'</span><span class="p">,</span> <span class="s">'a_bool'</span><span class="p">,</span> <span class="s">'true'</span><span class="p">)</span> <span class="n">config</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s">'Section1'</span><span class="p">,</span> <span class="s">'a_float'</span><span class="p">,</span> <span class="s">'3.1415'</span><span class="p">)</span> <span class="n">config</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s">'Section1'</span><span class="p">,</span> <span class="s">'baz'</span><span class="p">,</span> <span class="s">'fun'</span><span class="p">)</span> <span class="n">config</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s">'Section1'</span><span class="p">,</span> <span class="s">'bar'</span><span class="p">,</span> <span class="s">'Python'</span><span class="p">)</span> <span class="n">config</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s">'Section1'</span><span class="p">,</span> <span class="s">'foo'</span><span class="p">,</span> <span class="s">'%(bar)s is %(baz)s!'</span><span class="p">)</span> <span class="c"># Writing our configuration file to 'example.cfg'</span> <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s">'example.cfg'</span><span class="p">,</span> <span class="s">'w'</span><span class="p">)</span> <span class="k">as</span> <span class="n">configfile</span><span class="p">:</span> <span class="n">config</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">configfile</span><span class="p">)</span> </pre></div> </div> <p>An example of reading the configuration file again:</p> <div class="highlight-python3"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">configparser</span> <span class="n">config</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">RawConfigParser</span><span class="p">()</span> <span class="n">config</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="s">'example.cfg'</span><span class="p">)</span> <span class="c"># getfloat() raises an exception if the value is not a float</span> <span class="c"># getint() and getboolean() also do this for their respective types</span> <span class="n">a_float</span> <span class="o">=</span> <span class="n">config</span><span class="o">.</span><span class="n">getfloat</span><span class="p">(</span><span class="s">'Section1'</span><span class="p">,</span> <span class="s">'a_float'</span><span class="p">)</span> <span class="n">an_int</span> <span class="o">=</span> <span class="n">config</span><span class="o">.</span><span class="n">getint</span><span class="p">(</span><span class="s">'Section1'</span><span class="p">,</span> <span class="s">'an_int'</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="n">a_float</span> <span class="o">+</span> <span class="n">an_int</span><span class="p">)</span> <span class="c"># Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.</span> <span class="c"># This is because we are using a RawConfigParser().</span> <span class="k">if</span> <span class="n">config</span><span class="o">.</span><span class="n">getboolean</span><span class="p">(</span><span class="s">'Section1'</span><span class="p">,</span> <span class="s">'a_bool'</span><span class="p">):</span> <span class="nb">print</span><span class="p">(</span><span class="n">config</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'Section1'</span><span class="p">,</span> <span class="s">'foo'</span><span class="p">))</span> </pre></div> </div> <p>To get interpolation, use <a class="reference internal" href="#configparser.ConfigParser" title="configparser.ConfigParser"><tt class="xref py py-class docutils literal"><span class="pre">ConfigParser</span></tt></a>:</p> <div class="highlight-python3"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">configparser</span> <span class="n">cfg</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">ConfigParser</span><span class="p">()</span> <span class="n">cfg</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="s">'example.cfg'</span><span class="p">)</span> <span class="c"># Set the optional *raw* argument of get() to True if you wish to disable</span> <span class="c"># interpolation in a single get operation.</span> <span class="nb">print</span><span class="p">(</span><span class="n">cfg</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'Section1'</span><span class="p">,</span> <span class="s">'foo'</span><span class="p">,</span> <span class="n">raw</span><span class="o">=</span><span class="k">False</span><span class="p">))</span> <span class="c"># -> "Python is fun!"</span> <span class="nb">print</span><span class="p">(</span><span class="n">cfg</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'Section1'</span><span class="p">,</span> <span class="s">'foo'</span><span class="p">,</span> <span class="n">raw</span><span class="o">=</span><span class="k">True</span><span class="p">))</span> <span class="c"># -> "%(bar)s is %(baz)s!"</span> <span class="c"># The optional *vars* argument is a dict with members that will take</span> <span class="c"># precedence in interpolation.</span> <span class="nb">print</span><span class="p">(</span><span class="n">cfg</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'Section1'</span><span class="p">,</span> <span class="s">'foo'</span><span class="p">,</span> <span class="nb">vars</span><span class="o">=</span><span class="p">{</span><span class="s">'bar'</span><span class="p">:</span> <span class="s">'Documentation'</span><span class="p">,</span> <span class="s">'baz'</span><span class="p">:</span> <span class="s">'evil'</span><span class="p">}))</span> <span class="c"># The optional *fallback* argument can be used to provide a fallback value</span> <span class="nb">print</span><span class="p">(</span><span class="n">cfg</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'Section1'</span><span class="p">,</span> <span class="s">'foo'</span><span class="p">))</span> <span class="c"># -> "Python is fun!"</span> <span class="nb">print</span><span class="p">(</span><span class="n">cfg</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'Section1'</span><span class="p">,</span> <span class="s">'foo'</span><span class="p">,</span> <span class="n">fallback</span><span class="o">=</span><span class="s">'Monty is not.'</span><span class="p">))</span> <span class="c"># -> "Python is fun!"</span> <span class="nb">print</span><span class="p">(</span><span class="n">cfg</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'Section1'</span><span class="p">,</span> <span class="s">'monster'</span><span class="p">,</span> <span class="n">fallback</span><span class="o">=</span><span class="s">'No such things as monsters.'</span><span class="p">))</span> <span class="c"># -> "No such things as monsters."</span> <span class="c"># A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError</span> <span class="c"># but we can also use:</span> <span class="nb">print</span><span class="p">(</span><span class="n">cfg</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'Section1'</span><span class="p">,</span> <span class="s">'monster'</span><span class="p">,</span> <span class="n">fallback</span><span class="o">=</span><span class="k">None</span><span class="p">))</span> <span class="c"># -> None</span> </pre></div> </div> <p>Default values are available in both types of ConfigParsers. They are used in interpolation if an option used is not defined elsewhere.</p> <div class="highlight-python3"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">configparser</span> <span class="c"># New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each</span> <span class="n">config</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">ConfigParser</span><span class="p">({</span><span class="s">'bar'</span><span class="p">:</span> <span class="s">'Life'</span><span class="p">,</span> <span class="s">'baz'</span><span class="p">:</span> <span class="s">'hard'</span><span class="p">})</span> <span class="n">config</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="s">'example.cfg'</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="n">config</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'Section1'</span><span class="p">,</span> <span class="s">'foo'</span><span class="p">))</span> <span class="c"># -> "Python is fun!"</span> <span class="n">config</span><span class="o">.</span><span class="n">remove_option</span><span class="p">(</span><span class="s">'Section1'</span><span class="p">,</span> <span class="s">'bar'</span><span class="p">)</span> <span class="n">config</span><span class="o">.</span><span class="n">remove_option</span><span class="p">(</span><span class="s">'Section1'</span><span class="p">,</span> <span class="s">'baz'</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="n">config</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'Section1'</span><span class="p">,</span> <span class="s">'foo'</span><span class="p">))</span> <span class="c"># -> "Life is hard!"</span> </pre></div> </div> </div> <div class="section" id="configparser-objects"> <span id="id10"></span><h2>14.2.9. ConfigParser Objects<a class="headerlink" href="#configparser-objects" title="Permalink to this headline">¶</a></h2> <dl class="class"> <dt id="configparser.ConfigParser"> <em class="property">class </em><tt class="descclassname">configparser.</tt><tt class="descname">ConfigParser</tt><big>(</big><em>defaults=None</em>, <em>dict_type=collections.OrderedDict</em>, <em>allow_no_value=False</em>, <em>delimiters=('='</em>, <em>':')</em>, <em>comment_prefixes=('#'</em>, <em>';')</em>, <em>inline_comment_prefixes=None</em>, <em>strict=True</em>, <em>empty_lines_in_values=True</em>, <em>default_section=configparser.DEFAULTSECT</em>, <em>interpolation=BasicInterpolation()</em><big>)</big><a class="headerlink" href="#configparser.ConfigParser" title="Permalink to this definition">¶</a></dt> <dd><p>The main configuration parser. When <em>defaults</em> is given, it is initialized into the dictionary of intrinsic defaults. When <em>dict_type</em> is given, it will be used to create the dictionary objects for the list of sections, for the options within a section, and for the default values.</p> <p>When <em>delimiters</em> is given, it is used as the set of substrings that divide keys from values. When <em>comment_prefixes</em> is given, it will be used as the set of substrings that prefix comments in otherwise empty lines. Comments can be indented. When <em>inline_comment_prefixes</em> is given, it will be used as the set of substrings that prefix comments in non-empty lines.</p> <p>When <em>strict</em> is <tt class="xref docutils literal"><span class="pre">True</span></tt> (the default), the parser won’t allow for any section or option duplicates while reading from a single source (file, string or dictionary), raising <a class="reference internal" href="#configparser.DuplicateSectionError" title="configparser.DuplicateSectionError"><tt class="xref py py-exc docutils literal"><span class="pre">DuplicateSectionError</span></tt></a> or <a class="reference internal" href="#configparser.DuplicateOptionError" title="configparser.DuplicateOptionError"><tt class="xref py py-exc docutils literal"><span class="pre">DuplicateOptionError</span></tt></a>. When <em>empty_lines_in_values</em> is <tt class="xref docutils literal"><span class="pre">False</span></tt> (default: <tt class="xref docutils literal"><span class="pre">True</span></tt>), each empty line marks the end of an option. Otherwise, internal empty lines of a multiline option are kept as part of the value. When <em>allow_no_value</em> is <tt class="xref docutils literal"><span class="pre">True</span></tt> (default: <tt class="xref docutils literal"><span class="pre">False</span></tt>), options without values are accepted; the value held for these is <tt class="xref docutils literal"><span class="pre">None</span></tt> and they are serialized without the trailing delimiter.</p> <p>When <em>default_section</em> is given, it specifies the name for the special section holding default values for other sections and interpolation purposes (normally named <tt class="docutils literal"><span class="pre">"DEFAULT"</span></tt>). This value can be retrieved and changed on runtime using the <tt class="docutils literal"><span class="pre">default_section</span></tt> instance attribute.</p> <p>Interpolation behaviour may be customized by providing a custom handler through the <em>interpolation</em> argument. <tt class="xref docutils literal"><span class="pre">None</span></tt> can be used to turn off interpolation completely, <tt class="docutils literal"><span class="pre">ExtendedInterpolation()</span></tt> provides a more advanced variant inspired by <tt class="docutils literal"><span class="pre">zc.buildout</span></tt>. More on the subject in the <a class="reference external" href="#interpolation-of-values">dedicated documentation section</a>.</p> <p>All option names used in interpolation will be passed through the <a class="reference internal" href="#configparser.optionxform" title="configparser.optionxform"><tt class="xref py py-meth docutils literal"><span class="pre">optionxform()</span></tt></a> method just like any other option name reference. For example, using the default implementation of <a class="reference internal" href="#configparser.optionxform" title="configparser.optionxform"><tt class="xref py py-meth docutils literal"><span class="pre">optionxform()</span></tt></a> (which converts option names to lower case), the values <tt class="docutils literal"><span class="pre">foo</span> <span class="pre">%(bar)s</span></tt> and <tt class="docutils literal"><span class="pre">foo</span> <span class="pre">%(BAR)s</span></tt> are equivalent.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 3.1:</span> The default <em>dict_type</em> is <a class="reference internal" href="collections.html#collections.OrderedDict" title="collections.OrderedDict"><tt class="xref py py-class docutils literal"><span class="pre">collections.OrderedDict</span></tt></a>.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 3.2:</span> <em>allow_no_value</em>, <em>delimiters</em>, <em>comment_prefixes</em>, <em>strict</em>, <em>empty_lines_in_values</em>, <em>default_section</em> and <em>interpolation</em> were added.</p> <dl class="method"> <dt id="configparser.ConfigParser.defaults"> <tt class="descname">defaults</tt><big>(</big><big>)</big><a class="headerlink" href="#configparser.ConfigParser.defaults" title="Permalink to this definition">¶</a></dt> <dd><p>Return a dictionary containing the instance-wide defaults.</p> </dd></dl> <dl class="method"> <dt id="configparser.ConfigParser.sections"> <tt class="descname">sections</tt><big>(</big><big>)</big><a class="headerlink" href="#configparser.ConfigParser.sections" title="Permalink to this definition">¶</a></dt> <dd><p>Return a list of the sections available; the <em>default section</em> is not included in the list.</p> </dd></dl> <dl class="method"> <dt id="configparser.ConfigParser.add_section"> <tt class="descname">add_section</tt><big>(</big><em>section</em><big>)</big><a class="headerlink" href="#configparser.ConfigParser.add_section" title="Permalink to this definition">¶</a></dt> <dd><p>Add a section named <em>section</em> to the instance. If a section by the given name already exists, <a class="reference internal" href="#configparser.DuplicateSectionError" title="configparser.DuplicateSectionError"><tt class="xref py py-exc docutils literal"><span class="pre">DuplicateSectionError</span></tt></a> is raised. If the <em>default section</em> name is passed, <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> is raised. The name of the section must be a string; if not, <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a> is raised.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 3.2:</span> Non-string section names raise <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="configparser.ConfigParser.has_section"> <tt class="descname">has_section</tt><big>(</big><em>section</em><big>)</big><a class="headerlink" href="#configparser.ConfigParser.has_section" title="Permalink to this definition">¶</a></dt> <dd><p>Indicates whether the named <em>section</em> is present in the configuration. The <em>default section</em> is not acknowledged.</p> </dd></dl> <dl class="method"> <dt id="configparser.ConfigParser.options"> <tt class="descname">options</tt><big>(</big><em>section</em><big>)</big><a class="headerlink" href="#configparser.ConfigParser.options" title="Permalink to this definition">¶</a></dt> <dd><p>Return a list of options available in the specified <em>section</em>.</p> </dd></dl> <dl class="method"> <dt id="configparser.ConfigParser.has_option"> <tt class="descname">has_option</tt><big>(</big><em>section</em>, <em>option</em><big>)</big><a class="headerlink" href="#configparser.ConfigParser.has_option" title="Permalink to this definition">¶</a></dt> <dd><p>If the given <em>section</em> exists, and contains the given <em>option</em>, return <a class="reference internal" href="constants.html#True" title="True"><tt class="xref py py-const xref docutils literal"><span class="pre">True</span></tt></a>; otherwise return <a class="reference internal" href="constants.html#False" title="False"><tt class="xref py py-const xref docutils literal"><span class="pre">False</span></tt></a>. If the specified <em>section</em> is <a class="reference internal" href="constants.html#None" title="None"><tt class="xref py py-const xref docutils literal"><span class="pre">None</span></tt></a> or an empty string, DEFAULT is assumed.</p> </dd></dl> <dl class="method"> <dt id="configparser.ConfigParser.read"> <tt class="descname">read</tt><big>(</big><em>filenames</em>, <em>encoding=None</em><big>)</big><a class="headerlink" href="#configparser.ConfigParser.read" title="Permalink to this definition">¶</a></dt> <dd><p>Attempt to read and parse a list of filenames, returning a list of filenames which were successfully parsed. If <em>filenames</em> is a string, it is treated as a single filename. If a file named in <em>filenames</em> cannot be opened, that file will be ignored. This is designed so that you can specify a list of potential configuration file locations (for example, the current directory, the user’s home directory, and some system-wide directory), and all existing configuration files in the list will be read. If none of the named files exist, the <a class="reference internal" href="#configparser.ConfigParser" title="configparser.ConfigParser"><tt class="xref py py-class docutils literal"><span class="pre">ConfigParser</span></tt></a> instance will contain an empty dataset. An application which requires initial values to be loaded from a file should load the required file or files using <a class="reference internal" href="#configparser.ConfigParser.read_file" title="configparser.ConfigParser.read_file"><tt class="xref py py-meth docutils literal"><span class="pre">read_file()</span></tt></a> before calling <a class="reference internal" href="#configparser.ConfigParser.read" title="configparser.ConfigParser.read"><tt class="xref py py-meth docutils literal"><span class="pre">read()</span></tt></a> for any optional files:</p> <div class="highlight-python3"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">configparser</span><span class="o">,</span> <span class="nn">os</span> <span class="n">config</span> <span class="o">=</span> <span class="n">configparser</span><span class="o">.</span><span class="n">ConfigParser</span><span class="p">()</span> <span class="n">config</span><span class="o">.</span><span class="n">read_file</span><span class="p">(</span><span class="nb">open</span><span class="p">(</span><span class="s">'defaults.cfg'</span><span class="p">))</span> <span class="n">config</span><span class="o">.</span><span class="n">read</span><span class="p">([</span><span class="s">'site.cfg'</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">expanduser</span><span class="p">(</span><span class="s">'~/.myapp.cfg'</span><span class="p">)],</span> <span class="n">encoding</span><span class="o">=</span><span class="s">'cp1250'</span><span class="p">)</span> </pre></div> </div> <p class="versionadded"> <span class="versionmodified">New in version 3.2:</span> The <em>encoding</em> parameter. Previously, all files were read using the default encoding for <a class="reference internal" href="functions.html#open" title="open"><tt class="xref py py-func docutils literal"><span class="pre">open()</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="configparser.ConfigParser.read_file"> <tt class="descname">read_file</tt><big>(</big><em>f</em>, <em>source=None</em><big>)</big><a class="headerlink" href="#configparser.ConfigParser.read_file" title="Permalink to this definition">¶</a></dt> <dd><p>Read and parse configuration data from <em>f</em> which must be an iterable yielding Unicode strings (for example files opened in text mode).</p> <p>Optional argument <em>source</em> specifies the name of the file being read. If not given and <em>f</em> has a <tt class="xref py py-attr docutils literal"><span class="pre">name</span></tt> attribute, that is used for <em>source</em>; the default is <tt class="docutils literal"><span class="pre">'<???>'</span></tt>.</p> <p class="versionadded"> <span class="versionmodified">New in version 3.2:</span> Replaces <a class="reference internal" href="#configparser.ConfigParser.readfp" title="configparser.ConfigParser.readfp"><tt class="xref py py-meth docutils literal"><span class="pre">readfp()</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="configparser.ConfigParser.read_string"> <tt class="descname">read_string</tt><big>(</big><em>string</em>, <em>source='<string>'</em><big>)</big><a class="headerlink" href="#configparser.ConfigParser.read_string" title="Permalink to this definition">¶</a></dt> <dd><p>Parse configuration data from a string.</p> <p>Optional argument <em>source</em> specifies a context-specific name of the string passed. If not given, <tt class="docutils literal"><span class="pre">'<string>'</span></tt> is used. This should commonly be a filesystem path or a URL.</p> <p class="versionadded"> <span class="versionmodified">New in version 3.2.</span> </p> </dd></dl> <dl class="method"> <dt id="configparser.ConfigParser.read_dict"> <tt class="descname">read_dict</tt><big>(</big><em>dictionary</em>, <em>source='<dict>'</em><big>)</big><a class="headerlink" href="#configparser.ConfigParser.read_dict" title="Permalink to this definition">¶</a></dt> <dd><p>Load configuration from any object that provides a dict-like <tt class="docutils literal"><span class="pre">items()</span></tt> method. Keys are section names, values are dictionaries with keys and values that should be present in the section. If the used dictionary type preserves order, sections and their keys will be added in order. Values are automatically converted to strings.</p> <p>Optional argument <em>source</em> specifies a context-specific name of the dictionary passed. If not given, <tt class="docutils literal"><span class="pre"><dict></span></tt> is used.</p> <p>This method can be used to copy state between parsers.</p> <p class="versionadded"> <span class="versionmodified">New in version 3.2.</span> </p> </dd></dl> <dl class="method"> <dt id="configparser.ConfigParser.get"> <tt class="descname">get</tt><big>(</big><em>section</em>, <em>option</em>, <em>*</em>, <em>raw=False</em>, <em>vars=None</em><span class="optional">[</span>, <em>fallback</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#configparser.ConfigParser.get" title="Permalink to this definition">¶</a></dt> <dd><p>Get an <em>option</em> value for the named <em>section</em>. If <em>vars</em> is provided, it must be a dictionary. The <em>option</em> is looked up in <em>vars</em> (if provided), <em>section</em>, and in <em>DEFAULTSECT</em> in that order. If the key is not found and <em>fallback</em> is provided, it is used as a fallback value. <tt class="xref docutils literal"><span class="pre">None</span></tt> can be provided as a <em>fallback</em> value.</p> <p>All the <tt class="docutils literal"><span class="pre">'%'</span></tt> interpolations are expanded in the return values, unless the <em>raw</em> argument is true. Values for interpolation keys are looked up in the same manner as the option.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 3.2:</span> Arguments <em>raw</em>, <em>vars</em> and <em>fallback</em> are keyword only to protect users from trying to use the third argument as the <em>fallback</em> fallback (especially when using the mapping protocol).</p> </dd></dl> <dl class="method"> <dt id="configparser.ConfigParser.getint"> <tt class="descname">getint</tt><big>(</big><em>section</em>, <em>option</em>, <em>*</em>, <em>raw=False</em>, <em>vars=None</em><span class="optional">[</span>, <em>fallback</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#configparser.ConfigParser.getint" title="Permalink to this definition">¶</a></dt> <dd><p>A convenience method which coerces the <em>option</em> in the specified <em>section</em> to an integer. See <a class="reference internal" href="#configparser.ConfigParser.get" title="configparser.ConfigParser.get"><tt class="xref py py-meth docutils literal"><span class="pre">get()</span></tt></a> for explanation of <em>raw</em>, <em>vars</em> and <em>fallback</em>.</p> </dd></dl> <dl class="method"> <dt id="configparser.ConfigParser.getfloat"> <tt class="descname">getfloat</tt><big>(</big><em>section</em>, <em>option</em>, <em>*</em>, <em>raw=False</em>, <em>vars=None</em><span class="optional">[</span>, <em>fallback</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#configparser.ConfigParser.getfloat" title="Permalink to this definition">¶</a></dt> <dd><p>A convenience method which coerces the <em>option</em> in the specified <em>section</em> to a floating point number. See <a class="reference internal" href="#configparser.ConfigParser.get" title="configparser.ConfigParser.get"><tt class="xref py py-meth docutils literal"><span class="pre">get()</span></tt></a> for explanation of <em>raw</em>, <em>vars</em> and <em>fallback</em>.</p> </dd></dl> <dl class="method"> <dt id="configparser.ConfigParser.getboolean"> <tt class="descname">getboolean</tt><big>(</big><em>section</em>, <em>option</em>, <em>*</em>, <em>raw=False</em>, <em>vars=None</em><span class="optional">[</span>, <em>fallback</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#configparser.ConfigParser.getboolean" title="Permalink to this definition">¶</a></dt> <dd><p>A convenience method which coerces the <em>option</em> in the specified <em>section</em> to a Boolean value. Note that the accepted values for the option are <tt class="docutils literal"><span class="pre">'1'</span></tt>, <tt class="docutils literal"><span class="pre">'yes'</span></tt>, <tt class="docutils literal"><span class="pre">'true'</span></tt>, and <tt class="docutils literal"><span class="pre">'on'</span></tt>, which cause this method to return <tt class="xref docutils literal"><span class="pre">True</span></tt>, and <tt class="docutils literal"><span class="pre">'0'</span></tt>, <tt class="docutils literal"><span class="pre">'no'</span></tt>, <tt class="docutils literal"><span class="pre">'false'</span></tt>, and <tt class="docutils literal"><span class="pre">'off'</span></tt>, which cause it to return <tt class="xref docutils literal"><span class="pre">False</span></tt>. These string values are checked in a case-insensitive manner. Any other value will cause it to raise <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a>. See <a class="reference internal" href="#configparser.ConfigParser.get" title="configparser.ConfigParser.get"><tt class="xref py py-meth docutils literal"><span class="pre">get()</span></tt></a> for explanation of <em>raw</em>, <em>vars</em> and <em>fallback</em>.</p> </dd></dl> <dl class="method"> <dt id="configparser.ConfigParser.items"> <tt class="descname">items</tt><big>(</big><em>raw=False</em>, <em>vars=None</em><big>)</big><a class="headerlink" href="#configparser.ConfigParser.items" title="Permalink to this definition">¶</a></dt> <dt> <tt class="descname">items</tt><big>(</big><em>section</em>, <em>raw=False</em>, <em>vars=None</em><big>)</big></dt> <dd><p>When <em>section</em> is not given, return a list of <em>section_name</em>, <em>section_proxy</em> pairs, including DEFAULTSECT.</p> <p>Otherwise, return a list of <em>name</em>, <em>value</em> pairs for the options in the given <em>section</em>. Optional arguments have the same meaning as for the <a class="reference internal" href="#configparser.ConfigParser.get" title="configparser.ConfigParser.get"><tt class="xref py py-meth docutils literal"><span class="pre">get()</span></tt></a> method.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 3.2:</span> Items present in <em>vars</em> no longer appear in the result. The previous behaviour mixed actual parser options with variables provided for interpolation.</p> </dd></dl> <dl class="method"> <dt id="configparser.ConfigParser.set"> <tt class="descname">set</tt><big>(</big><em>section</em>, <em>option</em>, <em>value</em><big>)</big><a class="headerlink" href="#configparser.ConfigParser.set" title="Permalink to this definition">¶</a></dt> <dd><p>If the given section exists, set the given option to the specified value; otherwise raise <a class="reference internal" href="#configparser.NoSectionError" title="configparser.NoSectionError"><tt class="xref py py-exc docutils literal"><span class="pre">NoSectionError</span></tt></a>. <em>option</em> and <em>value</em> must be strings; if not, <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a> is raised.</p> </dd></dl> <dl class="method"> <dt id="configparser.ConfigParser.write"> <tt class="descname">write</tt><big>(</big><em>fileobject</em>, <em>space_around_delimiters=True</em><big>)</big><a class="headerlink" href="#configparser.ConfigParser.write" title="Permalink to this definition">¶</a></dt> <dd><p>Write a representation of the configuration to the specified <a class="reference internal" href="../glossary.html#term-file-object"><em class="xref std std-term">file object</em></a>, which must be opened in text mode (accepting strings). This representation can be parsed by a future <a class="reference internal" href="#configparser.ConfigParser.read" title="configparser.ConfigParser.read"><tt class="xref py py-meth docutils literal"><span class="pre">read()</span></tt></a> call. If <em>space_around_delimiters</em> is true, delimiters between keys and values are surrounded by spaces.</p> </dd></dl> <dl class="method"> <dt id="configparser.ConfigParser.remove_option"> <tt class="descname">remove_option</tt><big>(</big><em>section</em>, <em>option</em><big>)</big><a class="headerlink" href="#configparser.ConfigParser.remove_option" title="Permalink to this definition">¶</a></dt> <dd><p>Remove the specified <em>option</em> from the specified <em>section</em>. If the section does not exist, raise <a class="reference internal" href="#configparser.NoSectionError" title="configparser.NoSectionError"><tt class="xref py py-exc docutils literal"><span class="pre">NoSectionError</span></tt></a>. If the option existed to be removed, return <a class="reference internal" href="constants.html#True" title="True"><tt class="xref py py-const xref docutils literal"><span class="pre">True</span></tt></a>; otherwise return <a class="reference internal" href="constants.html#False" title="False"><tt class="xref py py-const xref docutils literal"><span class="pre">False</span></tt></a>.</p> </dd></dl> <dl class="method"> <dt id="configparser.ConfigParser.remove_section"> <tt class="descname">remove_section</tt><big>(</big><em>section</em><big>)</big><a class="headerlink" href="#configparser.ConfigParser.remove_section" title="Permalink to this definition">¶</a></dt> <dd><p>Remove the specified <em>section</em> from the configuration. If the section in fact existed, return <tt class="xref docutils literal"><span class="pre">True</span></tt>. Otherwise return <tt class="xref docutils literal"><span class="pre">False</span></tt>.</p> </dd></dl> <dl class="method"> <dt id="configparser.ConfigParser.optionxform"> <tt class="descname">optionxform</tt><big>(</big><em>option</em><big>)</big><a class="headerlink" href="#configparser.ConfigParser.optionxform" title="Permalink to this definition">¶</a></dt> <dd><p>Transforms the option name <em>option</em> as found in an input file or as passed in by client code to the form that should be used in the internal structures. The default implementation returns a lower-case version of <em>option</em>; subclasses may override this or client code can set an attribute of this name on instances to affect this behavior.</p> <p>You don’t need to subclass the parser to use this method, you can also set it on an instance, to a function that takes a string argument and returns a string. Setting it to <tt class="docutils literal"><span class="pre">str</span></tt>, for example, would make option names case sensitive:</p> <div class="highlight-python3"><div class="highlight"><pre><span class="n">cfgparser</span> <span class="o">=</span> <span class="n">ConfigParser</span><span class="p">()</span> <span class="n">cfgparser</span><span class="o">.</span><span class="n">optionxform</span> <span class="o">=</span> <span class="nb">str</span> </pre></div> </div> <p>Note that when reading configuration files, whitespace around the option names is stripped before <a class="reference internal" href="#configparser.optionxform" title="configparser.optionxform"><tt class="xref py py-meth docutils literal"><span class="pre">optionxform()</span></tt></a> is called.</p> </dd></dl> <dl class="method"> <dt id="configparser.ConfigParser.readfp"> <tt class="descname">readfp</tt><big>(</big><em>fp</em>, <em>filename=None</em><big>)</big><a class="headerlink" href="#configparser.ConfigParser.readfp" title="Permalink to this definition">¶</a></dt> <dd><p class="deprecated"> <span class="versionmodified">Deprecated since version 3.2:</span> Use <a class="reference internal" href="#configparser.ConfigParser.read_file" title="configparser.ConfigParser.read_file"><tt class="xref py py-meth docutils literal"><span class="pre">read_file()</span></tt></a> instead.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 3.2:</span> <a class="reference internal" href="#configparser.ConfigParser.readfp" title="configparser.ConfigParser.readfp"><tt class="xref py py-meth docutils literal"><span class="pre">readfp()</span></tt></a> now iterates on <em>f</em> instead of calling <tt class="docutils literal"><span class="pre">f.readline()</span></tt>.</p> <p>For existing code calling <a class="reference internal" href="#configparser.ConfigParser.readfp" title="configparser.ConfigParser.readfp"><tt class="xref py py-meth docutils literal"><span class="pre">readfp()</span></tt></a> with arguments which don’t support iteration, the following generator may be used as a wrapper around the file-like object:</p> <div class="highlight-python3"><div class="highlight"><pre><span class="k">def</span> <span class="nf">readline_generator</span><span class="p">(</span><span class="n">f</span><span class="p">):</span> <span class="n">line</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span> <span class="k">while</span> <span class="n">line</span><span class="p">:</span> <span class="k">yield</span> <span class="n">line</span> <span class="n">line</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span> </pre></div> </div> <p>Instead of <tt class="docutils literal"><span class="pre">parser.readfp(f)</span></tt> use <tt class="docutils literal"><span class="pre">parser.read_file(readline_generator(f))</span></tt>.</p> </dd></dl> </dd></dl> <dl class="data"> <dt id="configparser.MAX_INTERPOLATION_DEPTH"> <tt class="descclassname">configparser.</tt><tt class="descname">MAX_INTERPOLATION_DEPTH</tt><a class="headerlink" href="#configparser.MAX_INTERPOLATION_DEPTH" title="Permalink to this definition">¶</a></dt> <dd><p>The maximum depth for recursive interpolation for <tt class="xref py py-meth docutils literal"><span class="pre">get()</span></tt> when the <em>raw</em> parameter is false. This is relevant only when the default <em>interpolation</em> is used.</p> </dd></dl> </div> <div class="section" id="rawconfigparser-objects"> <span id="id12"></span><h2>14.2.10. RawConfigParser Objects<a class="headerlink" href="#rawconfigparser-objects" title="Permalink to this headline">¶</a></h2> <dl class="class"> <dt id="configparser.RawConfigParser"> <em class="property">class </em><tt class="descclassname">configparser.</tt><tt class="descname">RawConfigParser</tt><big>(</big><em>defaults=None</em>, <em>dict_type=collections.OrderedDict</em>, <em>allow_no_value=False</em>, <em>*</em>, <em>delimiters=('='</em>, <em>':')</em>, <em>comment_prefixes=('#'</em>, <em>';')</em>, <em>inline_comment_prefixes=None</em>, <em>strict=True</em>, <em>empty_lines_in_values=True</em>, <em>default_section=configparser.DEFAULTSECT</em><span class="optional">[</span>, <em>interpolation</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#configparser.RawConfigParser" title="Permalink to this definition">¶</a></dt> <dd><p>Legacy variant of the <a class="reference internal" href="#configparser.ConfigParser" title="configparser.ConfigParser"><tt class="xref py py-class docutils literal"><span class="pre">ConfigParser</span></tt></a> with interpolation disabled by default and unsafe <tt class="docutils literal"><span class="pre">add_section</span></tt> and <tt class="docutils literal"><span class="pre">set</span></tt> methods.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">Consider using <a class="reference internal" href="#configparser.ConfigParser" title="configparser.ConfigParser"><tt class="xref py py-class docutils literal"><span class="pre">ConfigParser</span></tt></a> instead which checks types of the values to be stored internally. If you don’t want interpolation, you can use <tt class="docutils literal"><span class="pre">ConfigParser(interpolation=None)</span></tt>.</p> </div> <dl class="method"> <dt id="configparser.RawConfigParser.add_section"> <tt class="descname">add_section</tt><big>(</big><em>section</em><big>)</big><a class="headerlink" href="#configparser.RawConfigParser.add_section" title="Permalink to this definition">¶</a></dt> <dd><p>Add a section named <em>section</em> to the instance. If a section by the given name already exists, <a class="reference internal" href="#configparser.DuplicateSectionError" title="configparser.DuplicateSectionError"><tt class="xref py py-exc docutils literal"><span class="pre">DuplicateSectionError</span></tt></a> is raised. If the <em>default section</em> name is passed, <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> is raised.</p> <p>Type of <em>section</em> is not checked which lets users create non-string named sections. This behaviour is unsupported and may cause internal errors.</p> </dd></dl> <dl class="method"> <dt id="configparser.RawConfigParser.set"> <tt class="descname">set</tt><big>(</big><em>section</em>, <em>option</em>, <em>value</em><big>)</big><a class="headerlink" href="#configparser.RawConfigParser.set" title="Permalink to this definition">¶</a></dt> <dd><p>If the given section exists, set the given option to the specified value; otherwise raise <a class="reference internal" href="#configparser.NoSectionError" title="configparser.NoSectionError"><tt class="xref py py-exc docutils literal"><span class="pre">NoSectionError</span></tt></a>. While it is possible to use <a class="reference internal" href="#configparser.RawConfigParser" title="configparser.RawConfigParser"><tt class="xref py py-class docutils literal"><span class="pre">RawConfigParser</span></tt></a> (or <a class="reference internal" href="#configparser.ConfigParser" title="configparser.ConfigParser"><tt class="xref py py-class docutils literal"><span class="pre">ConfigParser</span></tt></a> with <em>raw</em> parameters set to true) for <em>internal</em> storage of non-string values, full functionality (including interpolation and output to files) can only be achieved using string values.</p> <p>This method lets users assign non-string values to keys internally. This behaviour is unsupported and will cause errors when attempting to write to a file or get it in non-raw mode. <strong>Use the mapping protocol API</strong> which does not allow such assignments to take place.</p> </dd></dl> </dd></dl> </div> <div class="section" id="exceptions"> <h2>14.2.11. Exceptions<a class="headerlink" href="#exceptions" title="Permalink to this headline">¶</a></h2> <dl class="exception"> <dt id="configparser.Error"> <em class="property">exception </em><tt class="descclassname">configparser.</tt><tt class="descname">Error</tt><a class="headerlink" href="#configparser.Error" title="Permalink to this definition">¶</a></dt> <dd><p>Base class for all other <a class="reference internal" href="#module-configparser" title="configparser: Configuration file parser."><tt class="xref py py-mod docutils literal"><span class="pre">configparser</span></tt></a> exceptions.</p> </dd></dl> <dl class="exception"> <dt id="configparser.NoSectionError"> <em class="property">exception </em><tt class="descclassname">configparser.</tt><tt class="descname">NoSectionError</tt><a class="headerlink" href="#configparser.NoSectionError" title="Permalink to this definition">¶</a></dt> <dd><p>Exception raised when a specified section is not found.</p> </dd></dl> <dl class="exception"> <dt id="configparser.DuplicateSectionError"> <em class="property">exception </em><tt class="descclassname">configparser.</tt><tt class="descname">DuplicateSectionError</tt><a class="headerlink" href="#configparser.DuplicateSectionError" title="Permalink to this definition">¶</a></dt> <dd><p>Exception raised if <tt class="xref py py-meth docutils literal"><span class="pre">add_section()</span></tt> is called with the name of a section that is already present or in strict parsers when a section if found more than once in a single input file, string or dictionary.</p> <p class="versionadded"> <span class="versionmodified">New in version 3.2:</span> Optional <tt class="docutils literal"><span class="pre">source</span></tt> and <tt class="docutils literal"><span class="pre">lineno</span></tt> attributes and arguments to <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> were added.</p> </dd></dl> <dl class="exception"> <dt id="configparser.DuplicateOptionError"> <em class="property">exception </em><tt class="descclassname">configparser.</tt><tt class="descname">DuplicateOptionError</tt><a class="headerlink" href="#configparser.DuplicateOptionError" title="Permalink to this definition">¶</a></dt> <dd><p>Exception raised by strict parsers if a single option appears twice during reading from a single file, string or dictionary. This catches misspellings and case sensitivity-related errors, e.g. a dictionary may have two keys representing the same case-insensitive configuration key.</p> </dd></dl> <dl class="exception"> <dt id="configparser.NoOptionError"> <em class="property">exception </em><tt class="descclassname">configparser.</tt><tt class="descname">NoOptionError</tt><a class="headerlink" href="#configparser.NoOptionError" title="Permalink to this definition">¶</a></dt> <dd><p>Exception raised when a specified option is not found in the specified section.</p> </dd></dl> <dl class="exception"> <dt id="configparser.InterpolationError"> <em class="property">exception </em><tt class="descclassname">configparser.</tt><tt class="descname">InterpolationError</tt><a class="headerlink" href="#configparser.InterpolationError" title="Permalink to this definition">¶</a></dt> <dd><p>Base class for exceptions raised when problems occur performing string interpolation.</p> </dd></dl> <dl class="exception"> <dt id="configparser.InterpolationDepthError"> <em class="property">exception </em><tt class="descclassname">configparser.</tt><tt class="descname">InterpolationDepthError</tt><a class="headerlink" href="#configparser.InterpolationDepthError" title="Permalink to this definition">¶</a></dt> <dd><p>Exception raised when string interpolation cannot be completed because the number of iterations exceeds <a class="reference internal" href="#configparser.MAX_INTERPOLATION_DEPTH" title="configparser.MAX_INTERPOLATION_DEPTH"><tt class="xref py py-const docutils literal"><span class="pre">MAX_INTERPOLATION_DEPTH</span></tt></a>. Subclass of <a class="reference internal" href="#configparser.InterpolationError" title="configparser.InterpolationError"><tt class="xref py py-exc docutils literal"><span class="pre">InterpolationError</span></tt></a>.</p> </dd></dl> <dl class="exception"> <dt id="configparser.InterpolationMissingOptionError"> <em class="property">exception </em><tt class="descclassname">configparser.</tt><tt class="descname">InterpolationMissingOptionError</tt><a class="headerlink" href="#configparser.InterpolationMissingOptionError" title="Permalink to this definition">¶</a></dt> <dd><p>Exception raised when an option referenced from a value does not exist. Subclass of <a class="reference internal" href="#configparser.InterpolationError" title="configparser.InterpolationError"><tt class="xref py py-exc docutils literal"><span class="pre">InterpolationError</span></tt></a>.</p> </dd></dl> <dl class="exception"> <dt id="configparser.InterpolationSyntaxError"> <em class="property">exception </em><tt class="descclassname">configparser.</tt><tt class="descname">InterpolationSyntaxError</tt><a class="headerlink" href="#configparser.InterpolationSyntaxError" title="Permalink to this definition">¶</a></dt> <dd><p>Exception raised when the source text into which substitutions are made does not conform to the required syntax. Subclass of <a class="reference internal" href="#configparser.InterpolationError" title="configparser.InterpolationError"><tt class="xref py py-exc docutils literal"><span class="pre">InterpolationError</span></tt></a>.</p> </dd></dl> <dl class="exception"> <dt id="configparser.MissingSectionHeaderError"> <em class="property">exception </em><tt class="descclassname">configparser.</tt><tt class="descname">MissingSectionHeaderError</tt><a class="headerlink" href="#configparser.MissingSectionHeaderError" title="Permalink to this definition">¶</a></dt> <dd><p>Exception raised when attempting to parse a file which has no section headers.</p> </dd></dl> <dl class="exception"> <dt id="configparser.ParsingError"> <em class="property">exception </em><tt class="descclassname">configparser.</tt><tt class="descname">ParsingError</tt><a class="headerlink" href="#configparser.ParsingError" title="Permalink to this definition">¶</a></dt> <dd><p>Exception raised when errors occur attempting to parse a file.</p> <p class="versionchanged"> <span class="versionmodified">Changed in version 3.2:</span> The <tt class="docutils literal"><span class="pre">filename</span></tt> attribute and <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> argument were renamed to <tt class="docutils literal"><span class="pre">source</span></tt> for consistency.</p> </dd></dl> <p class="rubric">Footnotes</p> <table class="docutils footnote" frame="void" id="id13" rules="none"> <colgroup><col class="label" /><col /></colgroup> <tbody valign="top"> <tr><td class="label">[1]</td><td><em>(<a class="fn-backref" href="#id1">1</a>, <a class="fn-backref" href="#id2">2</a>, <a class="fn-backref" href="#id3">3</a>, <a class="fn-backref" href="#id4">4</a>, <a class="fn-backref" href="#id5">5</a>, <a class="fn-backref" href="#id6">6</a>, <a class="fn-backref" href="#id7">7</a>, <a class="fn-backref" href="#id8">8</a>, <a class="fn-backref" href="#id9">9</a>)</em> Config parsers allow for heavy customization. If you are interested in changing the behaviour outlined by the footnote reference, consult the <a class="reference internal" href="#customizing-parser-behaviour">Customizing Parser Behaviour</a> section.</td></tr> </tbody> </table> </div> </div> </div> </div> </div> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"> <h3><a href="../contents.html">Table Of Contents</a></h3> <ul> <li><a class="reference internal" href="#">14.2. <tt class="docutils literal"><span class="pre">configparser</span></tt> — Configuration file parser</a><ul> <li><a class="reference internal" href="#quick-start">14.2.1. Quick Start</a></li> <li><a class="reference internal" href="#supported-datatypes">14.2.2. Supported Datatypes</a></li> <li><a class="reference internal" href="#fallback-values">14.2.3. Fallback Values</a></li> <li><a class="reference internal" href="#supported-ini-file-structure">14.2.4. Supported INI File Structure</a></li> <li><a class="reference internal" href="#interpolation-of-values">14.2.5. Interpolation of values</a></li> <li><a class="reference internal" href="#mapping-protocol-access">14.2.6. Mapping Protocol Access</a></li> <li><a class="reference internal" href="#customizing-parser-behaviour">14.2.7. Customizing Parser Behaviour</a></li> <li><a class="reference internal" href="#legacy-api-examples">14.2.8. Legacy API Examples</a></li> <li><a class="reference internal" href="#configparser-objects">14.2.9. ConfigParser Objects</a></li> <li><a class="reference internal" href="#rawconfigparser-objects">14.2.10. RawConfigParser Objects</a></li> <li><a class="reference internal" href="#exceptions">14.2.11. Exceptions</a></li> </ul> </li> </ul> <h4>Previous topic</h4> <p class="topless"><a href="csv.html" title="previous chapter">14.1. <tt class="docutils literal"><span class="pre">csv</span></tt> — CSV File Reading and Writing</a></p> <h4>Next topic</h4> <p class="topless"><a href="netrc.html" title="next chapter">14.3. <tt class="docutils literal"><span class="pre">netrc</span></tt> — netrc file processing</a></p> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a Bug</a></li> <li><a href="../_sources/library/configparser.txt" rel="nofollow">Show Source</a></li> </ul> <div id="searchbox" style="display: none"> <h3>Quick search</h3> <form class="search" action="../search.html" method="get"> <input type="text" name="q" size="18" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="netrc.html" title="14.3. netrc — netrc file processing" >next</a> |</li> <li class="right" > <a href="csv.html" title="14.1. csv — CSV File Reading and Writing" >previous</a> |</li> <li><img src="../_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="http://www.python.org/">Python</a> »</li> <li> <a href="../index.html">3.3.2 Documentation</a> » </li> <li><a href="index.html" >The Python Standard Library</a> »</li> <li><a href="fileformats.html" >14. File Formats</a> »</li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 1990-2013, Python Software Foundation. <br /> The Python Software Foundation is a non-profit corporation. <a href="http://www.python.org/psf/donations/">Please donate.</a> <br /> Last updated on May 15, 2013. <a href="../bugs.html">Found a bug</a>? <br /> Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.0.7. </div> </body> </html>