<div class="section" id="the-nonlocal-statement">
<span id="nonlocal"></span><h2>The <a class="reference internal" href="#nonlocal"><tt class="xref std std-keyword docutils literal"><span class="pre">nonlocal</span></tt></a> statement</h2>
<pre id="index-41">
<strong id="grammar-token-nonlocal_stmt">nonlocal_stmt</strong> ::=  &quot;nonlocal&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><tt class="xref docutils literal"><span class="pre">identifier</span></tt></a> (&quot;,&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><tt class="xref docutils literal"><span class="pre">identifier</span></tt></a>)*
</pre>
<p>The <a class="reference internal" href="#nonlocal"><tt class="xref std std-keyword docutils literal"><span class="pre">nonlocal</span></tt></a> statement causes the listed identifiers to refer to
previously bound variables in the nearest enclosing scope excluding globals.
This is important because the default behavior for binding is to search the
local namespace first.  The statement allows encapsulated code to rebind
variables outside of the local scope besides the global (module) scope.</p>
<p>Names listed in a <a class="reference internal" href="#nonlocal"><tt class="xref std std-keyword docutils literal"><span class="pre">nonlocal</span></tt></a> statement, unlike those listed in a
<a class="reference internal" href="#global"><tt class="xref std std-keyword docutils literal"><span class="pre">global</span></tt></a> statement, must refer to pre-existing bindings in an
enclosing scope (the scope in which a new binding should be created cannot
be determined unambiguously).</p>
<p>Names listed in a <a class="reference internal" href="#nonlocal"><tt class="xref std std-keyword docutils literal"><span class="pre">nonlocal</span></tt></a> statement must not collide with
pre-existing bindings in the local scope.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-42"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-3104"><strong>PEP 3104</strong></a> - Access to Names in Outer Scopes</dt>
<dd>The specification for the <a class="reference internal" href="#nonlocal"><tt class="xref std std-keyword docutils literal"><span class="pre">nonlocal</span></tt></a> statement.</dd>
</dl>
</div>
</div>
</div>
