add files

This commit is contained in:
Caleb Fontenot
2019-07-15 09:16:41 -07:00
parent b4f7a8873b
commit 335515d331
1027 changed files with 679464 additions and 0 deletions

View File

@@ -0,0 +1,820 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>8. Compound statements &#8212; Python 3.7.4 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" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="9. Top-level components" href="toplevel_components.html" />
<link rel="prev" title="7. Simple statements" href="simple_stmts.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/reference/compound_stmts.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="toplevel_components.html" title="9. Top-level components"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="simple_stmts.html" title="7. Simple statements"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="compound-statements">
<span id="compound"></span><h1>8. Compound statements<a class="headerlink" href="#compound-statements" title="Permalink to this headline"></a></h1>
<p id="index-0">Compound statements contain (groups of) other statements; they affect or control
the execution of those other statements in some way. In general, compound
statements span multiple lines, although in simple incarnations a whole compound
statement may be contained in one line.</p>
<p>The <a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a>, <a class="reference internal" href="#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> and <a class="reference internal" href="#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statements implement
traditional control flow constructs. <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> specifies exception
handlers and/or cleanup code for a group of statements, while the
<a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement allows the execution of initialization and
finalization code around a block of code. Function and class definitions are
also syntactically compound statements.</p>
<p id="index-1">A compound statement consists of one or more clauses. A clause consists of a
header and a suite. The clause headers of a particular compound statement are
all at the same indentation level. Each clause header begins with a uniquely
identifying keyword and ends with a colon. A suite is a group of statements
controlled by a clause. A suite can be one or more semicolon-separated simple
statements on the same line as the header, following the headers colon, or it
can be one or more indented statements on subsequent lines. Only the latter
form of a suite can contain nested compound statements; the following is illegal,
mostly because it wouldnt be clear to which <a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> clause a following
<a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clause would belong:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">test1</span><span class="p">:</span> <span class="k">if</span> <span class="n">test2</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
</pre></div>
</div>
<p>Also note that the semicolon binds tighter than the colon in this context, so
that in the following example, either all or none of the <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> calls are
executed:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="n">y</span> <span class="o">&lt;</span> <span class="n">z</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">);</span> <span class="nb">print</span><span class="p">(</span><span class="n">y</span><span class="p">);</span> <span class="nb">print</span><span class="p">(</span><span class="n">z</span><span class="p">)</span>
</pre></div>
</div>
<p>Summarizing:</p>
<pre>
<strong id="grammar-token-compound-stmt">compound_stmt</strong> ::= <a class="reference internal" href="#grammar-token-if-stmt"><code class="xref docutils literal notranslate"><span class="pre">if_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-while-stmt"><code class="xref docutils literal notranslate"><span class="pre">while_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-for-stmt"><code class="xref docutils literal notranslate"><span class="pre">for_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-try-stmt"><code class="xref docutils literal notranslate"><span class="pre">try_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-with-stmt"><code class="xref docutils literal notranslate"><span class="pre">with_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-funcdef"><code class="xref docutils literal notranslate"><span class="pre">funcdef</span></code></a>
| <a class="reference internal" href="#grammar-token-classdef"><code class="xref docutils literal notranslate"><span class="pre">classdef</span></code></a>
| <a class="reference internal" href="#grammar-token-async-with-stmt"><code class="xref docutils literal notranslate"><span class="pre">async_with_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-async-for-stmt"><code class="xref docutils literal notranslate"><span class="pre">async_for_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-async-funcdef"><code class="xref docutils literal notranslate"><span class="pre">async_funcdef</span></code></a>
<strong id="grammar-token-suite">suite </strong> ::= <a class="reference internal" href="#grammar-token-stmt-list"><code class="xref docutils literal notranslate"><span class="pre">stmt_list</span></code></a> NEWLINE | NEWLINE INDENT <a class="reference internal" href="#grammar-token-statement"><code class="xref docutils literal notranslate"><span class="pre">statement</span></code></a>+ DEDENT
<strong id="grammar-token-statement">statement </strong> ::= <a class="reference internal" href="#grammar-token-stmt-list"><code class="xref docutils literal notranslate"><span class="pre">stmt_list</span></code></a> NEWLINE | <a class="reference internal" href="#grammar-token-compound-stmt"><code class="xref docutils literal notranslate"><span class="pre">compound_stmt</span></code></a>
<strong id="grammar-token-stmt-list">stmt_list </strong> ::= <a class="reference internal" href="simple_stmts.html#grammar-token-simple-stmt"><code class="xref docutils literal notranslate"><span class="pre">simple_stmt</span></code></a> (&quot;;&quot; <a class="reference internal" href="simple_stmts.html#grammar-token-simple-stmt"><code class="xref docutils literal notranslate"><span class="pre">simple_stmt</span></code></a>)* [&quot;;&quot;]
</pre>
<p id="index-2">Note that statements always end in a <code class="docutils literal notranslate"><span class="pre">NEWLINE</span></code> possibly followed by a
<code class="docutils literal notranslate"><span class="pre">DEDENT</span></code>. Also note that optional continuation clauses always begin with a
keyword that cannot start a statement, thus there are no ambiguities (the
dangling <a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> problem is solved in Python by requiring nested
<a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statements to be indented).</p>
<p>The formatting of the grammar rules in the following sections places each clause
on a separate line for clarity.</p>
<div class="section" id="the-if-statement">
<span id="else"></span><span id="elif"></span><span id="if"></span><h2>8.1. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> statement<a class="headerlink" href="#the-if-statement" title="Permalink to this headline"></a></h2>
<p id="index-3">The <a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement is used for conditional execution:</p>
<pre>
<strong id="grammar-token-if-stmt">if_stmt</strong> ::= &quot;if&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
(&quot;elif&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>)*
[&quot;else&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
</pre>
<p>It selects exactly one of the suites by evaluating the expressions one by one
until one is found to be true (see section <a class="reference internal" href="expressions.html#booleans"><span class="std std-ref">Boolean operations</span></a> for the definition of
true and false); then that suite is executed (and no other part of the
<a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement is executed or evaluated). If all expressions are
false, the suite of the <a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clause, if present, is executed.</p>
</div>
<div class="section" id="the-while-statement">
<span id="while"></span><h2>8.2. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code> statement<a class="headerlink" href="#the-while-statement" title="Permalink to this headline"></a></h2>
<p id="index-4">The <a class="reference internal" href="#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> statement is used for repeated execution as long as an
expression is true:</p>
<pre>
<strong id="grammar-token-while-stmt">while_stmt</strong> ::= &quot;while&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
[&quot;else&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
</pre>
<p>This repeatedly tests the expression and, if it is true, executes the first
suite; if the expression is false (which may be the first time it is tested) the
suite of the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause, if present, is executed and the loop
terminates.</p>
<p id="index-5">A <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> statement executed in the first suite terminates the loop
without executing the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clauses suite. A <a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a>
statement executed in the first suite skips the rest of the suite and goes back
to testing the expression.</p>
</div>
<div class="section" id="the-for-statement">
<span id="for"></span><h2>8.3. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> statement<a class="headerlink" href="#the-for-statement" title="Permalink to this headline"></a></h2>
<p id="index-6">The <a class="reference internal" href="#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statement is used to iterate over the elements of a sequence
(such as a string, tuple or list) or other iterable object:</p>
<pre>
<strong id="grammar-token-for-stmt">for_stmt</strong> ::= &quot;for&quot; <a class="reference internal" href="simple_stmts.html#grammar-token-target-list"><code class="xref docutils literal notranslate"><span class="pre">target_list</span></code></a> &quot;in&quot; <a class="reference internal" href="expressions.html#grammar-token-expression-list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a> &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
[&quot;else&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
</pre>
<p>The expression list is evaluated once; it should yield an iterable object. An
iterator is created for the result of the <code class="docutils literal notranslate"><span class="pre">expression_list</span></code>. The suite is
then executed once for each item provided by the iterator, in the order returned
by the iterator. Each item in turn is assigned to the target list using the
standard rules for assignments (see <a class="reference internal" href="simple_stmts.html#assignment"><span class="std std-ref">Assignment statements</span></a>), and then the suite is
executed. When the items are exhausted (which is immediately when the sequence
is empty or an iterator raises a <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception), the suite in
the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause, if present, is executed, and the loop terminates.</p>
<p id="index-7">A <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> statement executed in the first suite terminates the loop
without executing the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clauses suite. A <a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a>
statement executed in the first suite skips the rest of the suite and continues
with the next item, or with the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause if there is no next
item.</p>
<p>The for-loop makes assignments to the variables(s) in the target list.
This overwrites all previous assignments to those variables including
those made in the suite of the for-loop:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
<span class="n">i</span> <span class="o">=</span> <span class="mi">5</span> <span class="c1"># this will not affect the for-loop</span>
<span class="c1"># because i will be overwritten with the next</span>
<span class="c1"># index in the range</span>
</pre></div>
</div>
<p id="index-8">Names in the target list are not deleted when the loop is finished, but if the
sequence is empty, they will not have been assigned to at all by the loop. Hint:
the built-in function <a class="reference internal" href="../library/stdtypes.html#range" title="range"><code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code></a> returns an iterator of integers suitable to
emulate the effect of Pascals <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">i</span> <span class="pre">:=</span> <span class="pre">a</span> <span class="pre">to</span> <span class="pre">b</span> <span class="pre">do</span></code>; e.g., <code class="docutils literal notranslate"><span class="pre">list(range(3))</span></code>
returns the list <code class="docutils literal notranslate"><span class="pre">[0,</span> <span class="pre">1,</span> <span class="pre">2]</span></code>.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p id="index-9">There is a subtlety when the sequence is being modified by the loop (this can
only occur for mutable sequences, e.g. lists). An internal counter is used
to keep track of which item is used next, and this is incremented on each
iteration. When this counter has reached the length of the sequence the loop
terminates. This means that if the suite deletes the current (or a previous)
item from the sequence, the next item will be skipped (since it gets the
index of the current item which has already been treated). Likewise, if the
suite inserts an item in the sequence before the current item, the current
item will be treated again the next time through the loop. This can lead to
nasty bugs that can be avoided by making a temporary copy using a slice of
the whole sequence, e.g.,</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">a</span><span class="p">[:]:</span>
<span class="k">if</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">:</span> <span class="n">a</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="the-try-statement">
<span id="finally"></span><span id="except"></span><span id="try"></span><h2>8.4. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> statement<a class="headerlink" href="#the-try-statement" title="Permalink to this headline"></a></h2>
<p id="index-10">The <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement specifies exception handlers and/or cleanup code
for a group of statements:</p>
<pre>
<strong id="grammar-token-try-stmt">try_stmt </strong> ::= <a class="reference internal" href="#grammar-token-try1-stmt"><code class="xref docutils literal notranslate"><span class="pre">try1_stmt</span></code></a> | <a class="reference internal" href="#grammar-token-try2-stmt"><code class="xref docutils literal notranslate"><span class="pre">try2_stmt</span></code></a>
<strong id="grammar-token-try1-stmt">try1_stmt</strong> ::= &quot;try&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
(&quot;except&quot; [<a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> [&quot;as&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>]] &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>)+
[&quot;else&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
[&quot;finally&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
<strong id="grammar-token-try2-stmt">try2_stmt</strong> ::= &quot;try&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
&quot;finally&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
</pre>
<p>The <a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> clause(s) specify one or more exception handlers. When no
exception occurs in the <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> clause, no exception handler is executed.
When an exception occurs in the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> suite, a search for an exception
handler is started. This search inspects the except clauses in turn until one
is found that matches the exception. An expression-less except clause, if
present, must be last; it matches any exception. For an except clause with an
expression, that expression is evaluated, and the clause matches the exception
if the resulting object is “compatible” with the exception. An object is
compatible with an exception if it is the class or a base class of the exception
object or a tuple containing an item compatible with the exception.</p>
<p>If no except clause matches the exception, the search for an exception handler
continues in the surrounding code and on the invocation stack. <a class="footnote-reference brackets" href="#id4" id="id1">1</a></p>
<p>If the evaluation of an expression in the header of an except clause raises an
exception, the original search for a handler is canceled and a search starts for
the new exception in the surrounding code and on the call stack (it is treated
as if the entire <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement raised the exception).</p>
<p id="index-11">When a matching except clause is found, the exception is assigned to the target
specified after the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code> keyword in that except clause, if present, and
the except clauses suite is executed. All except clauses must have an
executable block. When the end of this block is reached, execution continues
normally after the entire try statement. (This means that if two nested
handlers exist for the same exception, and the exception occurs in the try
clause of the inner handler, the outer handler will not handle the exception.)</p>
<p>When an exception has been assigned using <code class="docutils literal notranslate"><span class="pre">as</span> <span class="pre">target</span></code>, it is cleared at the
end of the except clause. This is as if</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">except</span> <span class="n">E</span> <span class="k">as</span> <span class="n">N</span><span class="p">:</span>
<span class="n">foo</span>
</pre></div>
</div>
<p>was translated to</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">except</span> <span class="n">E</span> <span class="k">as</span> <span class="n">N</span><span class="p">:</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">foo</span>
<span class="k">finally</span><span class="p">:</span>
<span class="k">del</span> <span class="n">N</span>
</pre></div>
</div>
<p>This means the exception must be assigned to a different name to be able to
refer to it after the except clause. Exceptions are cleared because with the
traceback attached to them, they form a reference cycle with the stack frame,
keeping all locals in that frame alive until the next garbage collection occurs.</p>
<p id="index-12">Before an except clauses suite is executed, details about the exception are
stored in the <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module and can be accessed via <a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>.
<a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a> returns a 3-tuple consisting of the exception class, the
exception instance and a traceback object (see section <a class="reference internal" href="datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a>) identifying
the point in the program where the exception occurred. <a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>
values are restored to their previous values (before the call) when returning
from a function that handled an exception.</p>
<p id="index-13">The optional <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause is executed if the control flow leaves the
<a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> suite, no exception was raised, and no <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a>,
<a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a>, or <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> statement was executed. Exceptions in
the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause are not handled by the preceding <a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a>
clauses.</p>
<p id="index-14">If <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> is present, it specifies a cleanup handler. The
<a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> clause is executed, including any <a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> and
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clauses. If an exception occurs in any of the clauses and is
not handled, the exception is temporarily saved. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause
is executed. If there is a saved exception it is re-raised at the end of the
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause. If the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause raises another
exception, the saved exception is set as the context of the new exception.
If the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause executes a <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> or <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a>
statement, the saved exception is discarded:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
<span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="mi">1</span><span class="o">/</span><span class="mi">0</span>
<span class="gp">... </span> <span class="k">finally</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">return</span> <span class="mi">42</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">()</span>
<span class="go">42</span>
</pre></div>
</div>
<p>The exception information is not available to the program during execution of
the <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause.</p>
<p id="index-15">When a <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a>, <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> or <a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> statement is
executed in the <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> suite of a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code>
statement, the <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause is also executed on the way out. A
<a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> statement is illegal in the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause. (The
reason is a problem with the current implementation — this restriction may be
lifted in the future).</p>
<p>The return value of a function is determined by the last <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a>
statement executed. Since the <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause always executes, a
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code> statement executed in the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause will
always be the last one executed:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">foo</span><span class="p">():</span>
<span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">return</span> <span class="s1">&#39;try&#39;</span>
<span class="gp">... </span> <span class="k">finally</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">return</span> <span class="s1">&#39;finally&#39;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">foo</span><span class="p">()</span>
<span class="go">&#39;finally&#39;</span>
</pre></div>
</div>
<p>Additional information on exceptions can be found in section <a class="reference internal" href="executionmodel.html#exceptions"><span class="std std-ref">Exceptions</span></a>,
and information on using the <a class="reference internal" href="simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> statement to generate exceptions
may be found in section <a class="reference internal" href="simple_stmts.html#raise"><span class="std std-ref">The raise statement</span></a>.</p>
</div>
<div class="section" id="the-with-statement">
<span id="as"></span><span id="with"></span><h2>8.5. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> statement<a class="headerlink" href="#the-with-statement" title="Permalink to this headline"></a></h2>
<p id="index-16">The <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement is used to wrap the execution of a block with
methods defined by a context manager (see section <a class="reference internal" href="datamodel.html#context-managers"><span class="std std-ref">With Statement Context Managers</span></a>).
This allows common <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a><a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a><a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a>
usage patterns to be encapsulated for convenient reuse.</p>
<pre>
<strong id="grammar-token-with-stmt">with_stmt</strong> ::= &quot;with&quot; <a class="reference internal" href="#grammar-token-with-item"><code class="xref docutils literal notranslate"><span class="pre">with_item</span></code></a> (&quot;,&quot; <a class="reference internal" href="#grammar-token-with-item"><code class="xref docutils literal notranslate"><span class="pre">with_item</span></code></a>)* &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
<strong id="grammar-token-with-item">with_item</strong> ::= <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> [&quot;as&quot; <a class="reference internal" href="simple_stmts.html#grammar-token-target"><code class="xref docutils literal notranslate"><span class="pre">target</span></code></a>]
</pre>
<p>The execution of the <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement with one “item” proceeds as follows:</p>
<ol class="arabic">
<li><p>The context expression (the expression given in the <a class="reference internal" href="#grammar-token-with-item"><code class="xref std std-token docutils literal notranslate"><span class="pre">with_item</span></code></a>) is
evaluated to obtain a context manager.</p></li>
<li><p>The context managers <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> is loaded for later use.</p></li>
<li><p>The context managers <a class="reference internal" href="datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> method is invoked.</p></li>
<li><p>If a target was included in the <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement, the return value
from <a class="reference internal" href="datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> is assigned to it.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>The <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement guarantees that if the <a class="reference internal" href="datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a>
method returns without an error, then <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> will always be
called. Thus, if an error occurs during the assignment to the target list,
it will be treated the same as an error occurring within the suite would
be. See step 6 below.</p>
</div>
</li>
<li><p>The suite is executed.</p></li>
<li><p>The context managers <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method is invoked. If an exception
caused the suite to be exited, its type, value, and traceback are passed as
arguments to <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a>. Otherwise, three <a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> arguments are
supplied.</p>
<p>If the suite was exited due to an exception, and the return value from the
<a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method was false, the exception is reraised. If the return
value was true, the exception is suppressed, and execution continues with the
statement following the <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.</p>
<p>If the suite was exited for any reason other than an exception, the return
value from <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> is ignored, and execution proceeds at the normal
location for the kind of exit that was taken.</p>
</li>
</ol>
<p>With more than one item, the context managers are processed as if multiple
<a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statements were nested:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">A</span><span class="p">()</span> <span class="k">as</span> <span class="n">a</span><span class="p">,</span> <span class="n">B</span><span class="p">()</span> <span class="k">as</span> <span class="n">b</span><span class="p">:</span>
<span class="n">suite</span>
</pre></div>
</div>
<p>is equivalent to</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">A</span><span class="p">()</span> <span class="k">as</span> <span class="n">a</span><span class="p">:</span>
<span class="k">with</span> <span class="n">B</span><span class="p">()</span> <span class="k">as</span> <span class="n">b</span><span class="p">:</span>
<span class="n">suite</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">Changed in version 3.1: </span>Support for multiple context expressions.</p>
</div>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<dl class="simple">
<dt><span class="target" id="index-17"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0343"><strong>PEP 343</strong></a> - The “with” statement</dt><dd><p>The specification, background, and examples for the Python <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>
statement.</p>
</dd>
</dl>
</div>
</div>
<div class="section" id="function-definitions">
<span id="def"></span><span id="function"></span><span id="index-18"></span><h2>8.6. Function definitions<a class="headerlink" href="#function-definitions" title="Permalink to this headline"></a></h2>
<p id="index-19">A function definition defines a user-defined function object (see section
<a class="reference internal" href="datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a>):</p>
<pre>
<strong id="grammar-token-funcdef">funcdef </strong> ::= [<a class="reference internal" href="#grammar-token-decorators"><code class="xref docutils literal notranslate"><span class="pre">decorators</span></code></a>] &quot;def&quot; <a class="reference internal" href="#grammar-token-funcname"><code class="xref docutils literal notranslate"><span class="pre">funcname</span></code></a> &quot;(&quot; [<a class="reference internal" href="#grammar-token-parameter-list"><code class="xref docutils literal notranslate"><span class="pre">parameter_list</span></code></a>] &quot;)&quot;
[&quot;-&gt;&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>] &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
<strong id="grammar-token-decorators">decorators </strong> ::= <a class="reference internal" href="#grammar-token-decorator"><code class="xref docutils literal notranslate"><span class="pre">decorator</span></code></a>+
<strong id="grammar-token-decorator">decorator </strong> ::= &quot;&#64;&quot; <a class="reference internal" href="#grammar-token-dotted-name"><code class="xref docutils literal notranslate"><span class="pre">dotted_name</span></code></a> [&quot;(&quot; [<a class="reference internal" href="expressions.html#grammar-token-argument-list"><code class="xref docutils literal notranslate"><span class="pre">argument_list</span></code></a> [&quot;,&quot;]] &quot;)&quot;] NEWLINE
<strong id="grammar-token-dotted-name">dotted_name </strong> ::= <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> (&quot;.&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>)*
<strong id="grammar-token-parameter-list">parameter_list </strong> ::= <a class="reference internal" href="#grammar-token-defparameter"><code class="xref docutils literal notranslate"><span class="pre">defparameter</span></code></a> (&quot;,&quot; <a class="reference internal" href="#grammar-token-defparameter"><code class="xref docutils literal notranslate"><span class="pre">defparameter</span></code></a>)* [&quot;,&quot; [<a class="reference internal" href="#grammar-token-parameter-list-starargs"><code class="xref docutils literal notranslate"><span class="pre">parameter_list_starargs</span></code></a>]]
| <a class="reference internal" href="#grammar-token-parameter-list-starargs"><code class="xref docutils literal notranslate"><span class="pre">parameter_list_starargs</span></code></a>
<strong id="grammar-token-parameter-list-starargs">parameter_list_starargs</strong> ::= &quot;*&quot; [<a class="reference internal" href="#grammar-token-parameter"><code class="xref docutils literal notranslate"><span class="pre">parameter</span></code></a>] (&quot;,&quot; <a class="reference internal" href="#grammar-token-defparameter"><code class="xref docutils literal notranslate"><span class="pre">defparameter</span></code></a>)* [&quot;,&quot; [&quot;**&quot; <a class="reference internal" href="#grammar-token-parameter"><code class="xref docutils literal notranslate"><span class="pre">parameter</span></code></a> [&quot;,&quot;]]]
| &quot;**&quot; <a class="reference internal" href="#grammar-token-parameter"><code class="xref docutils literal notranslate"><span class="pre">parameter</span></code></a> [&quot;,&quot;]
<strong id="grammar-token-parameter">parameter </strong> ::= <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> [&quot;:&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>]
<strong id="grammar-token-defparameter">defparameter </strong> ::= <a class="reference internal" href="#grammar-token-parameter"><code class="xref docutils literal notranslate"><span class="pre">parameter</span></code></a> [&quot;=&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>]
<strong id="grammar-token-funcname">funcname </strong> ::= <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>
</pre>
<p>A function definition is an executable statement. Its execution binds the
function name in the current local namespace to a function object (a wrapper
around the executable code for the function). This function object contains a
reference to the current global namespace as the global namespace to be used
when the function is called.</p>
<p>The function definition does not execute the function body; this gets executed
only when the function is called. <a class="footnote-reference brackets" href="#id5" id="id2">2</a></p>
<p id="index-20">A function definition may be wrapped by one or more <a class="reference internal" href="../glossary.html#term-decorator"><span class="xref std std-term">decorator</span></a> expressions.
Decorator expressions are evaluated when the function is defined, in the scope
that contains the function definition. The result must be a callable, which is
invoked with the function object as the only argument. The returned value is
bound to the function name instead of the function object. Multiple decorators
are applied in nested fashion. For example, the following code</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nd">@f1</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span>
<span class="nd">@f2</span>
<span class="k">def</span> <span class="nf">func</span><span class="p">():</span> <span class="k">pass</span>
</pre></div>
</div>
<p>is roughly equivalent to</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">func</span><span class="p">():</span> <span class="k">pass</span>
<span class="n">func</span> <span class="o">=</span> <span class="n">f1</span><span class="p">(</span><span class="n">arg</span><span class="p">)(</span><span class="n">f2</span><span class="p">(</span><span class="n">func</span><span class="p">))</span>
</pre></div>
</div>
<p>except that the original function is not temporarily bound to the name <code class="docutils literal notranslate"><span class="pre">func</span></code>.</p>
<p id="index-21">When one or more <a class="reference internal" href="../glossary.html#term-parameter"><span class="xref std std-term">parameters</span></a> have the form <em>parameter</em> <code class="docutils literal notranslate"><span class="pre">=</span></code>
<em>expression</em>, the function is said to have “default parameter values.” For a
parameter with a default value, the corresponding <a class="reference internal" href="../glossary.html#term-argument"><span class="xref std std-term">argument</span></a> may be
omitted from a call, in which
case the parameters default value is substituted. If a parameter has a default
value, all following parameters up until the “<code class="docutils literal notranslate"><span class="pre">*</span></code>” must also have a default
value — this is a syntactic restriction that is not expressed by the grammar.</p>
<p><strong>Default parameter values are evaluated from left to right when the function
definition is executed.</strong> This means that the expression is evaluated once, when
the function is defined, and that the same “pre-computed” value is used for each
call. This is especially important to understand when a default parameter is a
mutable object, such as a list or a dictionary: if the function modifies the
object (e.g. by appending an item to a list), the default value is in effect
modified. This is generally not what was intended. A way around this is to use
<code class="docutils literal notranslate"><span class="pre">None</span></code> as the default, and explicitly test for it in the body of the function,
e.g.:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">whats_on_the_telly</span><span class="p">(</span><span class="n">penguin</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="k">if</span> <span class="n">penguin</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">penguin</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">penguin</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s2">&quot;property of the zoo&quot;</span><span class="p">)</span>
<span class="k">return</span> <span class="n">penguin</span>
</pre></div>
</div>
<p id="index-22">Function call semantics are described in more detail in section <a class="reference internal" href="expressions.html#calls"><span class="std std-ref">Calls</span></a>. A
function call always assigns values to all parameters mentioned in the parameter
list, either from position arguments, from keyword arguments, or from default
values. If the form “<code class="docutils literal notranslate"><span class="pre">*identifier</span></code>” is present, it is initialized to a tuple
receiving any excess positional parameters, defaulting to the empty tuple.
If the form “<code class="docutils literal notranslate"><span class="pre">**identifier</span></code>” is present, it is initialized to a new
ordered mapping receiving any excess keyword arguments, defaulting to a
new empty mapping of the same type. Parameters after “<code class="docutils literal notranslate"><span class="pre">*</span></code>” or
<code class="docutils literal notranslate"><span class="pre">*identifier</span></code>” are keyword-only parameters and may only be passed
used keyword arguments.</p>
<p id="index-23">Parameters may have an <a class="reference internal" href="../glossary.html#term-function-annotation"><span class="xref std std-term">annotation</span></a> of the form “<code class="docutils literal notranslate"><span class="pre">:</span> <span class="pre">expression</span></code>
following the parameter name. Any parameter may have an annotation, even those of the form
<code class="docutils literal notranslate"><span class="pre">*identifier</span></code> or <code class="docutils literal notranslate"><span class="pre">**identifier</span></code>. Functions may have “return” annotation of
the form “<code class="docutils literal notranslate"><span class="pre">-&gt;</span> <span class="pre">expression</span></code>” after the parameter list. These annotations can be
any valid Python expression. The presence of annotations does not change the
semantics of a function. The annotation values are available as values of
a dictionary keyed by the parameters names in the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__annotations__</span></code>
attribute of the function object. If the <code class="docutils literal notranslate"><span class="pre">annotations</span></code> import from
<a class="reference internal" href="../library/__future__.html#module-__future__" title="__future__: Future statement definitions"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code></a> is used, annotations are preserved as strings at runtime which
enables postponed evaluation. Otherwise, they are evaluated when the function
definition is executed. In this case annotations may be evaluated in
a different order than they appear in the source code.</p>
<p id="index-24">It is also possible to create anonymous functions (functions not bound to a
name), for immediate use in expressions. This uses lambda expressions, described in
section <a class="reference internal" href="expressions.html#lambda"><span class="std std-ref">Lambdas</span></a>. Note that the lambda expression is merely a shorthand for a
simplified function definition; a function defined in a “<a class="reference internal" href="#def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">def</span></code></a>
statement can be passed around or assigned to another name just like a function
defined by a lambda expression. The “<code class="xref std std-keyword docutils literal notranslate"><span class="pre">def</span></code>” form is actually more powerful
since it allows the execution of multiple statements and annotations.</p>
<p><strong>Programmers note:</strong> Functions are first-class objects. A “<code class="docutils literal notranslate"><span class="pre">def</span></code>” statement
executed inside a function definition defines a local function that can be
returned or passed around. Free variables used in the nested function can
access the local variables of the function containing the def. See section
<a class="reference internal" href="executionmodel.html#naming"><span class="std std-ref">Naming and binding</span></a> for details.</p>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<dl class="simple">
<dt><span class="target" id="index-25"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3107"><strong>PEP 3107</strong></a> - Function Annotations</dt><dd><p>The original specification for function annotations.</p>
</dd>
<dt><span class="target" id="index-26"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0484"><strong>PEP 484</strong></a> - Type Hints</dt><dd><p>Definition of a standard meaning for annotations: type hints.</p>
</dd>
<dt><span class="target" id="index-27"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0526"><strong>PEP 526</strong></a> - Syntax for Variable Annotations</dt><dd><p>Ability to type hint variable declarations, including class
variables and instance variables</p>
</dd>
<dt><span class="target" id="index-28"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0563"><strong>PEP 563</strong></a> - Postponed Evaluation of Annotations</dt><dd><p>Support for forward references within annotations by preserving
annotations in a string form at runtime instead of eager evaluation.</p>
</dd>
</dl>
</div>
</div>
<div class="section" id="class-definitions">
<span id="class"></span><h2>8.7. Class definitions<a class="headerlink" href="#class-definitions" title="Permalink to this headline"></a></h2>
<p id="index-29">A class definition defines a class object (see section <a class="reference internal" href="datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a>):</p>
<pre>
<strong id="grammar-token-classdef">classdef </strong> ::= [<a class="reference internal" href="#grammar-token-decorators"><code class="xref docutils literal notranslate"><span class="pre">decorators</span></code></a>] &quot;class&quot; <a class="reference internal" href="#grammar-token-classname"><code class="xref docutils literal notranslate"><span class="pre">classname</span></code></a> [<a class="reference internal" href="#grammar-token-inheritance"><code class="xref docutils literal notranslate"><span class="pre">inheritance</span></code></a>] &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
<strong id="grammar-token-inheritance">inheritance</strong> ::= &quot;(&quot; [<a class="reference internal" href="expressions.html#grammar-token-argument-list"><code class="xref docutils literal notranslate"><span class="pre">argument_list</span></code></a>] &quot;)&quot;
<strong id="grammar-token-classname">classname </strong> ::= <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>
</pre>
<p>A class definition is an executable statement. The inheritance list usually
gives a list of base classes (see <a class="reference internal" href="datamodel.html#metaclasses"><span class="std std-ref">Metaclasses</span></a> for more advanced uses), so
each item in the list should evaluate to a class object which allows
subclassing. Classes without an inheritance list inherit, by default, from the
base class <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>; hence,</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Foo</span><span class="p">:</span>
<span class="k">pass</span>
</pre></div>
</div>
<p>is equivalent to</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Foo</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="k">pass</span>
</pre></div>
</div>
<p>The classs suite is then executed in a new execution frame (see <a class="reference internal" href="executionmodel.html#naming"><span class="std std-ref">Naming and binding</span></a>),
using a newly created local namespace and the original global namespace.
(Usually, the suite contains mostly function definitions.) When the classs
suite finishes execution, its execution frame is discarded but its local
namespace is saved. <a class="footnote-reference brackets" href="#id6" id="id3">3</a> A class object is then created using the inheritance
list for the base classes and the saved local namespace for the attribute
dictionary. The class name is bound to this class object in the original local
namespace.</p>
<p>The order in which attributes are defined in the class body is preserved
in the new classs <code class="docutils literal notranslate"><span class="pre">__dict__</span></code>. Note that this is reliable only right
after the class is created and only for classes that were defined using
the definition syntax.</p>
<p>Class creation can be customized heavily using <a class="reference internal" href="datamodel.html#metaclasses"><span class="std std-ref">metaclasses</span></a>.</p>
<p id="index-30">Classes can also be decorated: just like when decorating functions,</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nd">@f1</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span>
<span class="nd">@f2</span>
<span class="k">class</span> <span class="nc">Foo</span><span class="p">:</span> <span class="k">pass</span>
</pre></div>
</div>
<p>is roughly equivalent to</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Foo</span><span class="p">:</span> <span class="k">pass</span>
<span class="n">Foo</span> <span class="o">=</span> <span class="n">f1</span><span class="p">(</span><span class="n">arg</span><span class="p">)(</span><span class="n">f2</span><span class="p">(</span><span class="n">Foo</span><span class="p">))</span>
</pre></div>
</div>
<p>The evaluation rules for the decorator expressions are the same as for function
decorators. The result is then bound to the class name.</p>
<p><strong>Programmers note:</strong> Variables defined in the class definition are class
attributes; they are shared by instances. Instance attributes can be set in a
method with <code class="docutils literal notranslate"><span class="pre">self.name</span> <span class="pre">=</span> <span class="pre">value</span></code>. Both class and instance attributes are
accessible through the notation “<code class="docutils literal notranslate"><span class="pre">self.name</span></code>”, and an instance attribute hides
a class attribute with the same name when accessed in this way. Class
attributes can be used as defaults for instance attributes, but using mutable
values there can lead to unexpected results. <a class="reference internal" href="datamodel.html#descriptors"><span class="std std-ref">Descriptors</span></a>
can be used to create instance variables with different implementation details.</p>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<dl class="simple">
<dt><span class="target" id="index-31"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3115"><strong>PEP 3115</strong></a> - Metaclasses in Python 3000</dt><dd><p>The proposal that changed the declaration of metaclasses to the current
syntax, and the semantics for how classes with metaclasses are
constructed.</p>
</dd>
<dt><span class="target" id="index-32"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3129"><strong>PEP 3129</strong></a> - Class Decorators</dt><dd><p>The proposal that added class decorators. Function and method decorators
were introduced in <span class="target" id="index-33"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0318"><strong>PEP 318</strong></a>.</p>
</dd>
</dl>
</div>
</div>
<div class="section" id="coroutines">
<span id="async"></span><h2>8.8. Coroutines<a class="headerlink" href="#coroutines" title="Permalink to this headline"></a></h2>
<div class="versionadded">
<p><span class="versionmodified added">New in version 3.5.</span></p>
</div>
<div class="section" id="coroutine-function-definition">
<span id="async-def"></span><span id="index-34"></span><h3>8.8.1. Coroutine function definition<a class="headerlink" href="#coroutine-function-definition" title="Permalink to this headline"></a></h3>
<pre>
<strong id="grammar-token-async-funcdef">async_funcdef</strong> ::= [<a class="reference internal" href="#grammar-token-decorators"><code class="xref docutils literal notranslate"><span class="pre">decorators</span></code></a>] &quot;async&quot; &quot;def&quot; <a class="reference internal" href="#grammar-token-funcname"><code class="xref docutils literal notranslate"><span class="pre">funcname</span></code></a> &quot;(&quot; [<a class="reference internal" href="#grammar-token-parameter-list"><code class="xref docutils literal notranslate"><span class="pre">parameter_list</span></code></a>] &quot;)&quot;
[&quot;-&gt;&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>] &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
</pre>
<p id="index-35">Execution of Python coroutines can be suspended and resumed at many points
(see <a class="reference internal" href="../glossary.html#term-coroutine"><span class="xref std std-term">coroutine</span></a>). Inside the body of a coroutine function, <code class="docutils literal notranslate"><span class="pre">await</span></code> and
<code class="docutils literal notranslate"><span class="pre">async</span></code> identifiers become reserved keywords; <a class="reference internal" href="expressions.html#await"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code></a> expressions,
<a class="reference internal" href="#async-for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code></a> and <a class="reference internal" href="#async-with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code></a> can only be used in
coroutine function bodies.</p>
<p>Functions defined with <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code> syntax are always coroutine functions,
even if they do not contain <code class="docutils literal notranslate"><span class="pre">await</span></code> or <code class="docutils literal notranslate"><span class="pre">async</span></code> keywords.</p>
<p>It is a <a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> to use a <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code> expression inside the body
of a coroutine function.</p>
<p>An example of a coroutine function:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span> <span class="nf">func</span><span class="p">(</span><span class="n">param1</span><span class="p">,</span> <span class="n">param2</span><span class="p">):</span>
<span class="n">do_stuff</span><span class="p">()</span>
<span class="k">await</span> <span class="n">some_coroutine</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="the-async-for-statement">
<span id="async-for"></span><span id="index-36"></span><h3>8.8.2. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code> statement<a class="headerlink" href="#the-async-for-statement" title="Permalink to this headline"></a></h3>
<pre>
<strong id="grammar-token-async-for-stmt">async_for_stmt</strong> ::= &quot;async&quot; <a class="reference internal" href="#grammar-token-for-stmt"><code class="xref docutils literal notranslate"><span class="pre">for_stmt</span></code></a>
</pre>
<p>An <a class="reference internal" href="../glossary.html#term-asynchronous-iterable"><span class="xref std std-term">asynchronous iterable</span></a> is able to call asynchronous code in its
<em>iter</em> implementation, and <a class="reference internal" href="../glossary.html#term-asynchronous-iterator"><span class="xref std std-term">asynchronous iterator</span></a> can call asynchronous
code in its <em>next</em> method.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code> statement allows convenient iteration over asynchronous
iterators.</p>
<p>The following code:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">for</span> <span class="n">TARGET</span> <span class="ow">in</span> <span class="n">ITER</span><span class="p">:</span>
<span class="n">BLOCK</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">BLOCK2</span>
</pre></div>
</div>
<p>Is semantically equivalent to:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nb">iter</span> <span class="o">=</span> <span class="p">(</span><span class="n">ITER</span><span class="p">)</span>
<span class="nb">iter</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="nb">iter</span><span class="p">)</span><span class="o">.</span><span class="fm">__aiter__</span><span class="p">(</span><span class="nb">iter</span><span class="p">)</span>
<span class="n">running</span> <span class="o">=</span> <span class="kc">True</span>
<span class="k">while</span> <span class="n">running</span><span class="p">:</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">TARGET</span> <span class="o">=</span> <span class="k">await</span> <span class="nb">type</span><span class="p">(</span><span class="nb">iter</span><span class="p">)</span><span class="o">.</span><span class="fm">__anext__</span><span class="p">(</span><span class="nb">iter</span><span class="p">)</span>
<span class="k">except</span> <span class="n">StopAsyncIteration</span><span class="p">:</span>
<span class="n">running</span> <span class="o">=</span> <span class="kc">False</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">BLOCK</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">BLOCK2</span>
</pre></div>
</div>
<p>See also <a class="reference internal" href="datamodel.html#object.__aiter__" title="object.__aiter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__aiter__()</span></code></a> and <a class="reference internal" href="datamodel.html#object.__anext__" title="object.__anext__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__anext__()</span></code></a> for details.</p>
<p>It is a <a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> to use an <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code> statement outside the
body of a coroutine function.</p>
</div>
<div class="section" id="the-async-with-statement">
<span id="async-with"></span><span id="index-37"></span><h3>8.8.3. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code> statement<a class="headerlink" href="#the-async-with-statement" title="Permalink to this headline"></a></h3>
<pre>
<strong id="grammar-token-async-with-stmt">async_with_stmt</strong> ::= &quot;async&quot; <a class="reference internal" href="#grammar-token-with-stmt"><code class="xref docutils literal notranslate"><span class="pre">with_stmt</span></code></a>
</pre>
<p>An <a class="reference internal" href="../glossary.html#term-asynchronous-context-manager"><span class="xref std std-term">asynchronous context manager</span></a> is a <a class="reference internal" href="../glossary.html#term-context-manager"><span class="xref std std-term">context manager</span></a> that is
able to suspend execution in its <em>enter</em> and <em>exit</em> methods.</p>
<p>The following code:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">with</span> <span class="n">EXPR</span> <span class="k">as</span> <span class="n">VAR</span><span class="p">:</span>
<span class="n">BLOCK</span>
</pre></div>
</div>
<p>Is semantically equivalent to:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">mgr</span> <span class="o">=</span> <span class="p">(</span><span class="n">EXPR</span><span class="p">)</span>
<span class="n">aexit</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="n">mgr</span><span class="p">)</span><span class="o">.</span><span class="fm">__aexit__</span>
<span class="n">aenter</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="n">mgr</span><span class="p">)</span><span class="o">.</span><span class="fm">__aenter__</span><span class="p">(</span><span class="n">mgr</span><span class="p">)</span>
<span class="n">VAR</span> <span class="o">=</span> <span class="k">await</span> <span class="n">aenter</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">BLOCK</span>
<span class="k">except</span><span class="p">:</span>
<span class="k">if</span> <span class="ow">not</span> <span class="k">await</span> <span class="n">aexit</span><span class="p">(</span><span class="n">mgr</span><span class="p">,</span> <span class="o">*</span><span class="n">sys</span><span class="o">.</span><span class="n">exc_info</span><span class="p">()):</span>
<span class="k">raise</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">await</span> <span class="n">aexit</span><span class="p">(</span><span class="n">mgr</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
</pre></div>
</div>
<p>See also <a class="reference internal" href="datamodel.html#object.__aenter__" title="object.__aenter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__aenter__()</span></code></a> and <a class="reference internal" href="datamodel.html#object.__aexit__" title="object.__aexit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__aexit__()</span></code></a> for details.</p>
<p>It is a <a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> to use an <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code> statement outside the
body of a coroutine function.</p>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<dl class="simple">
<dt><span class="target" id="index-38"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0492"><strong>PEP 492</strong></a> - Coroutines with async and await syntax</dt><dd><p>The proposal that made coroutines a proper standalone concept in Python,
and added supporting syntax.</p>
</dd>
</dl>
</div>
<p class="rubric">Footnotes</p>
<dl class="footnote brackets">
<dt class="label" id="id4"><span class="brackets"><a class="fn-backref" href="#id1">1</a></span></dt>
<dd><p>The exception is propagated to the invocation stack unless
there is a <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause which happens to raise another
exception. That new exception causes the old one to be lost.</p>
</dd>
<dt class="label" id="id5"><span class="brackets"><a class="fn-backref" href="#id2">2</a></span></dt>
<dd><p>A string literal appearing as the first statement in the function body is
transformed into the functions <code class="docutils literal notranslate"><span class="pre">__doc__</span></code> attribute and therefore the
functions <a class="reference internal" href="../glossary.html#term-docstring"><span class="xref std std-term">docstring</span></a>.</p>
</dd>
<dt class="label" id="id6"><span class="brackets"><a class="fn-backref" href="#id3">3</a></span></dt>
<dd><p>A string literal appearing as the first statement in the class body is
transformed into the namespaces <code class="docutils literal notranslate"><span class="pre">__doc__</span></code> item and therefore the classs
<a class="reference internal" href="../glossary.html#term-docstring"><span class="xref std std-term">docstring</span></a>.</p>
</dd>
</dl>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="../contents.html">Table of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">8. Compound statements</a><ul>
<li><a class="reference internal" href="#the-if-statement">8.1. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> statement</a></li>
<li><a class="reference internal" href="#the-while-statement">8.2. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code> statement</a></li>
<li><a class="reference internal" href="#the-for-statement">8.3. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> statement</a></li>
<li><a class="reference internal" href="#the-try-statement">8.4. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> statement</a></li>
<li><a class="reference internal" href="#the-with-statement">8.5. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> statement</a></li>
<li><a class="reference internal" href="#function-definitions">8.6. Function definitions</a></li>
<li><a class="reference internal" href="#class-definitions">8.7. Class definitions</a></li>
<li><a class="reference internal" href="#coroutines">8.8. Coroutines</a><ul>
<li><a class="reference internal" href="#coroutine-function-definition">8.8.1. Coroutine function definition</a></li>
<li><a class="reference internal" href="#the-async-for-statement">8.8.2. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code> statement</a></li>
<li><a class="reference internal" href="#the-async-with-statement">8.8.3. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code> statement</a></li>
</ul>
</li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="simple_stmts.html"
title="previous chapter">7. Simple statements</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="toplevel_components.html"
title="next chapter">9. Top-level components</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/reference/compound_stmts.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="toplevel_components.html" title="9. Top-level components"
>next</a> |</li>
<li class="right" >
<a href="simple_stmts.html" title="7. Simple statements"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,368 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>4. Execution model &#8212; Python 3.7.4 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" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="5. The import system" href="import.html" />
<link rel="prev" title="3. Data model" href="datamodel.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/reference/executionmodel.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="import.html" title="5. The import system"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="datamodel.html" title="3. Data model"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="execution-model">
<span id="execmodel"></span><h1>4. Execution model<a class="headerlink" href="#execution-model" title="Permalink to this headline"></a></h1>
<div class="section" id="structure-of-a-program">
<span id="prog-structure"></span><span id="index-0"></span><h2>4.1. Structure of a program<a class="headerlink" href="#structure-of-a-program" title="Permalink to this headline"></a></h2>
<p id="index-1">A Python program is constructed from code blocks.
A <em class="dfn">block</em> is a piece of Python program text that is executed as a unit.
The following are blocks: a module, a function body, and a class definition.
Each command typed interactively is a block. A script file (a file given as
standard input to the interpreter or specified as a command line argument to the
interpreter) is a code block. A script command (a command specified on the
interpreter command line with the <a class="reference internal" href="../using/cmdline.html#cmdoption-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">-c</span></code></a> option) is a code block. The string
argument passed to the built-in functions <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> and <a class="reference internal" href="../library/functions.html#exec" title="exec"><code class="xref py py-func docutils literal notranslate"><span class="pre">exec()</span></code></a> is a
code block.</p>
<p id="index-2">A code block is executed in an <em class="dfn">execution frame</em>. A frame contains some
administrative information (used for debugging) and determines where and how
execution continues after the code blocks execution has completed.</p>
</div>
<div class="section" id="naming-and-binding">
<span id="naming"></span><h2>4.2. Naming and binding<a class="headerlink" href="#naming-and-binding" title="Permalink to this headline"></a></h2>
<div class="section" id="binding-of-names">
<span id="bind-names"></span><span id="index-3"></span><h3>4.2.1. Binding of names<a class="headerlink" href="#binding-of-names" title="Permalink to this headline"></a></h3>
<p id="index-4"><em class="dfn">Names</em> refer to objects. Names are introduced by name binding operations.</p>
<p id="index-5">The following constructs bind names: formal parameters to functions,
<a class="reference internal" href="simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statements, class and function definitions (these bind the
class or function name in the defining block), and targets that are identifiers
if occurring in an assignment, <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop header, or after
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code> in a <a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement or <a class="reference internal" href="compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> clause.
The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code> statement
of the form <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">...</span> <span class="pre">import</span> <span class="pre">*</span></code> binds all names defined in the imported
module, except those beginning with an underscore. This form may only be used
at the module level.</p>
<p>A target occurring in a <a class="reference internal" href="simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> statement is also considered bound for
this purpose (though the actual semantics are to unbind the name).</p>
<p>Each assignment or import statement occurs within a block defined by a class or
function definition or at the module level (the top-level code block).</p>
<p id="index-6">If a name is bound in a block, it is a local variable of that block, unless
declared as <a class="reference internal" href="simple_stmts.html#nonlocal"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></a> or <a class="reference internal" href="simple_stmts.html#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a>. If a name is bound at
the module level, it is a global variable. (The variables of the module code
block are local and global.) If a variable is used in a code block but not
defined there, it is a <em class="dfn">free variable</em>.</p>
<p>Each occurrence of a name in the program text refers to the <em class="dfn">binding</em> of
that name established by the following name resolution rules.</p>
</div>
<div class="section" id="resolution-of-names">
<span id="resolve-names"></span><h3>4.2.2. Resolution of names<a class="headerlink" href="#resolution-of-names" title="Permalink to this headline"></a></h3>
<p id="index-7">A <em class="dfn">scope</em> defines the visibility of a name within a block. If a local
variable is defined in a block, its scope includes that block. If the
definition occurs in a function block, the scope extends to any blocks contained
within the defining one, unless a contained block introduces a different binding
for the name.</p>
<p id="index-8">When a name is used in a code block, it is resolved using the nearest enclosing
scope. The set of all such scopes visible to a code block is called the blocks
<em class="dfn">environment</em>.</p>
<p id="index-9">When a name is not found at all, a <a class="reference internal" href="../library/exceptions.html#NameError" title="NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a> exception is raised.
If the current scope is a function scope, and the name refers to a local
variable that has not yet been bound to a value at the point where the name is
used, an <a class="reference internal" href="../library/exceptions.html#UnboundLocalError" title="UnboundLocalError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnboundLocalError</span></code></a> exception is raised.
<a class="reference internal" href="../library/exceptions.html#UnboundLocalError" title="UnboundLocalError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnboundLocalError</span></code></a> is a subclass of <a class="reference internal" href="../library/exceptions.html#NameError" title="NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a>.</p>
<p>If a name binding operation occurs anywhere within a code block, all uses of the
name within the block are treated as references to the current block. This can
lead to errors when a name is used within a block before it is bound. This rule
is subtle. Python lacks declarations and allows name binding operations to
occur anywhere within a code block. The local variables of a code block can be
determined by scanning the entire text of the block for name binding operations.</p>
<p>If the <a class="reference internal" href="simple_stmts.html#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statement occurs within a block, all uses of the name
specified in the statement refer to the binding of that name in the top-level
namespace. Names are resolved in the top-level namespace by searching the
global namespace, i.e. the namespace of the module containing the code block,
and the builtins namespace, the namespace of the module <a class="reference internal" href="../library/builtins.html#module-builtins" title="builtins: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">builtins</span></code></a>. The
global namespace is searched first. If the name is not found there, the
builtins namespace is searched. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code> statement must precede
all uses of the name.</p>
<p>The <a class="reference internal" href="simple_stmts.html#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statement has the same scope as a name binding operation
in the same block. If the nearest enclosing scope for a free variable contains
a global statement, the free variable is treated as a global.</p>
<p>The <a class="reference internal" href="simple_stmts.html#nonlocal"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></a> statement causes corresponding names to refer
to previously bound variables in the nearest enclosing function scope.
<a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> is raised at compile time if the given name does not
exist in any enclosing function scope.</p>
<p id="index-10">The namespace for a module is automatically created the first time a module is
imported. The main module for a script is always called <a class="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a>.</p>
<p>Class definition blocks and arguments to <a class="reference internal" href="../library/functions.html#exec" title="exec"><code class="xref py py-func docutils literal notranslate"><span class="pre">exec()</span></code></a> and <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> are
special in the context of name resolution.
A class definition is an executable statement that may use and define names.
These references follow the normal rules for name resolution with an exception
that unbound local variables are looked up in the global namespace.
The namespace of the class definition becomes the attribute dictionary of
the class. The scope of names defined in a class block is limited to the
class block; it does not extend to the code blocks of methods this includes
comprehensions and generator expressions since they are implemented using a
function scope. This means that the following will fail:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">A</span><span class="p">:</span>
<span class="n">a</span> <span class="o">=</span> <span class="mi">42</span>
<span class="n">b</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">a</span> <span class="o">+</span> <span class="n">i</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="section" id="builtins-and-restricted-execution">
<span id="restrict-exec"></span><h3>4.2.3. Builtins and restricted execution<a class="headerlink" href="#builtins-and-restricted-execution" title="Permalink to this headline"></a></h3>
<div class="impl-detail compound" id="index-11">
<p><strong>CPython implementation detail:</strong> Users should not touch <code class="docutils literal notranslate"><span class="pre">__builtins__</span></code>; it is strictly an implementation
detail. Users wanting to override values in the builtins namespace should
<a class="reference internal" href="simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> the <a class="reference internal" href="../library/builtins.html#module-builtins" title="builtins: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">builtins</span></code></a> module and modify its
attributes appropriately.</p>
</div>
<p>The builtins namespace associated with the execution of a code block
is actually found by looking up the name <code class="docutils literal notranslate"><span class="pre">__builtins__</span></code> in its
global namespace; this should be a dictionary or a module (in the
latter case the modules dictionary is used). By default, when in the
<a class="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> module, <code class="docutils literal notranslate"><span class="pre">__builtins__</span></code> is the built-in module
<a class="reference internal" href="../library/builtins.html#module-builtins" title="builtins: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">builtins</span></code></a>; when in any other module, <code class="docutils literal notranslate"><span class="pre">__builtins__</span></code> is an
alias for the dictionary of the <a class="reference internal" href="../library/builtins.html#module-builtins" title="builtins: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">builtins</span></code></a> module itself.</p>
</div>
<div class="section" id="interaction-with-dynamic-features">
<span id="dynamic-features"></span><h3>4.2.4. Interaction with dynamic features<a class="headerlink" href="#interaction-with-dynamic-features" title="Permalink to this headline"></a></h3>
<p>Name resolution of free variables occurs at runtime, not at compile time.
This means that the following code will print 42:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">i</span> <span class="o">=</span> <span class="mi">10</span>
<span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
<span class="nb">print</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
<span class="n">i</span> <span class="o">=</span> <span class="mi">42</span>
<span class="n">f</span><span class="p">()</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> and <a class="reference internal" href="../library/functions.html#exec" title="exec"><code class="xref py py-func docutils literal notranslate"><span class="pre">exec()</span></code></a> functions do not have access to the full
environment for resolving names. Names may be resolved in the local and global
namespaces of the caller. Free variables are not resolved in the nearest
enclosing namespace, but in the global namespace. <a class="footnote-reference brackets" href="#id3" id="id1">1</a> The <a class="reference internal" href="../library/functions.html#exec" title="exec"><code class="xref py py-func docutils literal notranslate"><span class="pre">exec()</span></code></a> and
<a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> functions have optional arguments to override the global and local
namespace. If only one namespace is specified, it is used for both.</p>
</div>
</div>
<div class="section" id="exceptions">
<span id="id2"></span><h2>4.3. Exceptions<a class="headerlink" href="#exceptions" title="Permalink to this headline"></a></h2>
<span class="target" id="index-12"></span><p id="index-13">Exceptions are a means of breaking out of the normal flow of control of a code
block in order to handle errors or other exceptional conditions. An exception
is <em>raised</em> at the point where the error is detected; it may be <em>handled</em> by the
surrounding code block or by any code block that directly or indirectly invoked
the code block where the error occurred.</p>
<p>The Python interpreter raises an exception when it detects a run-time error
(such as division by zero). A Python program can also explicitly raise an
exception with the <a class="reference internal" href="simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> statement. Exception handlers are specified
with the <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a><a class="reference internal" href="compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> statement. The <a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a>
clause of such a statement can be used to specify cleanup code which does not
handle the exception, but is executed whether an exception occurred or not in
the preceding code.</p>
<p id="index-14">Python uses the “termination” model of error handling: an exception handler can
find out what happened and continue execution at an outer level, but it cannot
repair the cause of the error and retry the failing operation (except by
re-entering the offending piece of code from the top).</p>
<p id="index-15">When an exception is not handled at all, the interpreter terminates execution of
the program, or returns to its interactive main loop. In either case, it prints
a stack traceback, except when the exception is <a class="reference internal" href="../library/exceptions.html#SystemExit" title="SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a>.</p>
<p>Exceptions are identified by class instances. The <a class="reference internal" href="compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> clause is
selected depending on the class of the instance: it must reference the class of
the instance or a base class thereof. The instance can be received by the
handler and can carry additional information about the exceptional condition.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>Exception messages are not part of the Python API. Their contents may change
from one version of Python to the next without warning and should not be
relied on by code which will run under multiple versions of the interpreter.</p>
</div>
<p>See also the description of the <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement in section <a class="reference internal" href="compound_stmts.html#try"><span class="std std-ref">The try statement</span></a>
and <a class="reference internal" href="simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> statement in section <a class="reference internal" href="simple_stmts.html#raise"><span class="std std-ref">The raise statement</span></a>.</p>
<p class="rubric">Footnotes</p>
<dl class="footnote brackets">
<dt class="label" id="id3"><span class="brackets"><a class="fn-backref" href="#id1">1</a></span></dt>
<dd><p>This limitation occurs because the code that is executed by these operations
is not available at the time the module is compiled.</p>
</dd>
</dl>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="../contents.html">Table of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">4. Execution model</a><ul>
<li><a class="reference internal" href="#structure-of-a-program">4.1. Structure of a program</a></li>
<li><a class="reference internal" href="#naming-and-binding">4.2. Naming and binding</a><ul>
<li><a class="reference internal" href="#binding-of-names">4.2.1. Binding of names</a></li>
<li><a class="reference internal" href="#resolution-of-names">4.2.2. Resolution of names</a></li>
<li><a class="reference internal" href="#builtins-and-restricted-execution">4.2.3. Builtins and restricted execution</a></li>
<li><a class="reference internal" href="#interaction-with-dynamic-features">4.2.4. Interaction with dynamic features</a></li>
</ul>
</li>
<li><a class="reference internal" href="#exceptions">4.3. Exceptions</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="datamodel.html"
title="previous chapter">3. Data model</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="import.html"
title="next chapter">5. The import system</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/reference/executionmodel.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="import.html" title="5. The import system"
>next</a> |</li>
<li class="right" >
<a href="datamodel.html" title="3. Data model"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,335 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>10. Full Grammar specification &#8212; Python 3.7.4 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" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="The Python Standard Library" href="../library/index.html" />
<link rel="prev" title="9. Top-level components" href="toplevel_components.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/reference/grammar.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="../library/index.html" title="The Python Standard Library"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="toplevel_components.html" title="9. Top-level components"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="full-grammar-specification">
<h1>10. Full Grammar specification<a class="headerlink" href="#full-grammar-specification" title="Permalink to this headline"></a></h1>
<p>This is the full Python grammar, as it is read by the parser generator and used
to parse Python source files:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Grammar for Python</span>
<span class="c1"># NOTE WELL: You should also follow all the steps listed at</span>
<span class="c1"># https://devguide.python.org/grammar/</span>
<span class="c1"># Start symbols for the grammar:</span>
<span class="c1"># single_input is a single interactive statement;</span>
<span class="c1"># file_input is a module or sequence of commands read from an input file;</span>
<span class="c1"># eval_input is the input for the eval() functions.</span>
<span class="c1"># NB: compound_stmt in single_input is followed by extra NEWLINE!</span>
<span class="n">single_input</span><span class="p">:</span> <span class="n">NEWLINE</span> <span class="o">|</span> <span class="n">simple_stmt</span> <span class="o">|</span> <span class="n">compound_stmt</span> <span class="n">NEWLINE</span>
<span class="n">file_input</span><span class="p">:</span> <span class="p">(</span><span class="n">NEWLINE</span> <span class="o">|</span> <span class="n">stmt</span><span class="p">)</span><span class="o">*</span> <span class="n">ENDMARKER</span>
<span class="n">eval_input</span><span class="p">:</span> <span class="n">testlist</span> <span class="n">NEWLINE</span><span class="o">*</span> <span class="n">ENDMARKER</span>
<span class="n">decorator</span><span class="p">:</span> <span class="s1">&#39;@&#39;</span> <span class="n">dotted_name</span> <span class="p">[</span> <span class="s1">&#39;(&#39;</span> <span class="p">[</span><span class="n">arglist</span><span class="p">]</span> <span class="s1">&#39;)&#39;</span> <span class="p">]</span> <span class="n">NEWLINE</span>
<span class="n">decorators</span><span class="p">:</span> <span class="n">decorator</span><span class="o">+</span>
<span class="n">decorated</span><span class="p">:</span> <span class="n">decorators</span> <span class="p">(</span><span class="n">classdef</span> <span class="o">|</span> <span class="n">funcdef</span> <span class="o">|</span> <span class="n">async_funcdef</span><span class="p">)</span>
<span class="n">async_funcdef</span><span class="p">:</span> <span class="s1">&#39;async&#39;</span> <span class="n">funcdef</span>
<span class="n">funcdef</span><span class="p">:</span> <span class="s1">&#39;def&#39;</span> <span class="n">NAME</span> <span class="n">parameters</span> <span class="p">[</span><span class="s1">&#39;-&gt;&#39;</span> <span class="n">test</span><span class="p">]</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span>
<span class="n">parameters</span><span class="p">:</span> <span class="s1">&#39;(&#39;</span> <span class="p">[</span><span class="n">typedargslist</span><span class="p">]</span> <span class="s1">&#39;)&#39;</span>
<span class="n">typedargslist</span><span class="p">:</span> <span class="p">(</span><span class="n">tfpdef</span> <span class="p">[</span><span class="s1">&#39;=&#39;</span> <span class="n">test</span><span class="p">]</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">tfpdef</span> <span class="p">[</span><span class="s1">&#39;=&#39;</span> <span class="n">test</span><span class="p">])</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span> <span class="p">[</span>
<span class="s1">&#39;*&#39;</span> <span class="p">[</span><span class="n">tfpdef</span><span class="p">]</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">tfpdef</span> <span class="p">[</span><span class="s1">&#39;=&#39;</span> <span class="n">test</span><span class="p">])</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span> <span class="p">[</span><span class="s1">&#39;**&#39;</span> <span class="n">tfpdef</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]]]</span>
<span class="o">|</span> <span class="s1">&#39;**&#39;</span> <span class="n">tfpdef</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]]]</span>
<span class="o">|</span> <span class="s1">&#39;*&#39;</span> <span class="p">[</span><span class="n">tfpdef</span><span class="p">]</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">tfpdef</span> <span class="p">[</span><span class="s1">&#39;=&#39;</span> <span class="n">test</span><span class="p">])</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span> <span class="p">[</span><span class="s1">&#39;**&#39;</span> <span class="n">tfpdef</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]]]</span>
<span class="o">|</span> <span class="s1">&#39;**&#39;</span> <span class="n">tfpdef</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">])</span>
<span class="n">tfpdef</span><span class="p">:</span> <span class="n">NAME</span> <span class="p">[</span><span class="s1">&#39;:&#39;</span> <span class="n">test</span><span class="p">]</span>
<span class="n">varargslist</span><span class="p">:</span> <span class="p">(</span><span class="n">vfpdef</span> <span class="p">[</span><span class="s1">&#39;=&#39;</span> <span class="n">test</span><span class="p">]</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">vfpdef</span> <span class="p">[</span><span class="s1">&#39;=&#39;</span> <span class="n">test</span><span class="p">])</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span> <span class="p">[</span>
<span class="s1">&#39;*&#39;</span> <span class="p">[</span><span class="n">vfpdef</span><span class="p">]</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">vfpdef</span> <span class="p">[</span><span class="s1">&#39;=&#39;</span> <span class="n">test</span><span class="p">])</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span> <span class="p">[</span><span class="s1">&#39;**&#39;</span> <span class="n">vfpdef</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]]]</span>
<span class="o">|</span> <span class="s1">&#39;**&#39;</span> <span class="n">vfpdef</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]]]</span>
<span class="o">|</span> <span class="s1">&#39;*&#39;</span> <span class="p">[</span><span class="n">vfpdef</span><span class="p">]</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">vfpdef</span> <span class="p">[</span><span class="s1">&#39;=&#39;</span> <span class="n">test</span><span class="p">])</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span> <span class="p">[</span><span class="s1">&#39;**&#39;</span> <span class="n">vfpdef</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]]]</span>
<span class="o">|</span> <span class="s1">&#39;**&#39;</span> <span class="n">vfpdef</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]</span>
<span class="p">)</span>
<span class="n">vfpdef</span><span class="p">:</span> <span class="n">NAME</span>
<span class="n">stmt</span><span class="p">:</span> <span class="n">simple_stmt</span> <span class="o">|</span> <span class="n">compound_stmt</span>
<span class="n">simple_stmt</span><span class="p">:</span> <span class="n">small_stmt</span> <span class="p">(</span><span class="s1">&#39;;&#39;</span> <span class="n">small_stmt</span><span class="p">)</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;;&#39;</span><span class="p">]</span> <span class="n">NEWLINE</span>
<span class="n">small_stmt</span><span class="p">:</span> <span class="p">(</span><span class="n">expr_stmt</span> <span class="o">|</span> <span class="n">del_stmt</span> <span class="o">|</span> <span class="n">pass_stmt</span> <span class="o">|</span> <span class="n">flow_stmt</span> <span class="o">|</span>
<span class="n">import_stmt</span> <span class="o">|</span> <span class="n">global_stmt</span> <span class="o">|</span> <span class="n">nonlocal_stmt</span> <span class="o">|</span> <span class="n">assert_stmt</span><span class="p">)</span>
<span class="n">expr_stmt</span><span class="p">:</span> <span class="n">testlist_star_expr</span> <span class="p">(</span><span class="n">annassign</span> <span class="o">|</span> <span class="n">augassign</span> <span class="p">(</span><span class="n">yield_expr</span><span class="o">|</span><span class="n">testlist</span><span class="p">)</span> <span class="o">|</span>
<span class="p">(</span><span class="s1">&#39;=&#39;</span> <span class="p">(</span><span class="n">yield_expr</span><span class="o">|</span><span class="n">testlist_star_expr</span><span class="p">))</span><span class="o">*</span><span class="p">)</span>
<span class="n">annassign</span><span class="p">:</span> <span class="s1">&#39;:&#39;</span> <span class="n">test</span> <span class="p">[</span><span class="s1">&#39;=&#39;</span> <span class="n">test</span><span class="p">]</span>
<span class="n">testlist_star_expr</span><span class="p">:</span> <span class="p">(</span><span class="n">test</span><span class="o">|</span><span class="n">star_expr</span><span class="p">)</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="p">(</span><span class="n">test</span><span class="o">|</span><span class="n">star_expr</span><span class="p">))</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]</span>
<span class="n">augassign</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;+=&#39;</span> <span class="o">|</span> <span class="s1">&#39;-=&#39;</span> <span class="o">|</span> <span class="s1">&#39;*=&#39;</span> <span class="o">|</span> <span class="s1">&#39;@=&#39;</span> <span class="o">|</span> <span class="s1">&#39;/=&#39;</span> <span class="o">|</span> <span class="s1">&#39;%=&#39;</span> <span class="o">|</span> <span class="s1">&#39;&amp;=&#39;</span> <span class="o">|</span> <span class="s1">&#39;|=&#39;</span> <span class="o">|</span> <span class="s1">&#39;^=&#39;</span> <span class="o">|</span>
<span class="s1">&#39;&lt;&lt;=&#39;</span> <span class="o">|</span> <span class="s1">&#39;&gt;&gt;=&#39;</span> <span class="o">|</span> <span class="s1">&#39;**=&#39;</span> <span class="o">|</span> <span class="s1">&#39;//=&#39;</span><span class="p">)</span>
<span class="c1"># For normal and annotated assignments, additional restrictions enforced by the interpreter</span>
<span class="n">del_stmt</span><span class="p">:</span> <span class="s1">&#39;del&#39;</span> <span class="n">exprlist</span>
<span class="n">pass_stmt</span><span class="p">:</span> <span class="s1">&#39;pass&#39;</span>
<span class="n">flow_stmt</span><span class="p">:</span> <span class="n">break_stmt</span> <span class="o">|</span> <span class="n">continue_stmt</span> <span class="o">|</span> <span class="n">return_stmt</span> <span class="o">|</span> <span class="n">raise_stmt</span> <span class="o">|</span> <span class="n">yield_stmt</span>
<span class="n">break_stmt</span><span class="p">:</span> <span class="s1">&#39;break&#39;</span>
<span class="n">continue_stmt</span><span class="p">:</span> <span class="s1">&#39;continue&#39;</span>
<span class="n">return_stmt</span><span class="p">:</span> <span class="s1">&#39;return&#39;</span> <span class="p">[</span><span class="n">testlist</span><span class="p">]</span>
<span class="n">yield_stmt</span><span class="p">:</span> <span class="n">yield_expr</span>
<span class="n">raise_stmt</span><span class="p">:</span> <span class="s1">&#39;raise&#39;</span> <span class="p">[</span><span class="n">test</span> <span class="p">[</span><span class="s1">&#39;from&#39;</span> <span class="n">test</span><span class="p">]]</span>
<span class="n">import_stmt</span><span class="p">:</span> <span class="n">import_name</span> <span class="o">|</span> <span class="n">import_from</span>
<span class="n">import_name</span><span class="p">:</span> <span class="s1">&#39;import&#39;</span> <span class="n">dotted_as_names</span>
<span class="c1"># note below: the (&#39;.&#39; | &#39;...&#39;) is necessary because &#39;...&#39; is tokenized as ELLIPSIS</span>
<span class="n">import_from</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;from&#39;</span> <span class="p">((</span><span class="s1">&#39;.&#39;</span> <span class="o">|</span> <span class="s1">&#39;...&#39;</span><span class="p">)</span><span class="o">*</span> <span class="n">dotted_name</span> <span class="o">|</span> <span class="p">(</span><span class="s1">&#39;.&#39;</span> <span class="o">|</span> <span class="s1">&#39;...&#39;</span><span class="p">)</span><span class="o">+</span><span class="p">)</span>
<span class="s1">&#39;import&#39;</span> <span class="p">(</span><span class="s1">&#39;*&#39;</span> <span class="o">|</span> <span class="s1">&#39;(&#39;</span> <span class="n">import_as_names</span> <span class="s1">&#39;)&#39;</span> <span class="o">|</span> <span class="n">import_as_names</span><span class="p">))</span>
<span class="n">import_as_name</span><span class="p">:</span> <span class="n">NAME</span> <span class="p">[</span><span class="s1">&#39;as&#39;</span> <span class="n">NAME</span><span class="p">]</span>
<span class="n">dotted_as_name</span><span class="p">:</span> <span class="n">dotted_name</span> <span class="p">[</span><span class="s1">&#39;as&#39;</span> <span class="n">NAME</span><span class="p">]</span>
<span class="n">import_as_names</span><span class="p">:</span> <span class="n">import_as_name</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">import_as_name</span><span class="p">)</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]</span>
<span class="n">dotted_as_names</span><span class="p">:</span> <span class="n">dotted_as_name</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">dotted_as_name</span><span class="p">)</span><span class="o">*</span>
<span class="n">dotted_name</span><span class="p">:</span> <span class="n">NAME</span> <span class="p">(</span><span class="s1">&#39;.&#39;</span> <span class="n">NAME</span><span class="p">)</span><span class="o">*</span>
<span class="n">global_stmt</span><span class="p">:</span> <span class="s1">&#39;global&#39;</span> <span class="n">NAME</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">NAME</span><span class="p">)</span><span class="o">*</span>
<span class="n">nonlocal_stmt</span><span class="p">:</span> <span class="s1">&#39;nonlocal&#39;</span> <span class="n">NAME</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">NAME</span><span class="p">)</span><span class="o">*</span>
<span class="n">assert_stmt</span><span class="p">:</span> <span class="s1">&#39;assert&#39;</span> <span class="n">test</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span> <span class="n">test</span><span class="p">]</span>
<span class="n">compound_stmt</span><span class="p">:</span> <span class="n">if_stmt</span> <span class="o">|</span> <span class="n">while_stmt</span> <span class="o">|</span> <span class="n">for_stmt</span> <span class="o">|</span> <span class="n">try_stmt</span> <span class="o">|</span> <span class="n">with_stmt</span> <span class="o">|</span> <span class="n">funcdef</span> <span class="o">|</span> <span class="n">classdef</span> <span class="o">|</span> <span class="n">decorated</span> <span class="o">|</span> <span class="n">async_stmt</span>
<span class="n">async_stmt</span><span class="p">:</span> <span class="s1">&#39;async&#39;</span> <span class="p">(</span><span class="n">funcdef</span> <span class="o">|</span> <span class="n">with_stmt</span> <span class="o">|</span> <span class="n">for_stmt</span><span class="p">)</span>
<span class="n">if_stmt</span><span class="p">:</span> <span class="s1">&#39;if&#39;</span> <span class="n">test</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span> <span class="p">(</span><span class="s1">&#39;elif&#39;</span> <span class="n">test</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span><span class="p">)</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;else&#39;</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span><span class="p">]</span>
<span class="n">while_stmt</span><span class="p">:</span> <span class="s1">&#39;while&#39;</span> <span class="n">test</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span> <span class="p">[</span><span class="s1">&#39;else&#39;</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span><span class="p">]</span>
<span class="n">for_stmt</span><span class="p">:</span> <span class="s1">&#39;for&#39;</span> <span class="n">exprlist</span> <span class="s1">&#39;in&#39;</span> <span class="n">testlist</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span> <span class="p">[</span><span class="s1">&#39;else&#39;</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span><span class="p">]</span>
<span class="n">try_stmt</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;try&#39;</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span>
<span class="p">((</span><span class="n">except_clause</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span><span class="p">)</span><span class="o">+</span>
<span class="p">[</span><span class="s1">&#39;else&#39;</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span><span class="p">]</span>
<span class="p">[</span><span class="s1">&#39;finally&#39;</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span><span class="p">]</span> <span class="o">|</span>
<span class="s1">&#39;finally&#39;</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span><span class="p">))</span>
<span class="n">with_stmt</span><span class="p">:</span> <span class="s1">&#39;with&#39;</span> <span class="n">with_item</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">with_item</span><span class="p">)</span><span class="o">*</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span>
<span class="n">with_item</span><span class="p">:</span> <span class="n">test</span> <span class="p">[</span><span class="s1">&#39;as&#39;</span> <span class="n">expr</span><span class="p">]</span>
<span class="c1"># NB compile.c makes sure that the default except clause is last</span>
<span class="n">except_clause</span><span class="p">:</span> <span class="s1">&#39;except&#39;</span> <span class="p">[</span><span class="n">test</span> <span class="p">[</span><span class="s1">&#39;as&#39;</span> <span class="n">NAME</span><span class="p">]]</span>
<span class="n">suite</span><span class="p">:</span> <span class="n">simple_stmt</span> <span class="o">|</span> <span class="n">NEWLINE</span> <span class="n">INDENT</span> <span class="n">stmt</span><span class="o">+</span> <span class="n">DEDENT</span>
<span class="n">test</span><span class="p">:</span> <span class="n">or_test</span> <span class="p">[</span><span class="s1">&#39;if&#39;</span> <span class="n">or_test</span> <span class="s1">&#39;else&#39;</span> <span class="n">test</span><span class="p">]</span> <span class="o">|</span> <span class="n">lambdef</span>
<span class="n">test_nocond</span><span class="p">:</span> <span class="n">or_test</span> <span class="o">|</span> <span class="n">lambdef_nocond</span>
<span class="n">lambdef</span><span class="p">:</span> <span class="s1">&#39;lambda&#39;</span> <span class="p">[</span><span class="n">varargslist</span><span class="p">]</span> <span class="s1">&#39;:&#39;</span> <span class="n">test</span>
<span class="n">lambdef_nocond</span><span class="p">:</span> <span class="s1">&#39;lambda&#39;</span> <span class="p">[</span><span class="n">varargslist</span><span class="p">]</span> <span class="s1">&#39;:&#39;</span> <span class="n">test_nocond</span>
<span class="n">or_test</span><span class="p">:</span> <span class="n">and_test</span> <span class="p">(</span><span class="s1">&#39;or&#39;</span> <span class="n">and_test</span><span class="p">)</span><span class="o">*</span>
<span class="n">and_test</span><span class="p">:</span> <span class="n">not_test</span> <span class="p">(</span><span class="s1">&#39;and&#39;</span> <span class="n">not_test</span><span class="p">)</span><span class="o">*</span>
<span class="n">not_test</span><span class="p">:</span> <span class="s1">&#39;not&#39;</span> <span class="n">not_test</span> <span class="o">|</span> <span class="n">comparison</span>
<span class="n">comparison</span><span class="p">:</span> <span class="n">expr</span> <span class="p">(</span><span class="n">comp_op</span> <span class="n">expr</span><span class="p">)</span><span class="o">*</span>
<span class="c1"># &lt;&gt; isn&#39;t actually a valid comparison operator in Python. It&#39;s here for the</span>
<span class="c1"># sake of a __future__ import described in PEP 401 (which really works :-)</span>
<span class="n">comp_op</span><span class="p">:</span> <span class="s1">&#39;&lt;&#39;</span><span class="o">|</span><span class="s1">&#39;&gt;&#39;</span><span class="o">|</span><span class="s1">&#39;==&#39;</span><span class="o">|</span><span class="s1">&#39;&gt;=&#39;</span><span class="o">|</span><span class="s1">&#39;&lt;=&#39;</span><span class="o">|</span><span class="s1">&#39;&lt;&gt;&#39;</span><span class="o">|</span><span class="s1">&#39;!=&#39;</span><span class="o">|</span><span class="s1">&#39;in&#39;</span><span class="o">|</span><span class="s1">&#39;not&#39;</span> <span class="s1">&#39;in&#39;</span><span class="o">|</span><span class="s1">&#39;is&#39;</span><span class="o">|</span><span class="s1">&#39;is&#39;</span> <span class="s1">&#39;not&#39;</span>
<span class="n">star_expr</span><span class="p">:</span> <span class="s1">&#39;*&#39;</span> <span class="n">expr</span>
<span class="n">expr</span><span class="p">:</span> <span class="n">xor_expr</span> <span class="p">(</span><span class="s1">&#39;|&#39;</span> <span class="n">xor_expr</span><span class="p">)</span><span class="o">*</span>
<span class="n">xor_expr</span><span class="p">:</span> <span class="n">and_expr</span> <span class="p">(</span><span class="s1">&#39;^&#39;</span> <span class="n">and_expr</span><span class="p">)</span><span class="o">*</span>
<span class="n">and_expr</span><span class="p">:</span> <span class="n">shift_expr</span> <span class="p">(</span><span class="s1">&#39;&amp;&#39;</span> <span class="n">shift_expr</span><span class="p">)</span><span class="o">*</span>
<span class="n">shift_expr</span><span class="p">:</span> <span class="n">arith_expr</span> <span class="p">((</span><span class="s1">&#39;&lt;&lt;&#39;</span><span class="o">|</span><span class="s1">&#39;&gt;&gt;&#39;</span><span class="p">)</span> <span class="n">arith_expr</span><span class="p">)</span><span class="o">*</span>
<span class="n">arith_expr</span><span class="p">:</span> <span class="n">term</span> <span class="p">((</span><span class="s1">&#39;+&#39;</span><span class="o">|</span><span class="s1">&#39;-&#39;</span><span class="p">)</span> <span class="n">term</span><span class="p">)</span><span class="o">*</span>
<span class="n">term</span><span class="p">:</span> <span class="n">factor</span> <span class="p">((</span><span class="s1">&#39;*&#39;</span><span class="o">|</span><span class="s1">&#39;@&#39;</span><span class="o">|</span><span class="s1">&#39;/&#39;</span><span class="o">|</span><span class="s1">&#39;%&#39;</span><span class="o">|</span><span class="s1">&#39;//&#39;</span><span class="p">)</span> <span class="n">factor</span><span class="p">)</span><span class="o">*</span>
<span class="n">factor</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;+&#39;</span><span class="o">|</span><span class="s1">&#39;-&#39;</span><span class="o">|</span><span class="s1">&#39;~&#39;</span><span class="p">)</span> <span class="n">factor</span> <span class="o">|</span> <span class="n">power</span>
<span class="n">power</span><span class="p">:</span> <span class="n">atom_expr</span> <span class="p">[</span><span class="s1">&#39;**&#39;</span> <span class="n">factor</span><span class="p">]</span>
<span class="n">atom_expr</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;await&#39;</span><span class="p">]</span> <span class="n">atom</span> <span class="n">trailer</span><span class="o">*</span>
<span class="n">atom</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;(&#39;</span> <span class="p">[</span><span class="n">yield_expr</span><span class="o">|</span><span class="n">testlist_comp</span><span class="p">]</span> <span class="s1">&#39;)&#39;</span> <span class="o">|</span>
<span class="s1">&#39;[&#39;</span> <span class="p">[</span><span class="n">testlist_comp</span><span class="p">]</span> <span class="s1">&#39;]&#39;</span> <span class="o">|</span>
<span class="s1">&#39;{&#39;</span> <span class="p">[</span><span class="n">dictorsetmaker</span><span class="p">]</span> <span class="s1">&#39;}&#39;</span> <span class="o">|</span>
<span class="n">NAME</span> <span class="o">|</span> <span class="n">NUMBER</span> <span class="o">|</span> <span class="n">STRING</span><span class="o">+</span> <span class="o">|</span> <span class="s1">&#39;...&#39;</span> <span class="o">|</span> <span class="s1">&#39;None&#39;</span> <span class="o">|</span> <span class="s1">&#39;True&#39;</span> <span class="o">|</span> <span class="s1">&#39;False&#39;</span><span class="p">)</span>
<span class="n">testlist_comp</span><span class="p">:</span> <span class="p">(</span><span class="n">test</span><span class="o">|</span><span class="n">star_expr</span><span class="p">)</span> <span class="p">(</span> <span class="n">comp_for</span> <span class="o">|</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="p">(</span><span class="n">test</span><span class="o">|</span><span class="n">star_expr</span><span class="p">))</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]</span> <span class="p">)</span>
<span class="n">trailer</span><span class="p">:</span> <span class="s1">&#39;(&#39;</span> <span class="p">[</span><span class="n">arglist</span><span class="p">]</span> <span class="s1">&#39;)&#39;</span> <span class="o">|</span> <span class="s1">&#39;[&#39;</span> <span class="n">subscriptlist</span> <span class="s1">&#39;]&#39;</span> <span class="o">|</span> <span class="s1">&#39;.&#39;</span> <span class="n">NAME</span>
<span class="n">subscriptlist</span><span class="p">:</span> <span class="n">subscript</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">subscript</span><span class="p">)</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]</span>
<span class="n">subscript</span><span class="p">:</span> <span class="n">test</span> <span class="o">|</span> <span class="p">[</span><span class="n">test</span><span class="p">]</span> <span class="s1">&#39;:&#39;</span> <span class="p">[</span><span class="n">test</span><span class="p">]</span> <span class="p">[</span><span class="n">sliceop</span><span class="p">]</span>
<span class="n">sliceop</span><span class="p">:</span> <span class="s1">&#39;:&#39;</span> <span class="p">[</span><span class="n">test</span><span class="p">]</span>
<span class="n">exprlist</span><span class="p">:</span> <span class="p">(</span><span class="n">expr</span><span class="o">|</span><span class="n">star_expr</span><span class="p">)</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="p">(</span><span class="n">expr</span><span class="o">|</span><span class="n">star_expr</span><span class="p">))</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]</span>
<span class="n">testlist</span><span class="p">:</span> <span class="n">test</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">test</span><span class="p">)</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]</span>
<span class="n">dictorsetmaker</span><span class="p">:</span> <span class="p">(</span> <span class="p">((</span><span class="n">test</span> <span class="s1">&#39;:&#39;</span> <span class="n">test</span> <span class="o">|</span> <span class="s1">&#39;**&#39;</span> <span class="n">expr</span><span class="p">)</span>
<span class="p">(</span><span class="n">comp_for</span> <span class="o">|</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="p">(</span><span class="n">test</span> <span class="s1">&#39;:&#39;</span> <span class="n">test</span> <span class="o">|</span> <span class="s1">&#39;**&#39;</span> <span class="n">expr</span><span class="p">))</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]))</span> <span class="o">|</span>
<span class="p">((</span><span class="n">test</span> <span class="o">|</span> <span class="n">star_expr</span><span class="p">)</span>
<span class="p">(</span><span class="n">comp_for</span> <span class="o">|</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="p">(</span><span class="n">test</span> <span class="o">|</span> <span class="n">star_expr</span><span class="p">))</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]))</span> <span class="p">)</span>
<span class="n">classdef</span><span class="p">:</span> <span class="s1">&#39;class&#39;</span> <span class="n">NAME</span> <span class="p">[</span><span class="s1">&#39;(&#39;</span> <span class="p">[</span><span class="n">arglist</span><span class="p">]</span> <span class="s1">&#39;)&#39;</span><span class="p">]</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span>
<span class="n">arglist</span><span class="p">:</span> <span class="n">argument</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">argument</span><span class="p">)</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]</span>
<span class="c1"># The reason that keywords are test nodes instead of NAME is that using NAME</span>
<span class="c1"># results in an ambiguity. ast.c makes sure it&#39;s a NAME.</span>
<span class="c1"># &quot;test &#39;=&#39; test&quot; is really &quot;keyword &#39;=&#39; test&quot;, but we have no such token.</span>
<span class="c1"># These need to be in a single rule to avoid grammar that is ambiguous</span>
<span class="c1"># to our LL(1) parser. Even though &#39;test&#39; includes &#39;*expr&#39; in star_expr,</span>
<span class="c1"># we explicitly match &#39;*&#39; here, too, to give it proper precedence.</span>
<span class="c1"># Illegal combinations and orderings are blocked in ast.c:</span>
<span class="c1"># multiple (test comp_for) arguments are blocked; keyword unpackings</span>
<span class="c1"># that precede iterable unpackings are blocked; etc.</span>
<span class="n">argument</span><span class="p">:</span> <span class="p">(</span> <span class="n">test</span> <span class="p">[</span><span class="n">comp_for</span><span class="p">]</span> <span class="o">|</span>
<span class="n">test</span> <span class="s1">&#39;=&#39;</span> <span class="n">test</span> <span class="o">|</span>
<span class="s1">&#39;**&#39;</span> <span class="n">test</span> <span class="o">|</span>
<span class="s1">&#39;*&#39;</span> <span class="n">test</span> <span class="p">)</span>
<span class="n">comp_iter</span><span class="p">:</span> <span class="n">comp_for</span> <span class="o">|</span> <span class="n">comp_if</span>
<span class="n">sync_comp_for</span><span class="p">:</span> <span class="s1">&#39;for&#39;</span> <span class="n">exprlist</span> <span class="s1">&#39;in&#39;</span> <span class="n">or_test</span> <span class="p">[</span><span class="n">comp_iter</span><span class="p">]</span>
<span class="n">comp_for</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;async&#39;</span><span class="p">]</span> <span class="n">sync_comp_for</span>
<span class="n">comp_if</span><span class="p">:</span> <span class="s1">&#39;if&#39;</span> <span class="n">test_nocond</span> <span class="p">[</span><span class="n">comp_iter</span><span class="p">]</span>
<span class="c1"># not used in grammar, but may appear in &quot;node&quot; passed from Parser to Compiler</span>
<span class="n">encoding_decl</span><span class="p">:</span> <span class="n">NAME</span>
<span class="n">yield_expr</span><span class="p">:</span> <span class="s1">&#39;yield&#39;</span> <span class="p">[</span><span class="n">yield_arg</span><span class="p">]</span>
<span class="n">yield_arg</span><span class="p">:</span> <span class="s1">&#39;from&#39;</span> <span class="n">test</span> <span class="o">|</span> <span class="n">testlist</span>
</pre></div>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h4>Previous topic</h4>
<p class="topless"><a href="toplevel_components.html"
title="previous chapter">9. Top-level components</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="../library/index.html"
title="next chapter">The Python Standard Library</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/reference/grammar.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="../library/index.html" title="The Python Standard Library"
>next</a> |</li>
<li class="right" >
<a href="toplevel_components.html" title="9. Top-level components"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,285 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>The Python Language Reference &#8212; Python 3.7.4 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" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="1. Introduction" href="introduction.html" />
<link rel="prev" title="4. Using Python on a Macintosh" href="../using/mac.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/reference/index.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="introduction.html" title="1. Introduction"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="../using/mac.html" title="4. Using Python on a Macintosh"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="the-python-language-reference">
<span id="reference-index"></span><h1>The Python Language Reference<a class="headerlink" href="#the-python-language-reference" title="Permalink to this headline"></a></h1>
<p>This reference manual describes the syntax and “core semantics” of the
language. It is terse, but attempts to be exact and complete. The semantics of
non-essential built-in object types and of the built-in functions and modules
are described in <a class="reference internal" href="../library/index.html#library-index"><span class="std std-ref">The Python Standard Library</span></a>. For an informal introduction to the
language, see <a class="reference internal" href="../tutorial/index.html#tutorial-index"><span class="std std-ref">The Python Tutorial</span></a>. For C or C++ programmers, two additional
manuals exist: <a class="reference internal" href="../extending/index.html#extending-index"><span class="std std-ref">Extending and Embedding the Python Interpreter</span></a> describes the high-level picture of how to
write a Python extension module, and the <a class="reference internal" href="../c-api/index.html#c-api-index"><span class="std std-ref">Python/C API Reference Manual</span></a> describes the
interfaces available to C/C++ programmers in detail.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="introduction.html">1. Introduction</a><ul>
<li class="toctree-l2"><a class="reference internal" href="introduction.html#alternate-implementations">1.1. Alternate Implementations</a></li>
<li class="toctree-l2"><a class="reference internal" href="introduction.html#notation">1.2. Notation</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="lexical_analysis.html">2. Lexical analysis</a><ul>
<li class="toctree-l2"><a class="reference internal" href="lexical_analysis.html#line-structure">2.1. Line structure</a></li>
<li class="toctree-l2"><a class="reference internal" href="lexical_analysis.html#other-tokens">2.2. Other tokens</a></li>
<li class="toctree-l2"><a class="reference internal" href="lexical_analysis.html#identifiers">2.3. Identifiers and keywords</a></li>
<li class="toctree-l2"><a class="reference internal" href="lexical_analysis.html#literals">2.4. Literals</a></li>
<li class="toctree-l2"><a class="reference internal" href="lexical_analysis.html#operators">2.5. Operators</a></li>
<li class="toctree-l2"><a class="reference internal" href="lexical_analysis.html#delimiters">2.6. Delimiters</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="datamodel.html">3. Data model</a><ul>
<li class="toctree-l2"><a class="reference internal" href="datamodel.html#objects-values-and-types">3.1. Objects, values and types</a></li>
<li class="toctree-l2"><a class="reference internal" href="datamodel.html#the-standard-type-hierarchy">3.2. The standard type hierarchy</a></li>
<li class="toctree-l2"><a class="reference internal" href="datamodel.html#special-method-names">3.3. Special method names</a></li>
<li class="toctree-l2"><a class="reference internal" href="datamodel.html#coroutines">3.4. Coroutines</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="executionmodel.html">4. Execution model</a><ul>
<li class="toctree-l2"><a class="reference internal" href="executionmodel.html#structure-of-a-program">4.1. Structure of a program</a></li>
<li class="toctree-l2"><a class="reference internal" href="executionmodel.html#naming-and-binding">4.2. Naming and binding</a></li>
<li class="toctree-l2"><a class="reference internal" href="executionmodel.html#exceptions">4.3. Exceptions</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="import.html">5. The import system</a><ul>
<li class="toctree-l2"><a class="reference internal" href="import.html#importlib">5.1. <code class="xref py py-mod docutils literal notranslate"><span class="pre">importlib</span></code></a></li>
<li class="toctree-l2"><a class="reference internal" href="import.html#packages">5.2. Packages</a></li>
<li class="toctree-l2"><a class="reference internal" href="import.html#searching">5.3. Searching</a></li>
<li class="toctree-l2"><a class="reference internal" href="import.html#loading">5.4. Loading</a></li>
<li class="toctree-l2"><a class="reference internal" href="import.html#the-path-based-finder">5.5. The Path Based Finder</a></li>
<li class="toctree-l2"><a class="reference internal" href="import.html#replacing-the-standard-import-system">5.6. Replacing the standard import system</a></li>
<li class="toctree-l2"><a class="reference internal" href="import.html#package-relative-imports">5.7. Package Relative Imports</a></li>
<li class="toctree-l2"><a class="reference internal" href="import.html#special-considerations-for-main">5.8. Special considerations for __main__</a></li>
<li class="toctree-l2"><a class="reference internal" href="import.html#open-issues">5.9. Open issues</a></li>
<li class="toctree-l2"><a class="reference internal" href="import.html#references">5.10. References</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="expressions.html">6. Expressions</a><ul>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#arithmetic-conversions">6.1. Arithmetic conversions</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#atoms">6.2. Atoms</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#primaries">6.3. Primaries</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#await-expression">6.4. Await expression</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#the-power-operator">6.5. The power operator</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#unary-arithmetic-and-bitwise-operations">6.6. Unary arithmetic and bitwise operations</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#binary-arithmetic-operations">6.7. Binary arithmetic operations</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#shifting-operations">6.8. Shifting operations</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#binary-bitwise-operations">6.9. Binary bitwise operations</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#comparisons">6.10. Comparisons</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#boolean-operations">6.11. Boolean operations</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#conditional-expressions">6.12. Conditional expressions</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#lambda">6.13. Lambdas</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#expression-lists">6.14. Expression lists</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#evaluation-order">6.15. Evaluation order</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#operator-precedence">6.16. Operator precedence</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="simple_stmts.html">7. Simple statements</a><ul>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#expression-statements">7.1. Expression statements</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#assignment-statements">7.2. Assignment statements</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#the-assert-statement">7.3. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">assert</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#the-pass-statement">7.4. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">pass</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#the-del-statement">7.5. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#the-return-statement">7.6. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#the-yield-statement">7.7. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#the-raise-statement">7.8. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#the-break-statement">7.9. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#the-continue-statement">7.10. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#the-import-statement">7.11. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#the-global-statement">7.12. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#the-nonlocal-statement">7.13. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code> statement</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="compound_stmts.html">8. Compound statements</a><ul>
<li class="toctree-l2"><a class="reference internal" href="compound_stmts.html#the-if-statement">8.1. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="compound_stmts.html#the-while-statement">8.2. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="compound_stmts.html#the-for-statement">8.3. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="compound_stmts.html#the-try-statement">8.4. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="compound_stmts.html#the-with-statement">8.5. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="compound_stmts.html#function-definitions">8.6. Function definitions</a></li>
<li class="toctree-l2"><a class="reference internal" href="compound_stmts.html#class-definitions">8.7. Class definitions</a></li>
<li class="toctree-l2"><a class="reference internal" href="compound_stmts.html#coroutines">8.8. Coroutines</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="toplevel_components.html">9. Top-level components</a><ul>
<li class="toctree-l2"><a class="reference internal" href="toplevel_components.html#complete-python-programs">9.1. Complete Python programs</a></li>
<li class="toctree-l2"><a class="reference internal" href="toplevel_components.html#file-input">9.2. File input</a></li>
<li class="toctree-l2"><a class="reference internal" href="toplevel_components.html#interactive-input">9.3. Interactive input</a></li>
<li class="toctree-l2"><a class="reference internal" href="toplevel_components.html#expression-input">9.4. Expression input</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="grammar.html">10. Full Grammar specification</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h4>Previous topic</h4>
<p class="topless"><a href="../using/mac.html"
title="previous chapter">4. Using Python on a Macintosh</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="introduction.html"
title="next chapter">1. Introduction</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/reference/index.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="introduction.html" title="1. Introduction"
>next</a> |</li>
<li class="right" >
<a href="../using/mac.html" title="4. Using Python on a Macintosh"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>

View File

@@ -0,0 +1,289 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>1. Introduction &#8212; Python 3.7.4 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" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="2. Lexical analysis" href="lexical_analysis.html" />
<link rel="prev" title="The Python Language Reference" href="index.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/reference/introduction.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="lexical_analysis.html" title="2. Lexical analysis"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="index.html" title="The Python Language Reference"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="introduction">
<span id="id1"></span><h1>1. Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline"></a></h1>
<p>This reference manual describes the Python programming language. It is not
intended as a tutorial.</p>
<p>While I am trying to be as precise as possible, I chose to use English rather
than formal specifications for everything except syntax and lexical analysis.
This should make the document more understandable to the average reader, but
will leave room for ambiguities. Consequently, if you were coming from Mars and
tried to re-implement Python from this document alone, you might have to guess
things and in fact you would probably end up implementing quite a different
language. On the other hand, if you are using Python and wonder what the precise
rules about a particular area of the language are, you should definitely be able
to find them here. If you would like to see a more formal definition of the
language, maybe you could volunteer your time — or invent a cloning machine
:-).</p>
<p>It is dangerous to add too many implementation details to a language reference
document — the implementation may change, and other implementations of the
same language may work differently. On the other hand, CPython is the one
Python implementation in widespread use (although alternate implementations
continue to gain support), and its particular quirks are sometimes worth being
mentioned, especially where the implementation imposes additional limitations.
Therefore, youll find short “implementation notes” sprinkled throughout the
text.</p>
<p>Every Python implementation comes with a number of built-in and standard
modules. These are documented in <a class="reference internal" href="../library/index.html#library-index"><span class="std std-ref">The Python Standard Library</span></a>. A few built-in modules
are mentioned when they interact in a significant way with the language
definition.</p>
<div class="section" id="alternate-implementations">
<span id="implementations"></span><h2>1.1. Alternate Implementations<a class="headerlink" href="#alternate-implementations" title="Permalink to this headline"></a></h2>
<p>Though there is one Python implementation which is by far the most popular,
there are some alternate implementations which are of particular interest to
different audiences.</p>
<p>Known implementations include:</p>
<dl class="simple">
<dt>CPython</dt><dd><p>This is the original and most-maintained implementation of Python, written in C.
New language features generally appear here first.</p>
</dd>
<dt>Jython</dt><dd><p>Python implemented in Java. This implementation can be used as a scripting
language for Java applications, or can be used to create applications using the
Java class libraries. It is also often used to create tests for Java libraries.
More information can be found at <a class="reference external" href="http://www.jython.org/">the Jython website</a>.</p>
</dd>
<dt>Python for .NET</dt><dd><p>This implementation actually uses the CPython implementation, but is a managed
.NET application and makes .NET libraries available. It was created by Brian
Lloyd. For more information, see the <a class="reference external" href="https://pythonnet.github.io/">Python for .NET home page</a>.</p>
</dd>
<dt>IronPython</dt><dd><p>An alternate Python for .NET. Unlike Python.NET, this is a complete Python
implementation that generates IL, and compiles Python code directly to .NET
assemblies. It was created by Jim Hugunin, the original creator of Jython. For
more information, see <a class="reference external" href="http://ironpython.net/">the IronPython website</a>.</p>
</dd>
<dt>PyPy</dt><dd><p>An implementation of Python written completely in Python. It supports several
advanced features not found in other implementations like stackless support
and a Just in Time compiler. One of the goals of the project is to encourage
experimentation with the language itself by making it easier to modify the
interpreter (since it is written in Python). Additional information is
available on <a class="reference external" href="http://pypy.org/">the PyPy projects home page</a>.</p>
</dd>
</dl>
<p>Each of these implementations varies in some way from the language as documented
in this manual, or introduces specific information beyond whats covered in the
standard Python documentation. Please refer to the implementation-specific
documentation to determine what else you need to know about the specific
implementation youre using.</p>
</div>
<div class="section" id="notation">
<span id="id2"></span><h2>1.2. Notation<a class="headerlink" href="#notation" title="Permalink to this headline"></a></h2>
<p id="index-0">The descriptions of lexical analysis and syntax use a modified BNF grammar
notation. This uses the following style of definition:</p>
<pre>
<strong id="grammar-token-name">name </strong> ::= <a class="reference internal" href="#grammar-token-lc-letter"><code class="xref docutils literal notranslate"><span class="pre">lc_letter</span></code></a> (<a class="reference internal" href="#grammar-token-lc-letter"><code class="xref docutils literal notranslate"><span class="pre">lc_letter</span></code></a> | &quot;_&quot;)*
<strong id="grammar-token-lc-letter">lc_letter</strong> ::= &quot;a&quot;...&quot;z&quot;
</pre>
<p>The first line says that a <code class="docutils literal notranslate"><span class="pre">name</span></code> is an <code class="docutils literal notranslate"><span class="pre">lc_letter</span></code> followed by a sequence
of zero or more <code class="docutils literal notranslate"><span class="pre">lc_letter</span></code>s and underscores. An <code class="docutils literal notranslate"><span class="pre">lc_letter</span></code> in turn is
any of the single characters <code class="docutils literal notranslate"><span class="pre">'a'</span></code> through <code class="docutils literal notranslate"><span class="pre">'z'</span></code>. (This rule is actually
adhered to for the names defined in lexical and grammar rules in this document.)</p>
<p>Each rule begins with a name (which is the name defined by the rule) and
<code class="docutils literal notranslate"><span class="pre">::=</span></code>. A vertical bar (<code class="docutils literal notranslate"><span class="pre">|</span></code>) is used to separate alternatives; it is the
least binding operator in this notation. A star (<code class="docutils literal notranslate"><span class="pre">*</span></code>) means zero or more
repetitions of the preceding item; likewise, a plus (<code class="docutils literal notranslate"><span class="pre">+</span></code>) means one or more
repetitions, and a phrase enclosed in square brackets (<code class="docutils literal notranslate"><span class="pre">[</span> <span class="pre">]</span></code>) means zero or
one occurrences (in other words, the enclosed phrase is optional). The <code class="docutils literal notranslate"><span class="pre">*</span></code>
and <code class="docutils literal notranslate"><span class="pre">+</span></code> operators bind as tightly as possible; parentheses are used for
grouping. Literal strings are enclosed in quotes. White space is only
meaningful to separate tokens. Rules are normally contained on a single line;
rules with many alternatives may be formatted alternatively with each line after
the first beginning with a vertical bar.</p>
<p id="index-1">In lexical definitions (as the example above), two more conventions are used:
Two literal characters separated by three dots mean a choice of any single
character in the given (inclusive) range of ASCII characters. A phrase between
angular brackets (<code class="docutils literal notranslate"><span class="pre">&lt;...&gt;</span></code>) gives an informal description of the symbol
defined; e.g., this could be used to describe the notion of control character
if needed.</p>
<p>Even though the notation used is almost the same, there is a big difference
between the meaning of lexical and syntactic definitions: a lexical definition
operates on the individual characters of the input source, while a syntax
definition operates on the stream of tokens generated by the lexical analysis.
All uses of BNF in the next chapter (“Lexical Analysis”) are lexical
definitions; uses in subsequent chapters are syntactic definitions.</p>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="../contents.html">Table of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">1. Introduction</a><ul>
<li><a class="reference internal" href="#alternate-implementations">1.1. Alternate Implementations</a></li>
<li><a class="reference internal" href="#notation">1.2. Notation</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="index.html"
title="previous chapter">The Python Language Reference</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="lexical_analysis.html"
title="next chapter">2. Lexical analysis</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/reference/introduction.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="lexical_analysis.html" title="2. Lexical analysis"
>next</a> |</li>
<li class="right" >
<a href="index.html" title="The Python Language Reference"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>

View File

@@ -0,0 +1,940 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>2. Lexical analysis &#8212; Python 3.7.4 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" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="3. Data model" href="datamodel.html" />
<link rel="prev" title="1. Introduction" href="introduction.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/reference/lexical_analysis.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="datamodel.html" title="3. Data model"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="introduction.html" title="1. Introduction"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="lexical-analysis">
<span id="lexical"></span><h1>2. Lexical analysis<a class="headerlink" href="#lexical-analysis" title="Permalink to this headline"></a></h1>
<p id="index-0">A Python program is read by a <em>parser</em>. Input to the parser is a stream of
<em>tokens</em>, generated by the <em>lexical analyzer</em>. This chapter describes how the
lexical analyzer breaks a file into tokens.</p>
<p>Python reads program text as Unicode code points; the encoding of a source file
can be given by an encoding declaration and defaults to UTF-8, see <span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3120"><strong>PEP 3120</strong></a>
for details. If the source file cannot be decoded, a <a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> is
raised.</p>
<div class="section" id="line-structure">
<span id="id1"></span><h2>2.1. Line structure<a class="headerlink" href="#line-structure" title="Permalink to this headline"></a></h2>
<p id="index-2">A Python program is divided into a number of <em>logical lines</em>.</p>
<div class="section" id="logical-lines">
<span id="id2"></span><h3>2.1.1. Logical lines<a class="headerlink" href="#logical-lines" title="Permalink to this headline"></a></h3>
<p id="index-3">The end of a logical line is represented by the token NEWLINE. Statements
cannot cross logical line boundaries except where NEWLINE is allowed by the
syntax (e.g., between statements in compound statements). A logical line is
constructed from one or more <em>physical lines</em> by following the explicit or
implicit <em>line joining</em> rules.</p>
</div>
<div class="section" id="physical-lines">
<span id="id3"></span><h3>2.1.2. Physical lines<a class="headerlink" href="#physical-lines" title="Permalink to this headline"></a></h3>
<p>A physical line is a sequence of characters terminated by an end-of-line
sequence. In source files and strings, any of the standard platform line
termination sequences can be used - the Unix form using ASCII LF (linefeed),
the Windows form using the ASCII sequence CR LF (return followed by linefeed),
or the old Macintosh form using the ASCII CR (return) character. All of these
forms can be used equally, regardless of platform. The end of input also serves
as an implicit terminator for the final physical line.</p>
<p>When embedding Python, source code strings should be passed to Python APIs using
the standard C conventions for newline characters (the <code class="docutils literal notranslate"><span class="pre">\n</span></code> character,
representing ASCII LF, is the line terminator).</p>
</div>
<div class="section" id="comments">
<span id="id4"></span><h3>2.1.3. Comments<a class="headerlink" href="#comments" title="Permalink to this headline"></a></h3>
<p id="index-4">A comment starts with a hash character (<code class="docutils literal notranslate"><span class="pre">#</span></code>) that is not part of a string
literal, and ends at the end of the physical line. A comment signifies the end
of the logical line unless the implicit line joining rules are invoked. Comments
are ignored by the syntax.</p>
</div>
<div class="section" id="encoding-declarations">
<span id="encodings"></span><h3>2.1.4. Encoding declarations<a class="headerlink" href="#encoding-declarations" title="Permalink to this headline"></a></h3>
<p id="index-5">If a comment in the first or second line of the Python script matches the
regular expression <code class="docutils literal notranslate"><span class="pre">coding[=:]\s*([-\w.]+)</span></code>, this comment is processed as an
encoding declaration; the first group of this expression names the encoding of
the source code file. The encoding declaration must appear on a line of its
own. If it is the second line, the first line must also be a comment-only line.
The recommended forms of an encoding expression are</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># -*- coding: &lt;encoding-name&gt; -*-</span>
</pre></div>
</div>
<p>which is recognized also by GNU Emacs, and</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># vim:fileencoding=&lt;encoding-name&gt;</span>
</pre></div>
</div>
<p>which is recognized by Bram Moolenaars VIM.</p>
<p>If no encoding declaration is found, the default encoding is UTF-8. In
addition, if the first bytes of the file are the UTF-8 byte-order mark
(<code class="docutils literal notranslate"><span class="pre">b'\xef\xbb\xbf'</span></code>), the declared file encoding is UTF-8 (this is supported,
among others, by Microsofts <strong class="program">notepad</strong>).</p>
<p>If an encoding is declared, the encoding name must be recognized by Python. The
encoding is used for all lexical analysis, including string literals, comments
and identifiers.</p>
</div>
<div class="section" id="explicit-line-joining">
<span id="explicit-joining"></span><h3>2.1.5. Explicit line joining<a class="headerlink" href="#explicit-line-joining" title="Permalink to this headline"></a></h3>
<p id="index-6">Two or more physical lines may be joined into logical lines using backslash
characters (<code class="docutils literal notranslate"><span class="pre">\</span></code>), as follows: when a physical line ends in a backslash that is
not part of a string literal or comment, it is joined with the following forming
a single logical line, deleting the backslash and the following end-of-line
character. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="mi">1900</span> <span class="o">&lt;</span> <span class="n">year</span> <span class="o">&lt;</span> <span class="mi">2100</span> <span class="ow">and</span> <span class="mi">1</span> <span class="o">&lt;=</span> <span class="n">month</span> <span class="o">&lt;=</span> <span class="mi">12</span> \
<span class="ow">and</span> <span class="mi">1</span> <span class="o">&lt;=</span> <span class="n">day</span> <span class="o">&lt;=</span> <span class="mi">31</span> <span class="ow">and</span> <span class="mi">0</span> <span class="o">&lt;=</span> <span class="n">hour</span> <span class="o">&lt;</span> <span class="mi">24</span> \
<span class="ow">and</span> <span class="mi">0</span> <span class="o">&lt;=</span> <span class="n">minute</span> <span class="o">&lt;</span> <span class="mi">60</span> <span class="ow">and</span> <span class="mi">0</span> <span class="o">&lt;=</span> <span class="n">second</span> <span class="o">&lt;</span> <span class="mi">60</span><span class="p">:</span> <span class="c1"># Looks like a valid date</span>
<span class="k">return</span> <span class="mi">1</span>
</pre></div>
</div>
<p>A line ending in a backslash cannot carry a comment. A backslash does not
continue a comment. A backslash does not continue a token except for string
literals (i.e., tokens other than string literals cannot be split across
physical lines using a backslash). A backslash is illegal elsewhere on a line
outside a string literal.</p>
</div>
<div class="section" id="implicit-line-joining">
<span id="implicit-joining"></span><h3>2.1.6. Implicit line joining<a class="headerlink" href="#implicit-line-joining" title="Permalink to this headline"></a></h3>
<p>Expressions in parentheses, square brackets or curly braces can be split over
more than one physical line without using backslashes. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">month_names</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;Januari&#39;</span><span class="p">,</span> <span class="s1">&#39;Februari&#39;</span><span class="p">,</span> <span class="s1">&#39;Maart&#39;</span><span class="p">,</span> <span class="c1"># These are the</span>
<span class="s1">&#39;April&#39;</span><span class="p">,</span> <span class="s1">&#39;Mei&#39;</span><span class="p">,</span> <span class="s1">&#39;Juni&#39;</span><span class="p">,</span> <span class="c1"># Dutch names</span>
<span class="s1">&#39;Juli&#39;</span><span class="p">,</span> <span class="s1">&#39;Augustus&#39;</span><span class="p">,</span> <span class="s1">&#39;September&#39;</span><span class="p">,</span> <span class="c1"># for the months</span>
<span class="s1">&#39;Oktober&#39;</span><span class="p">,</span> <span class="s1">&#39;November&#39;</span><span class="p">,</span> <span class="s1">&#39;December&#39;</span><span class="p">]</span> <span class="c1"># of the year</span>
</pre></div>
</div>
<p>Implicitly continued lines can carry comments. The indentation of the
continuation lines is not important. Blank continuation lines are allowed.
There is no NEWLINE token between implicit continuation lines. Implicitly
continued lines can also occur within triple-quoted strings (see below); in that
case they cannot carry comments.</p>
</div>
<div class="section" id="blank-lines">
<span id="id5"></span><h3>2.1.7. Blank lines<a class="headerlink" href="#blank-lines" title="Permalink to this headline"></a></h3>
<p id="index-7">A logical line that contains only spaces, tabs, formfeeds and possibly a
comment, is ignored (i.e., no NEWLINE token is generated). During interactive
input of statements, handling of a blank line may differ depending on the
implementation of the read-eval-print loop. In the standard interactive
interpreter, an entirely blank logical line (i.e. one containing not even
whitespace or a comment) terminates a multi-line statement.</p>
</div>
<div class="section" id="indentation">
<span id="id6"></span><h3>2.1.8. Indentation<a class="headerlink" href="#indentation" title="Permalink to this headline"></a></h3>
<p id="index-8">Leading whitespace (spaces and tabs) at the beginning of a logical line is used
to compute the indentation level of the line, which in turn is used to determine
the grouping of statements.</p>
<p>Tabs are replaced (from left to right) by one to eight spaces such that the
total number of characters up to and including the replacement is a multiple of
eight (this is intended to be the same rule as used by Unix). The total number
of spaces preceding the first non-blank character then determines the lines
indentation. Indentation cannot be split over multiple physical lines using
backslashes; the whitespace up to the first backslash determines the
indentation.</p>
<p>Indentation is rejected as inconsistent if a source file mixes tabs and spaces
in a way that makes the meaning dependent on the worth of a tab in spaces; a
<a class="reference internal" href="../library/exceptions.html#TabError" title="TabError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TabError</span></code></a> is raised in that case.</p>
<p><strong>Cross-platform compatibility note:</strong> because of the nature of text editors on
non-UNIX platforms, it is unwise to use a mixture of spaces and tabs for the
indentation in a single source file. It should also be noted that different
platforms may explicitly limit the maximum indentation level.</p>
<p>A formfeed character may be present at the start of the line; it will be ignored
for the indentation calculations above. Formfeed characters occurring elsewhere
in the leading whitespace have an undefined effect (for instance, they may reset
the space count to zero).</p>
<p id="index-9">The indentation levels of consecutive lines are used to generate INDENT and
DEDENT tokens, using a stack, as follows.</p>
<p>Before the first line of the file is read, a single zero is pushed on the stack;
this will never be popped off again. The numbers pushed on the stack will
always be strictly increasing from bottom to top. At the beginning of each
logical line, the lines indentation level is compared to the top of the stack.
If it is equal, nothing happens. If it is larger, it is pushed on the stack, and
one INDENT token is generated. If it is smaller, it <em>must</em> be one of the
numbers occurring on the stack; all numbers on the stack that are larger are
popped off, and for each number popped off a DEDENT token is generated. At the
end of the file, a DEDENT token is generated for each number remaining on the
stack that is larger than zero.</p>
<p>Here is an example of a correctly (though confusingly) indented piece of Python
code:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">perm</span><span class="p">(</span><span class="n">l</span><span class="p">):</span>
<span class="c1"># Compute the list of all permutations of l</span>
<span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">l</span><span class="p">)</span> <span class="o">&lt;=</span> <span class="mi">1</span><span class="p">:</span>
<span class="k">return</span> <span class="p">[</span><span class="n">l</span><span class="p">]</span>
<span class="n">r</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">l</span><span class="p">)):</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">l</span><span class="p">[:</span><span class="n">i</span><span class="p">]</span> <span class="o">+</span> <span class="n">l</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">:]</span>
<span class="n">p</span> <span class="o">=</span> <span class="n">perm</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">p</span><span class="p">:</span>
<span class="n">r</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">l</span><span class="p">[</span><span class="n">i</span><span class="p">:</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">]</span> <span class="o">+</span> <span class="n">x</span><span class="p">)</span>
<span class="k">return</span> <span class="n">r</span>
</pre></div>
</div>
<p>The following example shows various indentation errors:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span> <span class="k">def</span> <span class="nf">perm</span><span class="p">(</span><span class="n">l</span><span class="p">):</span> <span class="c1"># error: first line indented</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">l</span><span class="p">)):</span> <span class="c1"># error: not indented</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">l</span><span class="p">[:</span><span class="n">i</span><span class="p">]</span> <span class="o">+</span> <span class="n">l</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">:]</span>
<span class="n">p</span> <span class="o">=</span> <span class="n">perm</span><span class="p">(</span><span class="n">l</span><span class="p">[:</span><span class="n">i</span><span class="p">]</span> <span class="o">+</span> <span class="n">l</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">:])</span> <span class="c1"># error: unexpected indent</span>
<span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">p</span><span class="p">:</span>
<span class="n">r</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">l</span><span class="p">[</span><span class="n">i</span><span class="p">:</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">]</span> <span class="o">+</span> <span class="n">x</span><span class="p">)</span>
<span class="k">return</span> <span class="n">r</span> <span class="c1"># error: inconsistent dedent</span>
</pre></div>
</div>
<p>(Actually, the first three errors are detected by the parser; only the last
error is found by the lexical analyzer — the indentation of <code class="docutils literal notranslate"><span class="pre">return</span> <span class="pre">r</span></code> does
not match a level popped off the stack.)</p>
</div>
<div class="section" id="whitespace-between-tokens">
<span id="whitespace"></span><h3>2.1.9. Whitespace between tokens<a class="headerlink" href="#whitespace-between-tokens" title="Permalink to this headline"></a></h3>
<p>Except at the beginning of a logical line or in string literals, the whitespace
characters space, tab and formfeed can be used interchangeably to separate
tokens. Whitespace is needed between two tokens only if their concatenation
could otherwise be interpreted as a different token (e.g., ab is one token, but
a b is two tokens).</p>
</div>
</div>
<div class="section" id="other-tokens">
<span id="id7"></span><h2>2.2. Other tokens<a class="headerlink" href="#other-tokens" title="Permalink to this headline"></a></h2>
<p>Besides NEWLINE, INDENT and DEDENT, the following categories of tokens exist:
<em>identifiers</em>, <em>keywords</em>, <em>literals</em>, <em>operators</em>, and <em>delimiters</em>. Whitespace
characters (other than line terminators, discussed earlier) are not tokens, but
serve to delimit tokens. Where ambiguity exists, a token comprises the longest
possible string that forms a legal token, when read from left to right.</p>
</div>
<div class="section" id="identifiers">
<span id="identifiers-and-keywords"></span><h2>2.3. Identifiers and keywords<a class="headerlink" href="#identifiers" title="Permalink to this headline"></a></h2>
<p id="index-10">Identifiers (also referred to as <em>names</em>) are described by the following lexical
definitions.</p>
<p>The syntax of identifiers in Python is based on the Unicode standard annex
UAX-31, with elaboration and changes as defined below; see also <span class="target" id="index-11"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3131"><strong>PEP 3131</strong></a> for
further details.</p>
<p>Within the ASCII range (U+0001..U+007F), the valid characters for identifiers
are the same as in Python 2.x: the uppercase and lowercase letters <code class="docutils literal notranslate"><span class="pre">A</span></code> through
<code class="docutils literal notranslate"><span class="pre">Z</span></code>, the underscore <code class="docutils literal notranslate"><span class="pre">_</span></code> and, except for the first character, the digits
<code class="docutils literal notranslate"><span class="pre">0</span></code> through <code class="docutils literal notranslate"><span class="pre">9</span></code>.</p>
<p>Python 3.0 introduces additional characters from outside the ASCII range (see
<span class="target" id="index-12"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3131"><strong>PEP 3131</strong></a>). For these characters, the classification uses the version of the
Unicode Character Database as included in the <a class="reference internal" href="../library/unicodedata.html#module-unicodedata" title="unicodedata: Access the Unicode Database."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unicodedata</span></code></a> module.</p>
<p>Identifiers are unlimited in length. Case is significant.</p>
<pre>
<strong id="grammar-token-identifier">identifier </strong> ::= <a class="reference internal" href="#grammar-token-xid-start"><code class="xref docutils literal notranslate"><span class="pre">xid_start</span></code></a> <a class="reference internal" href="#grammar-token-xid-continue"><code class="xref docutils literal notranslate"><span class="pre">xid_continue</span></code></a>*
<strong id="grammar-token-id-start">id_start </strong> ::= &lt;all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property&gt;
<strong id="grammar-token-id-continue">id_continue </strong> ::= &lt;all characters in <a class="reference internal" href="#grammar-token-id-start"><code class="xref docutils literal notranslate"><span class="pre">id_start</span></code></a>, plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property&gt;
<strong id="grammar-token-xid-start">xid_start </strong> ::= &lt;all characters in <a class="reference internal" href="#grammar-token-id-start"><code class="xref docutils literal notranslate"><span class="pre">id_start</span></code></a> whose NFKC normalization is in &quot;id_start xid_continue*&quot;&gt;
<strong id="grammar-token-xid-continue">xid_continue</strong> ::= &lt;all characters in <a class="reference internal" href="#grammar-token-id-continue"><code class="xref docutils literal notranslate"><span class="pre">id_continue</span></code></a> whose NFKC normalization is in &quot;id_continue*&quot;&gt;
</pre>
<p>The Unicode category codes mentioned above stand for:</p>
<ul class="simple">
<li><p><em>Lu</em> - uppercase letters</p></li>
<li><p><em>Ll</em> - lowercase letters</p></li>
<li><p><em>Lt</em> - titlecase letters</p></li>
<li><p><em>Lm</em> - modifier letters</p></li>
<li><p><em>Lo</em> - other letters</p></li>
<li><p><em>Nl</em> - letter numbers</p></li>
<li><p><em>Mn</em> - nonspacing marks</p></li>
<li><p><em>Mc</em> - spacing combining marks</p></li>
<li><p><em>Nd</em> - decimal numbers</p></li>
<li><p><em>Pc</em> - connector punctuations</p></li>
<li><p><em>Other_ID_Start</em> - explicit list of characters in <a class="reference external" href="http://www.unicode.org/Public/11.0.0/ucd/PropList.txt">PropList.txt</a> to support backwards
compatibility</p></li>
<li><p><em>Other_ID_Continue</em> - likewise</p></li>
</ul>
<p>All identifiers are converted into the normal form NFKC while parsing; comparison
of identifiers is based on NFKC.</p>
<p>A non-normative HTML file listing all valid identifier characters for Unicode
4.1 can be found at
<a class="reference external" href="https://www.dcl.hpi.uni-potsdam.de/home/loewis/table-3131.html">https://www.dcl.hpi.uni-potsdam.de/home/loewis/table-3131.html</a>.</p>
<div class="section" id="keywords">
<span id="id8"></span><h3>2.3.1. Keywords<a class="headerlink" href="#keywords" title="Permalink to this headline"></a></h3>
<p id="index-13">The following identifiers are used as reserved words, or <em>keywords</em> of the
language, and cannot be used as ordinary identifiers. They must be spelled
exactly as written here:</p>
<div class="highlight-text notranslate"><div class="highlight"><pre><span></span>False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
</pre></div>
</div>
</div>
<div class="section" id="reserved-classes-of-identifiers">
<span id="id-classes"></span><span id="index-14"></span><h3>2.3.2. Reserved classes of identifiers<a class="headerlink" href="#reserved-classes-of-identifiers" title="Permalink to this headline"></a></h3>
<p>Certain classes of identifiers (besides keywords) have special meanings. These
classes are identified by the patterns of leading and trailing underscore
characters:</p>
<dl>
<dt><code class="docutils literal notranslate"><span class="pre">_*</span></code></dt><dd><p>Not imported by <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">module</span> <span class="pre">import</span> <span class="pre">*</span></code>. The special identifier <code class="docutils literal notranslate"><span class="pre">_</span></code> is used
in the interactive interpreter to store the result of the last evaluation; it is
stored in the <a class="reference internal" href="../library/builtins.html#module-builtins" title="builtins: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">builtins</span></code></a> module. When not in interactive mode, <code class="docutils literal notranslate"><span class="pre">_</span></code>
has no special meaning and is not defined. See section <a class="reference internal" href="simple_stmts.html#import"><span class="std std-ref">The import statement</span></a>.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>The name <code class="docutils literal notranslate"><span class="pre">_</span></code> is often used in conjunction with internationalization;
refer to the documentation for the <a class="reference internal" href="../library/gettext.html#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gettext</span></code></a> module for more
information on this convention.</p>
</div>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">__*__</span></code></dt><dd><p>System-defined names. These names are defined by the interpreter and its
implementation (including the standard library). Current system names are
discussed in the <a class="reference internal" href="datamodel.html#specialnames"><span class="std std-ref">Special method names</span></a> section and elsewhere. More will likely
be defined in future versions of Python. <em>Any</em> use of <code class="docutils literal notranslate"><span class="pre">__*__</span></code> names, in
any context, that does not follow explicitly documented use, is subject to
breakage without warning.</p>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">__*</span></code></dt><dd><p>Class-private names. Names in this category, when used within the context of a
class definition, are re-written to use a mangled form to help avoid name
clashes between “private” attributes of base and derived classes. See section
<a class="reference internal" href="expressions.html#atom-identifiers"><span class="std std-ref">Identifiers (Names)</span></a>.</p>
</dd>
</dl>
</div>
</div>
<div class="section" id="literals">
<span id="id9"></span><h2>2.4. Literals<a class="headerlink" href="#literals" title="Permalink to this headline"></a></h2>
<p id="index-15">Literals are notations for constant values of some built-in types.</p>
<div class="section" id="string-and-bytes-literals">
<span id="strings"></span><span id="index-16"></span><h3>2.4.1. String and Bytes literals<a class="headerlink" href="#string-and-bytes-literals" title="Permalink to this headline"></a></h3>
<p>String literals are described by the following lexical definitions:</p>
<pre>
<strong id="grammar-token-stringliteral">stringliteral </strong> ::= [<a class="reference internal" href="#grammar-token-stringprefix"><code class="xref docutils literal notranslate"><span class="pre">stringprefix</span></code></a>](<a class="reference internal" href="#grammar-token-shortstring"><code class="xref docutils literal notranslate"><span class="pre">shortstring</span></code></a> | <a class="reference internal" href="#grammar-token-longstring"><code class="xref docutils literal notranslate"><span class="pre">longstring</span></code></a>)
<strong id="grammar-token-stringprefix">stringprefix </strong> ::= &quot;r&quot; | &quot;u&quot; | &quot;R&quot; | &quot;U&quot; | &quot;f&quot; | &quot;F&quot;
| &quot;fr&quot; | &quot;Fr&quot; | &quot;fR&quot; | &quot;FR&quot; | &quot;rf&quot; | &quot;rF&quot; | &quot;Rf&quot; | &quot;RF&quot;
<strong id="grammar-token-shortstring">shortstring </strong> ::= &quot;'&quot; <a class="reference internal" href="#grammar-token-shortstringitem"><code class="xref docutils literal notranslate"><span class="pre">shortstringitem</span></code></a>* &quot;'&quot; | '&quot;' <a class="reference internal" href="#grammar-token-shortstringitem"><code class="xref docutils literal notranslate"><span class="pre">shortstringitem</span></code></a>* '&quot;'
<strong id="grammar-token-longstring">longstring </strong> ::= &quot;'''&quot; <a class="reference internal" href="#grammar-token-longstringitem"><code class="xref docutils literal notranslate"><span class="pre">longstringitem</span></code></a>* &quot;'''&quot; | '&quot;&quot;&quot;' <a class="reference internal" href="#grammar-token-longstringitem"><code class="xref docutils literal notranslate"><span class="pre">longstringitem</span></code></a>* '&quot;&quot;&quot;'
<strong id="grammar-token-shortstringitem">shortstringitem</strong> ::= <a class="reference internal" href="#grammar-token-shortstringchar"><code class="xref docutils literal notranslate"><span class="pre">shortstringchar</span></code></a> | <a class="reference internal" href="#grammar-token-stringescapeseq"><code class="xref docutils literal notranslate"><span class="pre">stringescapeseq</span></code></a>
<strong id="grammar-token-longstringitem">longstringitem </strong> ::= <a class="reference internal" href="#grammar-token-longstringchar"><code class="xref docutils literal notranslate"><span class="pre">longstringchar</span></code></a> | <a class="reference internal" href="#grammar-token-stringescapeseq"><code class="xref docutils literal notranslate"><span class="pre">stringescapeseq</span></code></a>
<strong id="grammar-token-shortstringchar">shortstringchar</strong> ::= &lt;any source character except &quot;\&quot; or newline or the quote&gt;
<strong id="grammar-token-longstringchar">longstringchar </strong> ::= &lt;any source character except &quot;\&quot;&gt;
<strong id="grammar-token-stringescapeseq">stringescapeseq</strong> ::= &quot;\&quot; &lt;any source character&gt;
</pre>
<pre>
<strong id="grammar-token-bytesliteral">bytesliteral </strong> ::= <a class="reference internal" href="#grammar-token-bytesprefix"><code class="xref docutils literal notranslate"><span class="pre">bytesprefix</span></code></a>(<a class="reference internal" href="#grammar-token-shortbytes"><code class="xref docutils literal notranslate"><span class="pre">shortbytes</span></code></a> | <a class="reference internal" href="#grammar-token-longbytes"><code class="xref docutils literal notranslate"><span class="pre">longbytes</span></code></a>)
<strong id="grammar-token-bytesprefix">bytesprefix </strong> ::= &quot;b&quot; | &quot;B&quot; | &quot;br&quot; | &quot;Br&quot; | &quot;bR&quot; | &quot;BR&quot; | &quot;rb&quot; | &quot;rB&quot; | &quot;Rb&quot; | &quot;RB&quot;
<strong id="grammar-token-shortbytes">shortbytes </strong> ::= &quot;'&quot; <a class="reference internal" href="#grammar-token-shortbytesitem"><code class="xref docutils literal notranslate"><span class="pre">shortbytesitem</span></code></a>* &quot;'&quot; | '&quot;' <a class="reference internal" href="#grammar-token-shortbytesitem"><code class="xref docutils literal notranslate"><span class="pre">shortbytesitem</span></code></a>* '&quot;'
<strong id="grammar-token-longbytes">longbytes </strong> ::= &quot;'''&quot; <a class="reference internal" href="#grammar-token-longbytesitem"><code class="xref docutils literal notranslate"><span class="pre">longbytesitem</span></code></a>* &quot;'''&quot; | '&quot;&quot;&quot;' <a class="reference internal" href="#grammar-token-longbytesitem"><code class="xref docutils literal notranslate"><span class="pre">longbytesitem</span></code></a>* '&quot;&quot;&quot;'
<strong id="grammar-token-shortbytesitem">shortbytesitem</strong> ::= <a class="reference internal" href="#grammar-token-shortbyteschar"><code class="xref docutils literal notranslate"><span class="pre">shortbyteschar</span></code></a> | <a class="reference internal" href="#grammar-token-bytesescapeseq"><code class="xref docutils literal notranslate"><span class="pre">bytesescapeseq</span></code></a>
<strong id="grammar-token-longbytesitem">longbytesitem </strong> ::= <a class="reference internal" href="#grammar-token-longbyteschar"><code class="xref docutils literal notranslate"><span class="pre">longbyteschar</span></code></a> | <a class="reference internal" href="#grammar-token-bytesescapeseq"><code class="xref docutils literal notranslate"><span class="pre">bytesescapeseq</span></code></a>
<strong id="grammar-token-shortbyteschar">shortbyteschar</strong> ::= &lt;any ASCII character except &quot;\&quot; or newline or the quote&gt;
<strong id="grammar-token-longbyteschar">longbyteschar </strong> ::= &lt;any ASCII character except &quot;\&quot;&gt;
<strong id="grammar-token-bytesescapeseq">bytesescapeseq</strong> ::= &quot;\&quot; &lt;any ASCII character&gt;
</pre>
<p>One syntactic restriction not indicated by these productions is that whitespace
is not allowed between the <a class="reference internal" href="#grammar-token-stringprefix"><code class="xref std std-token docutils literal notranslate"><span class="pre">stringprefix</span></code></a> or <a class="reference internal" href="#grammar-token-bytesprefix"><code class="xref std std-token docutils literal notranslate"><span class="pre">bytesprefix</span></code></a> and the
rest of the literal. The source character set is defined by the encoding
declaration; it is UTF-8 if no encoding declaration is given in the source file;
see section <a class="reference internal" href="#encodings"><span class="std std-ref">Encoding declarations</span></a>.</p>
<p id="index-17">In plain English: Both types of literals can be enclosed in matching single quotes
(<code class="docutils literal notranslate"><span class="pre">'</span></code>) or double quotes (<code class="docutils literal notranslate"><span class="pre">&quot;</span></code>). They can also be enclosed in matching groups
of three single or double quotes (these are generally referred to as
<em>triple-quoted strings</em>). The backslash (<code class="docutils literal notranslate"><span class="pre">\</span></code>) character is used to escape
characters that otherwise have a special meaning, such as newline, backslash
itself, or the quote character.</p>
<p id="index-18">Bytes literals are always prefixed with <code class="docutils literal notranslate"><span class="pre">'b'</span></code> or <code class="docutils literal notranslate"><span class="pre">'B'</span></code>; they produce an
instance of the <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> type instead of the <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> type. They
may only contain ASCII characters; bytes with a numeric value of 128 or greater
must be expressed with escapes.</p>
<p id="index-19">Both string and bytes literals may optionally be prefixed with a letter <code class="docutils literal notranslate"><span class="pre">'r'</span></code>
or <code class="docutils literal notranslate"><span class="pre">'R'</span></code>; such strings are called <em class="dfn">raw strings</em> and treat backslashes as
literal characters. As a result, in string literals, <code class="docutils literal notranslate"><span class="pre">'\U'</span></code> and <code class="docutils literal notranslate"><span class="pre">'\u'</span></code>
escapes in raw strings are not treated specially. Given that Python 2.xs raw
unicode literals behave differently than Python 3.xs the <code class="docutils literal notranslate"><span class="pre">'ur'</span></code> syntax
is not supported.</p>
<div class="versionadded">
<p><span class="versionmodified added">New in version 3.3: </span>The <code class="docutils literal notranslate"><span class="pre">'rb'</span></code> prefix of raw bytes literals has been added as a synonym
of <code class="docutils literal notranslate"><span class="pre">'br'</span></code>.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified added">New in version 3.3: </span>Support for the unicode legacy literal (<code class="docutils literal notranslate"><span class="pre">u'value'</span></code>) was reintroduced
to simplify the maintenance of dual Python 2.x and 3.x codebases.
See <span class="target" id="index-20"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0414"><strong>PEP 414</strong></a> for more information.</p>
</div>
<p id="index-21">A string literal with <code class="docutils literal notranslate"><span class="pre">'f'</span></code> or <code class="docutils literal notranslate"><span class="pre">'F'</span></code> in its prefix is a
<em class="dfn">formatted string literal</em>; see <a class="reference internal" href="#f-strings"><span class="std std-ref">Formatted string literals</span></a>. The <code class="docutils literal notranslate"><span class="pre">'f'</span></code> may be
combined with <code class="docutils literal notranslate"><span class="pre">'r'</span></code>, but not with <code class="docutils literal notranslate"><span class="pre">'b'</span></code> or <code class="docutils literal notranslate"><span class="pre">'u'</span></code>, therefore raw
formatted strings are possible, but formatted bytes literals are not.</p>
<p>In triple-quoted literals, unescaped newlines and quotes are allowed (and are
retained), except that three unescaped quotes in a row terminate the literal. (A
“quote” is the character used to open the literal, i.e. either <code class="docutils literal notranslate"><span class="pre">'</span></code> or <code class="docutils literal notranslate"><span class="pre">&quot;</span></code>.)</p>
<p id="index-22">Unless an <code class="docutils literal notranslate"><span class="pre">'r'</span></code> or <code class="docutils literal notranslate"><span class="pre">'R'</span></code> prefix is present, escape sequences in string and
bytes literals are interpreted according to rules similar to those used by
Standard C. The recognized escape sequences are:</p>
<table class="docutils align-center">
<colgroup>
<col style="width: 30%" />
<col style="width: 58%" />
<col style="width: 12%" />
</colgroup>
<thead>
<tr class="row-odd"><th class="head"><p>Escape Sequence</p></th>
<th class="head"><p>Meaning</p></th>
<th class="head"><p>Notes</p></th>
</tr>
</thead>
<tbody>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">\newline</span></code></p></td>
<td><p>Backslash and newline ignored</p></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">\\</span></code></p></td>
<td><p>Backslash (<code class="docutils literal notranslate"><span class="pre">\</span></code>)</p></td>
<td></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">\'</span></code></p></td>
<td><p>Single quote (<code class="docutils literal notranslate"><span class="pre">'</span></code>)</p></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">\&quot;</span></code></p></td>
<td><p>Double quote (<code class="docutils literal notranslate"><span class="pre">&quot;</span></code>)</p></td>
<td></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">\a</span></code></p></td>
<td><p>ASCII Bell (BEL)</p></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">\b</span></code></p></td>
<td><p>ASCII Backspace (BS)</p></td>
<td></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">\f</span></code></p></td>
<td><p>ASCII Formfeed (FF)</p></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">\n</span></code></p></td>
<td><p>ASCII Linefeed (LF)</p></td>
<td></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">\r</span></code></p></td>
<td><p>ASCII Carriage Return (CR)</p></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">\t</span></code></p></td>
<td><p>ASCII Horizontal Tab (TAB)</p></td>
<td></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">\v</span></code></p></td>
<td><p>ASCII Vertical Tab (VT)</p></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">\ooo</span></code></p></td>
<td><p>Character with octal value
<em>ooo</em></p></td>
<td><p>(1,3)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">\xhh</span></code></p></td>
<td><p>Character with hex value <em>hh</em></p></td>
<td><p>(2,3)</p></td>
</tr>
</tbody>
</table>
<p>Escape sequences only recognized in string literals are:</p>
<table class="docutils align-center">
<colgroup>
<col style="width: 30%" />
<col style="width: 58%" />
<col style="width: 12%" />
</colgroup>
<thead>
<tr class="row-odd"><th class="head"><p>Escape Sequence</p></th>
<th class="head"><p>Meaning</p></th>
<th class="head"><p>Notes</p></th>
</tr>
</thead>
<tbody>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">\N{name}</span></code></p></td>
<td><p>Character named <em>name</em> in the
Unicode database</p></td>
<td><p>(4)</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">\uxxxx</span></code></p></td>
<td><p>Character with 16-bit hex value
<em>xxxx</em></p></td>
<td><p>(5)</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">\Uxxxxxxxx</span></code></p></td>
<td><p>Character with 32-bit hex value
<em>xxxxxxxx</em></p></td>
<td><p>(6)</p></td>
</tr>
</tbody>
</table>
<p>Notes:</p>
<ol class="arabic">
<li><p>As in Standard C, up to three octal digits are accepted.</p></li>
<li><p>Unlike in Standard C, exactly two hex digits are required.</p></li>
<li><p>In a bytes literal, hexadecimal and octal escapes denote the byte with the
given value. In a string literal, these escapes denote a Unicode character
with the given value.</p></li>
<li><div class="versionchanged">
<p><span class="versionmodified changed">Changed in version 3.3: </span>Support for name aliases <a class="footnote-reference brackets" href="#id13" id="id10">1</a> has been added.</p>
</div>
</li>
<li><p>Exactly four hex digits are required.</p></li>
<li><p>Any Unicode character can be encoded this way. Exactly eight hex digits
are required.</p></li>
</ol>
<p id="index-23">Unlike Standard C, all unrecognized escape sequences are left in the string
unchanged, i.e., <em>the backslash is left in the result</em>. (This behavior is
useful when debugging: if an escape sequence is mistyped, the resulting output
is more easily recognized as broken.) It is also important to note that the
escape sequences only recognized in string literals fall into the category of
unrecognized escapes for bytes literals.</p>
<blockquote>
<div><div class="versionchanged">
<p><span class="versionmodified changed">Changed in version 3.6: </span>Unrecognized escape sequences produce a DeprecationWarning. In
some future version of Python they will be a SyntaxError.</p>
</div>
</div></blockquote>
<p>Even in a raw literal, quotes can be escaped with a backslash, but the
backslash remains in the result; for example, <code class="docutils literal notranslate"><span class="pre">r&quot;\&quot;&quot;</span></code> is a valid string
literal consisting of two characters: a backslash and a double quote; <code class="docutils literal notranslate"><span class="pre">r&quot;\&quot;</span></code>
is not a valid string literal (even a raw string cannot end in an odd number of
backslashes). Specifically, <em>a raw literal cannot end in a single backslash</em>
(since the backslash would escape the following quote character). Note also
that a single backslash followed by a newline is interpreted as those two
characters as part of the literal, <em>not</em> as a line continuation.</p>
</div>
<div class="section" id="string-literal-concatenation">
<span id="string-concatenation"></span><h3>2.4.2. String literal concatenation<a class="headerlink" href="#string-literal-concatenation" title="Permalink to this headline"></a></h3>
<p>Multiple adjacent string or bytes literals (delimited by whitespace), possibly
using different quoting conventions, are allowed, and their meaning is the same
as their concatenation. Thus, <code class="docutils literal notranslate"><span class="pre">&quot;hello&quot;</span> <span class="pre">'world'</span></code> is equivalent to
<code class="docutils literal notranslate"><span class="pre">&quot;helloworld&quot;</span></code>. This feature can be used to reduce the number of backslashes
needed, to split long strings conveniently across long lines, or even to add
comments to parts of strings, for example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s2">&quot;[A-Za-z_]&quot;</span> <span class="c1"># letter or underscore</span>
<span class="s2">&quot;[A-Za-z0-9_]*&quot;</span> <span class="c1"># letter, digit or underscore</span>
<span class="p">)</span>
</pre></div>
</div>
<p>Note that this feature is defined at the syntactical level, but implemented at
compile time. The + operator must be used to concatenate string expressions
at run time. Also note that literal concatenation can use different quoting
styles for each component (even mixing raw strings and triple quoted strings),
and formatted string literals may be concatenated with plain string literals.</p>
</div>
<div class="section" id="formatted-string-literals">
<span id="f-strings"></span><span id="index-24"></span><h3>2.4.3. Formatted string literals<a class="headerlink" href="#formatted-string-literals" title="Permalink to this headline"></a></h3>
<div class="versionadded">
<p><span class="versionmodified added">New in version 3.6.</span></p>
</div>
<p>A <em class="dfn">formatted string literal</em> or <em class="dfn">f-string</em> is a string literal
that is prefixed with <code class="docutils literal notranslate"><span class="pre">'f'</span></code> or <code class="docutils literal notranslate"><span class="pre">'F'</span></code>. These strings may contain
replacement fields, which are expressions delimited by curly braces <code class="docutils literal notranslate"><span class="pre">{}</span></code>.
While other string literals always have a constant value, formatted strings
are really expressions evaluated at run time.</p>
<p>Escape sequences are decoded like in ordinary string literals (except when
a literal is also marked as a raw string). After decoding, the grammar
for the contents of the string is:</p>
<pre>
<strong id="grammar-token-f-string">f_string </strong> ::= (<a class="reference internal" href="#grammar-token-literal-char"><code class="xref docutils literal notranslate"><span class="pre">literal_char</span></code></a> | &quot;{{&quot; | &quot;}}&quot; | <a class="reference internal" href="#grammar-token-replacement-field"><code class="xref docutils literal notranslate"><span class="pre">replacement_field</span></code></a>)*
<strong id="grammar-token-replacement-field">replacement_field</strong> ::= &quot;{&quot; <a class="reference internal" href="#grammar-token-f-expression"><code class="xref docutils literal notranslate"><span class="pre">f_expression</span></code></a> [&quot;!&quot; <a class="reference internal" href="#grammar-token-conversion"><code class="xref docutils literal notranslate"><span class="pre">conversion</span></code></a>] [&quot;:&quot; <a class="reference internal" href="#grammar-token-format-spec"><code class="xref docutils literal notranslate"><span class="pre">format_spec</span></code></a>] &quot;}&quot;
<strong id="grammar-token-f-expression">f_expression </strong> ::= (<a class="reference internal" href="expressions.html#grammar-token-conditional-expression"><code class="xref docutils literal notranslate"><span class="pre">conditional_expression</span></code></a> | &quot;*&quot; <a class="reference internal" href="expressions.html#grammar-token-or-expr"><code class="xref docutils literal notranslate"><span class="pre">or_expr</span></code></a>)
(&quot;,&quot; <a class="reference internal" href="expressions.html#grammar-token-conditional-expression"><code class="xref docutils literal notranslate"><span class="pre">conditional_expression</span></code></a> | &quot;,&quot; &quot;*&quot; <a class="reference internal" href="expressions.html#grammar-token-or-expr"><code class="xref docutils literal notranslate"><span class="pre">or_expr</span></code></a>)* [&quot;,&quot;]
| <a class="reference internal" href="expressions.html#grammar-token-yield-expression"><code class="xref docutils literal notranslate"><span class="pre">yield_expression</span></code></a>
<strong id="grammar-token-conversion">conversion </strong> ::= &quot;s&quot; | &quot;r&quot; | &quot;a&quot;
<strong id="grammar-token-format-spec">format_spec </strong> ::= (<a class="reference internal" href="#grammar-token-literal-char"><code class="xref docutils literal notranslate"><span class="pre">literal_char</span></code></a> | NULL | <a class="reference internal" href="#grammar-token-replacement-field"><code class="xref docutils literal notranslate"><span class="pre">replacement_field</span></code></a>)*
<strong id="grammar-token-literal-char">literal_char </strong> ::= &lt;any code point except &quot;{&quot;, &quot;}&quot; or NULL&gt;
</pre>
<p>The parts of the string outside curly braces are treated literally,
except that any doubled curly braces <code class="docutils literal notranslate"><span class="pre">'{{'</span></code> or <code class="docutils literal notranslate"><span class="pre">'}}'</span></code> are replaced
with the corresponding single curly brace. A single opening curly
bracket <code class="docutils literal notranslate"><span class="pre">'{'</span></code> marks a replacement field, which starts with a
Python expression. After the expression, there may be a conversion field,
introduced by an exclamation point <code class="docutils literal notranslate"><span class="pre">'!'</span></code>. A format specifier may also
be appended, introduced by a colon <code class="docutils literal notranslate"><span class="pre">':'</span></code>. A replacement field ends
with a closing curly bracket <code class="docutils literal notranslate"><span class="pre">'}'</span></code>.</p>
<p>Expressions in formatted string literals are treated like regular
Python expressions surrounded by parentheses, with a few exceptions.
An empty expression is not allowed, and a <a class="reference internal" href="expressions.html#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a> expression
must be surrounded by explicit parentheses. Replacement expressions
can contain line breaks (e.g. in triple-quoted strings), but they
cannot contain comments. Each expression is evaluated in the context
where the formatted string literal appears, in order from left to right.</p>
<p>If a conversion is specified, the result of evaluating the expression
is converted before formatting. Conversion <code class="docutils literal notranslate"><span class="pre">'!s'</span></code> calls <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> on
the result, <code class="docutils literal notranslate"><span class="pre">'!r'</span></code> calls <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a>, and <code class="docutils literal notranslate"><span class="pre">'!a'</span></code> calls <a class="reference internal" href="../library/functions.html#ascii" title="ascii"><code class="xref py py-func docutils literal notranslate"><span class="pre">ascii()</span></code></a>.</p>
<p>The result is then formatted using the <a class="reference internal" href="../library/functions.html#format" title="format"><code class="xref py py-func docutils literal notranslate"><span class="pre">format()</span></code></a> protocol. The
format specifier is passed to the <a class="reference internal" href="datamodel.html#object.__format__" title="object.__format__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__format__()</span></code></a> method of the
expression or conversion result. An empty string is passed when the
format specifier is omitted. The formatted result is then included in
the final value of the whole string.</p>
<p>Top-level format specifiers may include nested replacement fields. These nested
fields may include their own conversion fields and <a class="reference internal" href="../library/string.html#formatspec"><span class="std std-ref">format specifiers</span></a>, but may not include more deeply-nested replacement fields. The
<a class="reference internal" href="../library/string.html#formatspec"><span class="std std-ref">format specifier mini-language</span></a> is the same as that used by
the string .format() method.</p>
<p>Formatted string literals may be concatenated, but replacement fields
cannot be split across literals.</p>
<p>Some examples of formatted string literals:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">name</span> <span class="o">=</span> <span class="s2">&quot;Fred&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="s2">&quot;He said his name is </span><span class="si">{name!r}</span><span class="s2">.&quot;</span>
<span class="go">&quot;He said his name is &#39;Fred&#39;.&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="s2">&quot;He said his name is {repr(name)}.&quot;</span> <span class="c1"># repr() is equivalent to !r</span>
<span class="go">&quot;He said his name is &#39;Fred&#39;.&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">width</span> <span class="o">=</span> <span class="mi">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">precision</span> <span class="o">=</span> <span class="mi">4</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">value</span> <span class="o">=</span> <span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="s2">&quot;12.34567&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="s2">&quot;result: {value:</span><span class="si">{width}</span><span class="s2">.</span><span class="si">{precision}</span><span class="s2">}&quot;</span> <span class="c1"># nested fields</span>
<span class="go">&#39;result: 12.35&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">today</span> <span class="o">=</span> <span class="n">datetime</span><span class="p">(</span><span class="n">year</span><span class="o">=</span><span class="mi">2017</span><span class="p">,</span> <span class="n">month</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">day</span><span class="o">=</span><span class="mi">27</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="s2">&quot;{today:%B </span><span class="si">%d</span><span class="s2">, %Y}&quot;</span> <span class="c1"># using date format specifier</span>
<span class="go">&#39;January 27, 2017&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">number</span> <span class="o">=</span> <span class="mi">1024</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="s2">&quot;</span><span class="si">{number:#0x}</span><span class="s2">&quot;</span> <span class="c1"># using integer format specifier</span>
<span class="go">&#39;0x400&#39;</span>
</pre></div>
</div>
<p>A consequence of sharing the same syntax as regular string literals is
that characters in the replacement fields must not conflict with the
quoting used in the outer formatted string literal:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">f</span><span class="s2">&quot;abc </span><span class="si">{a[&quot;x&quot;]}</span><span class="s2"> def&quot;</span> <span class="c1"># error: outer string literal ended prematurely</span>
<span class="n">f</span><span class="s2">&quot;abc </span><span class="si">{a[&#39;x&#39;]}</span><span class="s2"> def&quot;</span> <span class="c1"># workaround: use different quoting</span>
</pre></div>
</div>
<p>Backslashes are not allowed in format expressions and will raise
an error:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">f</span><span class="s2">&quot;newline: {ord(&#39;</span><span class="se">\n</span><span class="s2">&#39;)}&quot;</span> <span class="c1"># raises SyntaxError</span>
</pre></div>
</div>
<p>To include a value in which a backslash escape is required, create
a temporary variable.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">newline</span> <span class="o">=</span> <span class="nb">ord</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="s2">&quot;newline: </span><span class="si">{newline}</span><span class="s2">&quot;</span>
<span class="go">&#39;newline: 10&#39;</span>
</pre></div>
</div>
<p>Formatted string literals cannot be used as docstrings, even if they do not
include expressions.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">foo</span><span class="p">():</span>
<span class="gp">... </span> <span class="n">f</span><span class="s2">&quot;Not a docstring&quot;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">foo</span><span class="o">.</span><span class="vm">__doc__</span> <span class="ow">is</span> <span class="kc">None</span>
<span class="go">True</span>
</pre></div>
</div>
<p>See also <span class="target" id="index-25"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0498"><strong>PEP 498</strong></a> for the proposal that added formatted string literals,
and <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a>, which uses a related format string mechanism.</p>
</div>
<div class="section" id="numeric-literals">
<span id="numbers"></span><h3>2.4.4. Numeric literals<a class="headerlink" href="#numeric-literals" title="Permalink to this headline"></a></h3>
<p id="index-26">There are three types of numeric literals: integers, floating point numbers, and
imaginary numbers. There are no complex literals (complex numbers can be formed
by adding a real number and an imaginary number).</p>
<p>Note that numeric literals do not include a sign; a phrase like <code class="docutils literal notranslate"><span class="pre">-1</span></code> is
actually an expression composed of the unary operator <code class="docutils literal notranslate"><span class="pre">-</span></code> and the literal
<code class="docutils literal notranslate"><span class="pre">1</span></code>.</p>
</div>
<div class="section" id="integer-literals">
<span id="integers"></span><span id="index-27"></span><h3>2.4.5. Integer literals<a class="headerlink" href="#integer-literals" title="Permalink to this headline"></a></h3>
<p>Integer literals are described by the following lexical definitions:</p>
<pre>
<strong id="grammar-token-integer">integer </strong> ::= <a class="reference internal" href="#grammar-token-decinteger"><code class="xref docutils literal notranslate"><span class="pre">decinteger</span></code></a> | <a class="reference internal" href="#grammar-token-bininteger"><code class="xref docutils literal notranslate"><span class="pre">bininteger</span></code></a> | <a class="reference internal" href="#grammar-token-octinteger"><code class="xref docutils literal notranslate"><span class="pre">octinteger</span></code></a> | <a class="reference internal" href="#grammar-token-hexinteger"><code class="xref docutils literal notranslate"><span class="pre">hexinteger</span></code></a>
<strong id="grammar-token-decinteger">decinteger </strong> ::= <a class="reference internal" href="#grammar-token-nonzerodigit"><code class="xref docutils literal notranslate"><span class="pre">nonzerodigit</span></code></a> ([&quot;_&quot;] <a class="reference internal" href="#grammar-token-digit"><code class="xref docutils literal notranslate"><span class="pre">digit</span></code></a>)* | &quot;0&quot;+ ([&quot;_&quot;] &quot;0&quot;)*
<strong id="grammar-token-bininteger">bininteger </strong> ::= &quot;0&quot; (&quot;b&quot; | &quot;B&quot;) ([&quot;_&quot;] <a class="reference internal" href="#grammar-token-bindigit"><code class="xref docutils literal notranslate"><span class="pre">bindigit</span></code></a>)+
<strong id="grammar-token-octinteger">octinteger </strong> ::= &quot;0&quot; (&quot;o&quot; | &quot;O&quot;) ([&quot;_&quot;] <a class="reference internal" href="#grammar-token-octdigit"><code class="xref docutils literal notranslate"><span class="pre">octdigit</span></code></a>)+
<strong id="grammar-token-hexinteger">hexinteger </strong> ::= &quot;0&quot; (&quot;x&quot; | &quot;X&quot;) ([&quot;_&quot;] <a class="reference internal" href="#grammar-token-hexdigit"><code class="xref docutils literal notranslate"><span class="pre">hexdigit</span></code></a>)+
<strong id="grammar-token-nonzerodigit">nonzerodigit</strong> ::= &quot;1&quot;...&quot;9&quot;
<strong id="grammar-token-digit">digit </strong> ::= &quot;0&quot;...&quot;9&quot;
<strong id="grammar-token-bindigit">bindigit </strong> ::= &quot;0&quot; | &quot;1&quot;
<strong id="grammar-token-octdigit">octdigit </strong> ::= &quot;0&quot;...&quot;7&quot;
<strong id="grammar-token-hexdigit">hexdigit </strong> ::= <a class="reference internal" href="#grammar-token-digit"><code class="xref docutils literal notranslate"><span class="pre">digit</span></code></a> | &quot;a&quot;...&quot;f&quot; | &quot;A&quot;...&quot;F&quot;
</pre>
<p>There is no limit for the length of integer literals apart from what can be
stored in available memory.</p>
<p>Underscores are ignored for determining the numeric value of the literal. They
can be used to group digits for enhanced readability. One underscore can occur
between digits, and after base specifiers like <code class="docutils literal notranslate"><span class="pre">0x</span></code>.</p>
<p>Note that leading zeros in a non-zero decimal number are not allowed. This is
for disambiguation with C-style octal literals, which Python used before version
3.0.</p>
<p>Some examples of integer literals:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mi">7</span> <span class="mi">2147483647</span> <span class="mo">0o177</span> <span class="mb">0b100110111</span>
<span class="mi">3</span> <span class="mi">79228162514264337593543950336</span> <span class="mo">0o377</span> <span class="mh">0xdeadbeef</span>
<span class="mi">100_000_000_000</span> <span class="mb">0b_1110_0101</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">Changed in version 3.6: </span>Underscores are now allowed for grouping purposes in literals.</p>
</div>
</div>
<div class="section" id="floating-point-literals">
<span id="floating"></span><span id="index-28"></span><h3>2.4.6. Floating point literals<a class="headerlink" href="#floating-point-literals" title="Permalink to this headline"></a></h3>
<p>Floating point literals are described by the following lexical definitions:</p>
<pre>
<strong id="grammar-token-floatnumber">floatnumber </strong> ::= <a class="reference internal" href="#grammar-token-pointfloat"><code class="xref docutils literal notranslate"><span class="pre">pointfloat</span></code></a> | <a class="reference internal" href="#grammar-token-exponentfloat"><code class="xref docutils literal notranslate"><span class="pre">exponentfloat</span></code></a>
<strong id="grammar-token-pointfloat">pointfloat </strong> ::= [<a class="reference internal" href="#grammar-token-digitpart"><code class="xref docutils literal notranslate"><span class="pre">digitpart</span></code></a>] <a class="reference internal" href="#grammar-token-fraction"><code class="xref docutils literal notranslate"><span class="pre">fraction</span></code></a> | <a class="reference internal" href="#grammar-token-digitpart"><code class="xref docutils literal notranslate"><span class="pre">digitpart</span></code></a> &quot;.&quot;
<strong id="grammar-token-exponentfloat">exponentfloat</strong> ::= (<a class="reference internal" href="#grammar-token-digitpart"><code class="xref docutils literal notranslate"><span class="pre">digitpart</span></code></a> | <a class="reference internal" href="#grammar-token-pointfloat"><code class="xref docutils literal notranslate"><span class="pre">pointfloat</span></code></a>) <a class="reference internal" href="#grammar-token-exponent"><code class="xref docutils literal notranslate"><span class="pre">exponent</span></code></a>
<strong id="grammar-token-digitpart">digitpart </strong> ::= <a class="reference internal" href="#grammar-token-digit"><code class="xref docutils literal notranslate"><span class="pre">digit</span></code></a> ([&quot;_&quot;] <a class="reference internal" href="#grammar-token-digit"><code class="xref docutils literal notranslate"><span class="pre">digit</span></code></a>)*
<strong id="grammar-token-fraction">fraction </strong> ::= &quot;.&quot; <a class="reference internal" href="#grammar-token-digitpart"><code class="xref docutils literal notranslate"><span class="pre">digitpart</span></code></a>
<strong id="grammar-token-exponent">exponent </strong> ::= (&quot;e&quot; | &quot;E&quot;) [&quot;+&quot; | &quot;-&quot;] <a class="reference internal" href="#grammar-token-digitpart"><code class="xref docutils literal notranslate"><span class="pre">digitpart</span></code></a>
</pre>
<p>Note that the integer and exponent parts are always interpreted using radix 10.
For example, <code class="docutils literal notranslate"><span class="pre">077e010</span></code> is legal, and denotes the same number as <code class="docutils literal notranslate"><span class="pre">77e10</span></code>. The
allowed range of floating point literals is implementation-dependent. As in
integer literals, underscores are supported for digit grouping.</p>
<p>Some examples of floating point literals:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mf">3.14</span> <span class="mf">10.</span> <span class="o">.</span><span class="mi">001</span> <span class="mf">1e100</span> <span class="mf">3.14e-10</span> <span class="mf">0e0</span> <span class="mf">3.14_15_93</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">Changed in version 3.6: </span>Underscores are now allowed for grouping purposes in literals.</p>
</div>
</div>
<div class="section" id="imaginary-literals">
<span id="imaginary"></span><span id="index-29"></span><h3>2.4.7. Imaginary literals<a class="headerlink" href="#imaginary-literals" title="Permalink to this headline"></a></h3>
<p>Imaginary literals are described by the following lexical definitions:</p>
<pre>
<strong id="grammar-token-imagnumber">imagnumber</strong> ::= (<a class="reference internal" href="#grammar-token-floatnumber"><code class="xref docutils literal notranslate"><span class="pre">floatnumber</span></code></a> | <a class="reference internal" href="#grammar-token-digitpart"><code class="xref docutils literal notranslate"><span class="pre">digitpart</span></code></a>) (&quot;j&quot; | &quot;J&quot;)
</pre>
<p>An imaginary literal yields a complex number with a real part of 0.0. Complex
numbers are represented as a pair of floating point numbers and have the same
restrictions on their range. To create a complex number with a nonzero real
part, add a floating point number to it, e.g., <code class="docutils literal notranslate"><span class="pre">(3+4j)</span></code>. Some examples of
imaginary literals:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mf">3.14</span><span class="n">j</span> <span class="mf">10.</span><span class="n">j</span> <span class="mi">10</span><span class="n">j</span> <span class="o">.</span><span class="mi">001</span><span class="n">j</span> <span class="mf">1e100j</span> <span class="mf">3.14e-10</span><span class="n">j</span> <span class="mf">3.14_15_93</span><span class="n">j</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="operators">
<span id="id11"></span><h2>2.5. Operators<a class="headerlink" href="#operators" title="Permalink to this headline"></a></h2>
<p id="index-30">The following tokens are operators:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>+ - * ** / // % @
&lt;&lt; &gt;&gt; &amp; | ^ ~
&lt; &gt; &lt;= &gt;= == !=
</pre></div>
</div>
</div>
<div class="section" id="delimiters">
<span id="id12"></span><h2>2.6. Delimiters<a class="headerlink" href="#delimiters" title="Permalink to this headline"></a></h2>
<p id="index-31">The following tokens serve as delimiters in the grammar:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>( ) [ ] { }
, : . ; @ = -&gt;
+= -= *= /= //= %= @=
&amp;= |= ^= &gt;&gt;= &lt;&lt;= **=
</pre></div>
</div>
<p>The period can also occur in floating-point and imaginary literals. A sequence
of three periods has a special meaning as an ellipsis literal. The second half
of the list, the augmented assignment operators, serve lexically as delimiters,
but also perform an operation.</p>
<p>The following printing ASCII characters have special meaning as part of other
tokens or are otherwise significant to the lexical analyzer:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>&#39; &quot; # \
</pre></div>
</div>
<p>The following printing ASCII characters are not used in Python. Their
occurrence outside string literals and comments is an unconditional error:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>$ ? `
</pre></div>
</div>
<p class="rubric">Footnotes</p>
<dl class="footnote brackets">
<dt class="label" id="id13"><span class="brackets"><a class="fn-backref" href="#id10">1</a></span></dt>
<dd><p><a class="reference external" href="http://www.unicode.org/Public/11.0.0/ucd/NameAliases.txt">http://www.unicode.org/Public/11.0.0/ucd/NameAliases.txt</a></p>
</dd>
</dl>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="../contents.html">Table of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">2. Lexical analysis</a><ul>
<li><a class="reference internal" href="#line-structure">2.1. Line structure</a><ul>
<li><a class="reference internal" href="#logical-lines">2.1.1. Logical lines</a></li>
<li><a class="reference internal" href="#physical-lines">2.1.2. Physical lines</a></li>
<li><a class="reference internal" href="#comments">2.1.3. Comments</a></li>
<li><a class="reference internal" href="#encoding-declarations">2.1.4. Encoding declarations</a></li>
<li><a class="reference internal" href="#explicit-line-joining">2.1.5. Explicit line joining</a></li>
<li><a class="reference internal" href="#implicit-line-joining">2.1.6. Implicit line joining</a></li>
<li><a class="reference internal" href="#blank-lines">2.1.7. Blank lines</a></li>
<li><a class="reference internal" href="#indentation">2.1.8. Indentation</a></li>
<li><a class="reference internal" href="#whitespace-between-tokens">2.1.9. Whitespace between tokens</a></li>
</ul>
</li>
<li><a class="reference internal" href="#other-tokens">2.2. Other tokens</a></li>
<li><a class="reference internal" href="#identifiers">2.3. Identifiers and keywords</a><ul>
<li><a class="reference internal" href="#keywords">2.3.1. Keywords</a></li>
<li><a class="reference internal" href="#reserved-classes-of-identifiers">2.3.2. Reserved classes of identifiers</a></li>
</ul>
</li>
<li><a class="reference internal" href="#literals">2.4. Literals</a><ul>
<li><a class="reference internal" href="#string-and-bytes-literals">2.4.1. String and Bytes literals</a></li>
<li><a class="reference internal" href="#string-literal-concatenation">2.4.2. String literal concatenation</a></li>
<li><a class="reference internal" href="#formatted-string-literals">2.4.3. Formatted string literals</a></li>
<li><a class="reference internal" href="#numeric-literals">2.4.4. Numeric literals</a></li>
<li><a class="reference internal" href="#integer-literals">2.4.5. Integer literals</a></li>
<li><a class="reference internal" href="#floating-point-literals">2.4.6. Floating point literals</a></li>
<li><a class="reference internal" href="#imaginary-literals">2.4.7. Imaginary literals</a></li>
</ul>
</li>
<li><a class="reference internal" href="#operators">2.5. Operators</a></li>
<li><a class="reference internal" href="#delimiters">2.6. Delimiters</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="introduction.html"
title="previous chapter">1. Introduction</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="datamodel.html"
title="next chapter">3. Data model</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/reference/lexical_analysis.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="datamodel.html" title="3. Data model"
>next</a> |</li>
<li class="right" >
<a href="introduction.html" title="1. Introduction"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>

View File

@@ -0,0 +1,903 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>7. Simple statements &#8212; Python 3.7.4 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" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="8. Compound statements" href="compound_stmts.html" />
<link rel="prev" title="6. Expressions" href="expressions.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/reference/simple_stmts.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="compound_stmts.html" title="8. Compound statements"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="expressions.html" title="6. Expressions"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="simple-statements">
<span id="simple"></span><h1>7. Simple statements<a class="headerlink" href="#simple-statements" title="Permalink to this headline"></a></h1>
<p id="index-0">A simple statement is comprised within a single logical line. Several simple
statements may occur on a single line separated by semicolons. The syntax for
simple statements is:</p>
<pre>
<strong id="grammar-token-simple-stmt">simple_stmt</strong> ::= <a class="reference internal" href="#grammar-token-expression-stmt"><code class="xref docutils literal notranslate"><span class="pre">expression_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-assert-stmt"><code class="xref docutils literal notranslate"><span class="pre">assert_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-assignment-stmt"><code class="xref docutils literal notranslate"><span class="pre">assignment_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-augmented-assignment-stmt"><code class="xref docutils literal notranslate"><span class="pre">augmented_assignment_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-annotated-assignment-stmt"><code class="xref docutils literal notranslate"><span class="pre">annotated_assignment_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-pass-stmt"><code class="xref docutils literal notranslate"><span class="pre">pass_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-del-stmt"><code class="xref docutils literal notranslate"><span class="pre">del_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-return-stmt"><code class="xref docutils literal notranslate"><span class="pre">return_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-yield-stmt"><code class="xref docutils literal notranslate"><span class="pre">yield_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-raise-stmt"><code class="xref docutils literal notranslate"><span class="pre">raise_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-break-stmt"><code class="xref docutils literal notranslate"><span class="pre">break_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-continue-stmt"><code class="xref docutils literal notranslate"><span class="pre">continue_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-import-stmt"><code class="xref docutils literal notranslate"><span class="pre">import_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-future-stmt"><code class="xref docutils literal notranslate"><span class="pre">future_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-global-stmt"><code class="xref docutils literal notranslate"><span class="pre">global_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-nonlocal-stmt"><code class="xref docutils literal notranslate"><span class="pre">nonlocal_stmt</span></code></a>
</pre>
<div class="section" id="expression-statements">
<span id="exprstmts"></span><h2>7.1. Expression statements<a class="headerlink" href="#expression-statements" title="Permalink to this headline"></a></h2>
<span class="target" id="index-1"></span><p id="index-2">Expression statements are used (mostly interactively) to compute and write a
value, or (usually) to call a procedure (a function that returns no meaningful
result; in Python, procedures return the value <code class="docutils literal notranslate"><span class="pre">None</span></code>). Other uses of
expression statements are allowed and occasionally useful. The syntax for an
expression statement is:</p>
<pre>
<strong id="grammar-token-expression-stmt">expression_stmt</strong> ::= <a class="reference internal" href="expressions.html#grammar-token-starred-expression"><code class="xref docutils literal notranslate"><span class="pre">starred_expression</span></code></a>
</pre>
<p>An expression statement evaluates the expression list (which may be a single
expression).</p>
<p id="index-3">In interactive mode, if the value is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it is converted to a string
using the built-in <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> function and the resulting string is written to
standard output on a line by itself (except if the result is <code class="docutils literal notranslate"><span class="pre">None</span></code>, so that
procedure calls do not cause any output.)</p>
</div>
<div class="section" id="assignment-statements">
<span id="assignment"></span><h2>7.2. Assignment statements<a class="headerlink" href="#assignment-statements" title="Permalink to this headline"></a></h2>
<p id="index-4">Assignment statements are used to (re)bind names to values and to modify
attributes or items of mutable objects:</p>
<pre>
<strong id="grammar-token-assignment-stmt">assignment_stmt</strong> ::= (<a class="reference internal" href="#grammar-token-target-list"><code class="xref docutils literal notranslate"><span class="pre">target_list</span></code></a> &quot;=&quot;)+ (<a class="reference internal" href="expressions.html#grammar-token-starred-expression"><code class="xref docutils literal notranslate"><span class="pre">starred_expression</span></code></a> | <a class="reference internal" href="expressions.html#grammar-token-yield-expression"><code class="xref docutils literal notranslate"><span class="pre">yield_expression</span></code></a>)
<strong id="grammar-token-target-list">target_list </strong> ::= <a class="reference internal" href="#grammar-token-target"><code class="xref docutils literal notranslate"><span class="pre">target</span></code></a> (&quot;,&quot; <a class="reference internal" href="#grammar-token-target"><code class="xref docutils literal notranslate"><span class="pre">target</span></code></a>)* [&quot;,&quot;]
<strong id="grammar-token-target">target </strong> ::= <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>
| &quot;(&quot; [<a class="reference internal" href="#grammar-token-target-list"><code class="xref docutils literal notranslate"><span class="pre">target_list</span></code></a>] &quot;)&quot;
| &quot;[&quot; [<a class="reference internal" href="#grammar-token-target-list"><code class="xref docutils literal notranslate"><span class="pre">target_list</span></code></a>] &quot;]&quot;
| <a class="reference internal" href="expressions.html#grammar-token-attributeref"><code class="xref docutils literal notranslate"><span class="pre">attributeref</span></code></a>
| <a class="reference internal" href="expressions.html#grammar-token-subscription"><code class="xref docutils literal notranslate"><span class="pre">subscription</span></code></a>
| <a class="reference internal" href="expressions.html#grammar-token-slicing"><code class="xref docutils literal notranslate"><span class="pre">slicing</span></code></a>
| &quot;*&quot; <a class="reference internal" href="#grammar-token-target"><code class="xref docutils literal notranslate"><span class="pre">target</span></code></a>
</pre>
<p>(See section <a class="reference internal" href="expressions.html#primaries"><span class="std std-ref">Primaries</span></a> for the syntax definitions for <em>attributeref</em>,
<em>subscription</em>, and <em>slicing</em>.)</p>
<p>An assignment statement evaluates the expression list (remember that this can be
a single expression or a comma-separated list, the latter yielding a tuple) and
assigns the single resulting object to each of the target lists, from left to
right.</p>
<p id="index-5">Assignment is defined recursively depending on the form of the target (list).
When a target is part of a mutable object (an attribute reference, subscription
or slicing), the mutable object must ultimately perform the assignment and
decide about its validity, and may raise an exception if the assignment is
unacceptable. The rules observed by various types and the exceptions raised are
given with the definition of the object types (see section <a class="reference internal" href="datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a>).</p>
<p id="index-6">Assignment of an object to a target list, optionally enclosed in parentheses or
square brackets, is recursively defined as follows.</p>
<ul class="simple">
<li><p>If the target list is a single target with no trailing comma,
optionally in parentheses, the object is assigned to that target.</p></li>
<li><p>Else: The object must be an iterable with the same number of
items as there are targets in the target list, and the items are assigned,
from left to right, to the corresponding targets.</p>
<ul>
<li><p>If the target list contains one target prefixed with an asterisk, called a
“starred” target: The object must be an iterable with at least as many items
as there are targets in the target list, minus one. The first items of the
iterable are assigned, from left to right, to the targets before the starred
target. The final items of the iterable are assigned to the targets after
the starred target. A list of the remaining items in the iterable is then
assigned to the starred target (the list can be empty).</p></li>
<li><p>Else: The object must be an iterable with the same number of items as there
are targets in the target list, and the items are assigned, from left to
right, to the corresponding targets.</p></li>
</ul>
</li>
</ul>
<p>Assignment of an object to a single target is recursively defined as follows.</p>
<ul>
<li><p>If the target is an identifier (name):</p>
<ul class="simple">
<li><p>If the name does not occur in a <a class="reference internal" href="#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> or <a class="reference internal" href="#nonlocal"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></a>
statement in the current code block: the name is bound to the object in the
current local namespace.</p></li>
<li><p>Otherwise: the name is bound to the object in the global namespace or the
outer namespace determined by <a class="reference internal" href="#nonlocal"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></a>, respectively.</p></li>
</ul>
<p id="index-7">The name is rebound if it was already bound. This may cause the reference
count for the object previously bound to the name to reach zero, causing the
object to be deallocated and its destructor (if it has one) to be called.</p>
</li>
<li id="index-8"><p>If the target is an attribute reference: The primary expression in the
reference is evaluated. It should yield an object with assignable attributes;
if this is not the case, <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised. That object is then
asked to assign the assigned object to the given attribute; if it cannot
perform the assignment, it raises an exception (usually but not necessarily
<a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>).</p>
<p id="attr-target-note">Note: If the object is a class instance and the attribute reference occurs on
both sides of the assignment operator, the RHS expression, <code class="docutils literal notranslate"><span class="pre">a.x</span></code> can access
either an instance attribute or (if no instance attribute exists) a class
attribute. The LHS target <code class="docutils literal notranslate"><span class="pre">a.x</span></code> is always set as an instance attribute,
creating it if necessary. Thus, the two occurrences of <code class="docutils literal notranslate"><span class="pre">a.x</span></code> do not
necessarily refer to the same attribute: if the RHS expression refers to a
class attribute, the LHS creates a new instance attribute as the target of the
assignment:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Cls</span><span class="p">:</span>
<span class="n">x</span> <span class="o">=</span> <span class="mi">3</span> <span class="c1"># class variable</span>
<span class="n">inst</span> <span class="o">=</span> <span class="n">Cls</span><span class="p">()</span>
<span class="n">inst</span><span class="o">.</span><span class="n">x</span> <span class="o">=</span> <span class="n">inst</span><span class="o">.</span><span class="n">x</span> <span class="o">+</span> <span class="mi">1</span> <span class="c1"># writes inst.x as 4 leaving Cls.x as 3</span>
</pre></div>
</div>
<p>This description does not necessarily apply to descriptor attributes, such as
properties created with <a class="reference internal" href="../library/functions.html#property" title="property"><code class="xref py py-func docutils literal notranslate"><span class="pre">property()</span></code></a>.</p>
</li>
<li id="index-9"><p>If the target is a subscription: The primary expression in the reference is
evaluated. It should yield either a mutable sequence object (such as a list)
or a mapping object (such as a dictionary). Next, the subscript expression is
evaluated.</p>
<p id="index-10">If the primary is a mutable sequence object (such as a list), the subscript
must yield an integer. If it is negative, the sequences length is added to
it. The resulting value must be a nonnegative integer less than the
sequences length, and the sequence is asked to assign the assigned object to
its item with that index. If the index is out of range, <a class="reference internal" href="../library/exceptions.html#IndexError" title="IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> is
raised (assignment to a subscripted sequence cannot add new items to a list).</p>
<p id="index-11">If the primary is a mapping object (such as a dictionary), the subscript must
have a type compatible with the mappings key type, and the mapping is then
asked to create a key/datum pair which maps the subscript to the assigned
object. This can either replace an existing key/value pair with the same key
value, or insert a new key/value pair (if no key with the same value existed).</p>
<p>For user-defined objects, the <a class="reference internal" href="datamodel.html#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setitem__()</span></code></a> method is called with
appropriate arguments.</p>
</li>
<li id="index-12"><p>If the target is a slicing: The primary expression in the reference is
evaluated. It should yield a mutable sequence object (such as a list). The
assigned object should be a sequence object of the same type. Next, the lower
and upper bound expressions are evaluated, insofar they are present; defaults
are zero and the sequences length. The bounds should evaluate to integers.
If either bound is negative, the sequences length is added to it. The
resulting bounds are clipped to lie between zero and the sequences length,
inclusive. Finally, the sequence object is asked to replace the slice with
the items of the assigned sequence. The length of the slice may be different
from the length of the assigned sequence, thus changing the length of the
target sequence, if the target sequence allows it.</p></li>
</ul>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> In the current implementation, the syntax for targets is taken to be the same
as for expressions, and invalid syntax is rejected during the code generation
phase, causing less detailed error messages.</p>
</div>
<p>Although the definition of assignment implies that overlaps between the
left-hand side and the right-hand side are simultaneous (for example <code class="docutils literal notranslate"><span class="pre">a,</span> <span class="pre">b</span> <span class="pre">=</span>
<span class="pre">b,</span> <span class="pre">a</span></code> swaps two variables), overlaps <em>within</em> the collection of assigned-to
variables occur left-to-right, sometimes resulting in confusion. For instance,
the following program prints <code class="docutils literal notranslate"><span class="pre">[0,</span> <span class="pre">2]</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">]</span>
<span class="n">i</span> <span class="o">=</span> <span class="mi">0</span>
<span class="n">i</span><span class="p">,</span> <span class="n">x</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span> <span class="c1"># i is updated, then x[i] is updated</span>
<span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<dl class="simple">
<dt><span class="target" id="index-13"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3132"><strong>PEP 3132</strong></a> - Extended Iterable Unpacking</dt><dd><p>The specification for the <code class="docutils literal notranslate"><span class="pre">*target</span></code> feature.</p>
</dd>
</dl>
</div>
<div class="section" id="augmented-assignment-statements">
<span id="augassign"></span><h3>7.2.1. Augmented assignment statements<a class="headerlink" href="#augmented-assignment-statements" title="Permalink to this headline"></a></h3>
<p id="index-14">Augmented assignment is the combination, in a single statement, of a binary
operation and an assignment statement:</p>
<pre>
<strong id="grammar-token-augmented-assignment-stmt">augmented_assignment_stmt</strong> ::= <a class="reference internal" href="#grammar-token-augtarget"><code class="xref docutils literal notranslate"><span class="pre">augtarget</span></code></a> <a class="reference internal" href="#grammar-token-augop"><code class="xref docutils literal notranslate"><span class="pre">augop</span></code></a> (<a class="reference internal" href="expressions.html#grammar-token-expression-list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a> | <a class="reference internal" href="expressions.html#grammar-token-yield-expression"><code class="xref docutils literal notranslate"><span class="pre">yield_expression</span></code></a>)
<strong id="grammar-token-augtarget">augtarget </strong> ::= <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> | <a class="reference internal" href="expressions.html#grammar-token-attributeref"><code class="xref docutils literal notranslate"><span class="pre">attributeref</span></code></a> | <a class="reference internal" href="expressions.html#grammar-token-subscription"><code class="xref docutils literal notranslate"><span class="pre">subscription</span></code></a> | <a class="reference internal" href="expressions.html#grammar-token-slicing"><code class="xref docutils literal notranslate"><span class="pre">slicing</span></code></a>
<strong id="grammar-token-augop">augop </strong> ::= &quot;+=&quot; | &quot;-=&quot; | &quot;*=&quot; | &quot;&#64;=&quot; | &quot;/=&quot; | &quot;//=&quot; | &quot;%=&quot; | &quot;**=&quot;
| &quot;&gt;&gt;=&quot; | &quot;&lt;&lt;=&quot; | &quot;&amp;=&quot; | &quot;^=&quot; | &quot;|=&quot;
</pre>
<p>(See section <a class="reference internal" href="expressions.html#primaries"><span class="std std-ref">Primaries</span></a> for the syntax definitions of the last three
symbols.)</p>
<p>An augmented assignment evaluates the target (which, unlike normal assignment
statements, cannot be an unpacking) and the expression list, performs the binary
operation specific to the type of assignment on the two operands, and assigns
the result to the original target. The target is only evaluated once.</p>
<p>An augmented assignment expression like <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">+=</span> <span class="pre">1</span></code> can be rewritten as <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">x</span> <span class="pre">+</span>
<span class="pre">1</span></code> to achieve a similar, but not exactly equal effect. In the augmented
version, <code class="docutils literal notranslate"><span class="pre">x</span></code> is only evaluated once. Also, when possible, the actual operation
is performed <em>in-place</em>, meaning that rather than creating a new object and
assigning that to the target, the old object is modified instead.</p>
<p>Unlike normal assignments, augmented assignments evaluate the left-hand side
<em>before</em> evaluating the right-hand side. For example, <code class="docutils literal notranslate"><span class="pre">a[i]</span> <span class="pre">+=</span> <span class="pre">f(x)</span></code> first
looks-up <code class="docutils literal notranslate"><span class="pre">a[i]</span></code>, then it evaluates <code class="docutils literal notranslate"><span class="pre">f(x)</span></code> and performs the addition, and
lastly, it writes the result back to <code class="docutils literal notranslate"><span class="pre">a[i]</span></code>.</p>
<p>With the exception of assigning to tuples and multiple targets in a single
statement, the assignment done by augmented assignment statements is handled the
same way as normal assignments. Similarly, with the exception of the possible
<em>in-place</em> behavior, the binary operation performed by augmented assignment is
the same as the normal binary operations.</p>
<p>For targets which are attribute references, the same <a class="reference internal" href="#attr-target-note"><span class="std std-ref">caveat about class
and instance attributes</span></a> applies as for regular assignments.</p>
</div>
<div class="section" id="annotated-assignment-statements">
<span id="annassign"></span><h3>7.2.2. Annotated assignment statements<a class="headerlink" href="#annotated-assignment-statements" title="Permalink to this headline"></a></h3>
<p id="index-15"><a class="reference internal" href="../glossary.html#term-variable-annotation"><span class="xref std std-term">Annotation</span></a> assignment is the combination, in a single
statement, of a variable or attribute annotation and an optional assignment statement:</p>
<pre>
<strong id="grammar-token-annotated-assignment-stmt">annotated_assignment_stmt</strong> ::= <a class="reference internal" href="#grammar-token-augtarget"><code class="xref docutils literal notranslate"><span class="pre">augtarget</span></code></a> &quot;:&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> [&quot;=&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>]
</pre>
<p>The difference from normal <a class="reference internal" href="#assignment"><span class="std std-ref">Assignment statements</span></a> is that only single target and
only single right hand side value is allowed.</p>
<p>For simple names as assignment targets, if in class or module scope,
the annotations are evaluated and stored in a special class or module
attribute <code class="xref py py-attr docutils literal notranslate"><span class="pre">__annotations__</span></code>
that is a dictionary mapping from variable names (mangled if private) to
evaluated annotations. This attribute is writable and is automatically
created at the start of class or module body execution, if annotations
are found statically.</p>
<p>For expressions as assignment targets, the annotations are evaluated if
in class or module scope, but not stored.</p>
<p>If a name is annotated in a function scope, then this name is local for
that scope. Annotations are never evaluated and stored in function scopes.</p>
<p>If the right hand side is present, an annotated
assignment performs the actual assignment before evaluating annotations
(where applicable). If the right hand side is not present for an expression
target, then the interpreter evaluates the target except for the last
<a class="reference internal" href="datamodel.html#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setitem__()</span></code></a> or <a class="reference internal" href="datamodel.html#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code></a> call.</p>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<dl class="simple">
<dt><span class="target" id="index-16"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0526"><strong>PEP 526</strong></a> - Syntax for Variable Annotations</dt><dd><p>The proposal that added syntax for annotating the types of variables
(including class variables and instance variables), instead of expressing
them through comments.</p>
</dd>
<dt><span class="target" id="index-17"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0484"><strong>PEP 484</strong></a> - Type hints</dt><dd><p>The proposal that added the <a class="reference internal" href="../library/typing.html#module-typing" title="typing: Support for type hints (see PEP 484)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">typing</span></code></a> module to provide a standard
syntax for type annotations that can be used in static analysis tools and
IDEs.</p>
</dd>
</dl>
</div>
</div>
</div>
<div class="section" id="the-assert-statement">
<span id="assert"></span><h2>7.3. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">assert</span></code> statement<a class="headerlink" href="#the-assert-statement" title="Permalink to this headline"></a></h2>
<p id="index-18">Assert statements are a convenient way to insert debugging assertions into a
program:</p>
<pre>
<strong id="grammar-token-assert-stmt">assert_stmt</strong> ::= &quot;assert&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> [&quot;,&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>]
</pre>
<p>The simple form, <code class="docutils literal notranslate"><span class="pre">assert</span> <span class="pre">expression</span></code>, is equivalent to</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">__debug__</span><span class="p">:</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">expression</span><span class="p">:</span> <span class="k">raise</span> <span class="ne">AssertionError</span>
</pre></div>
</div>
<p>The extended form, <code class="docutils literal notranslate"><span class="pre">assert</span> <span class="pre">expression1,</span> <span class="pre">expression2</span></code>, is equivalent to</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">__debug__</span><span class="p">:</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">expression1</span><span class="p">:</span> <span class="k">raise</span> <span class="ne">AssertionError</span><span class="p">(</span><span class="n">expression2</span><span class="p">)</span>
</pre></div>
</div>
<p id="index-19">These equivalences assume that <a class="reference internal" href="../library/constants.html#__debug__" title="__debug__"><code class="xref py py-const docutils literal notranslate"><span class="pre">__debug__</span></code></a> and <a class="reference internal" href="../library/exceptions.html#AssertionError" title="AssertionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AssertionError</span></code></a> refer to
the built-in variables with those names. In the current implementation, the
built-in variable <a class="reference internal" href="../library/constants.html#__debug__" title="__debug__"><code class="xref py py-const docutils literal notranslate"><span class="pre">__debug__</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code> under normal circumstances,
<code class="docutils literal notranslate"><span class="pre">False</span></code> when optimization is requested (command line option <a class="reference internal" href="../using/cmdline.html#cmdoption-o"><code class="xref std std-option docutils literal notranslate"><span class="pre">-O</span></code></a>). The current
code generator emits no code for an assert statement when optimization is
requested at compile time. Note that it is unnecessary to include the source
code for the expression that failed in the error message; it will be displayed
as part of the stack trace.</p>
<p>Assignments to <a class="reference internal" href="../library/constants.html#__debug__" title="__debug__"><code class="xref py py-const docutils literal notranslate"><span class="pre">__debug__</span></code></a> are illegal. The value for the built-in variable
is determined when the interpreter starts.</p>
</div>
<div class="section" id="the-pass-statement">
<span id="pass"></span><h2>7.4. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">pass</span></code> statement<a class="headerlink" href="#the-pass-statement" title="Permalink to this headline"></a></h2>
<pre id="index-20">
<strong id="grammar-token-pass-stmt">pass_stmt</strong> ::= &quot;pass&quot;
</pre>
<p><a class="reference internal" href="#pass"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">pass</span></code></a> is a null operation — when it is executed, nothing happens.
It is useful as a placeholder when a statement is required syntactically, but no
code needs to be executed, for example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">arg</span><span class="p">):</span> <span class="k">pass</span> <span class="c1"># a function that does nothing (yet)</span>
<span class="k">class</span> <span class="nc">C</span><span class="p">:</span> <span class="k">pass</span> <span class="c1"># a class with no methods (yet)</span>
</pre></div>
</div>
</div>
<div class="section" id="the-del-statement">
<span id="del"></span><h2>7.5. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code> statement<a class="headerlink" href="#the-del-statement" title="Permalink to this headline"></a></h2>
<pre id="index-21">
<strong id="grammar-token-del-stmt">del_stmt</strong> ::= &quot;del&quot; <a class="reference internal" href="#grammar-token-target-list"><code class="xref docutils literal notranslate"><span class="pre">target_list</span></code></a>
</pre>
<p>Deletion is recursively defined very similar to the way assignment is defined.
Rather than spelling it out in full details, here are some hints.</p>
<p>Deletion of a target list recursively deletes each target, from left to right.</p>
<p id="index-22">Deletion of a name removes the binding of that name from the local or global
namespace, depending on whether the name occurs in a <a class="reference internal" href="#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statement
in the same code block. If the name is unbound, a <a class="reference internal" href="../library/exceptions.html#NameError" title="NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a> exception
will be raised.</p>
<p id="index-23">Deletion of attribute references, subscriptions and slicings is passed to the
primary object involved; deletion of a slicing is in general equivalent to
assignment of an empty slice of the right type (but even this is determined by
the sliced object).</p>
<div class="versionchanged">
<p><span class="versionmodified changed">Changed in version 3.2: </span>Previously it was illegal to delete a name from the local namespace if it
occurs as a free variable in a nested block.</p>
</div>
</div>
<div class="section" id="the-return-statement">
<span id="return"></span><h2>7.6. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code> statement<a class="headerlink" href="#the-return-statement" title="Permalink to this headline"></a></h2>
<pre id="index-24">
<strong id="grammar-token-return-stmt">return_stmt</strong> ::= &quot;return&quot; [<a class="reference internal" href="expressions.html#grammar-token-expression-list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a>]
</pre>
<p><a class="reference internal" href="#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> may only occur syntactically nested in a function definition,
not within a nested class definition.</p>
<p>If an expression list is present, it is evaluated, else <code class="docutils literal notranslate"><span class="pre">None</span></code> is substituted.</p>
<p><a class="reference internal" href="#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> leaves the current function call with the expression list (or
<code class="docutils literal notranslate"><span class="pre">None</span></code>) as return value.</p>
<p id="index-25">When <a class="reference internal" href="#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> passes control out of a <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement with a
<a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause, that <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause is executed before
really leaving the function.</p>
<p>In a generator function, the <a class="reference internal" href="#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement indicates that the
generator is done and will cause <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> to be raised. The returned
value (if any) is used as an argument to construct <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> and
becomes the <code class="xref py py-attr docutils literal notranslate"><span class="pre">StopIteration.value</span></code> attribute.</p>
<p>In an asynchronous generator function, an empty <a class="reference internal" href="#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement
indicates that the asynchronous generator is done and will cause
<a class="reference internal" href="../library/exceptions.html#StopAsyncIteration" title="StopAsyncIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopAsyncIteration</span></code></a> to be raised. A non-empty <code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code>
statement is a syntax error in an asynchronous generator function.</p>
</div>
<div class="section" id="the-yield-statement">
<span id="yield"></span><h2>7.7. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code> statement<a class="headerlink" href="#the-yield-statement" title="Permalink to this headline"></a></h2>
<pre id="index-26">
<strong id="grammar-token-yield-stmt">yield_stmt</strong> ::= <a class="reference internal" href="expressions.html#grammar-token-yield-expression"><code class="xref docutils literal notranslate"><span class="pre">yield_expression</span></code></a>
</pre>
<p>A <a class="reference internal" href="#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement is semantically equivalent to a <a class="reference internal" href="expressions.html#yieldexpr"><span class="std std-ref">yield
expression</span></a>. The yield statement can be used to omit the parentheses
that would otherwise be required in the equivalent yield expression
statement. For example, the yield statements</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">yield</span> <span class="o">&lt;</span><span class="n">expr</span><span class="o">&gt;</span>
<span class="k">yield from</span> <span class="o">&lt;</span><span class="n">expr</span><span class="o">&gt;</span>
</pre></div>
</div>
<p>are equivalent to the yield expression statements</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="k">yield</span> <span class="o">&lt;</span><span class="n">expr</span><span class="o">&gt;</span><span class="p">)</span>
<span class="p">(</span><span class="k">yield from</span> <span class="o">&lt;</span><span class="n">expr</span><span class="o">&gt;</span><span class="p">)</span>
</pre></div>
</div>
<p>Yield expressions and statements are only used when defining a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a>
function, and are only used in the body of the generator function. Using yield
in a function definition is sufficient to cause that definition to create a
generator function instead of a normal function.</p>
<p>For full details of <a class="reference internal" href="#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> semantics, refer to the
<a class="reference internal" href="expressions.html#yieldexpr"><span class="std std-ref">Yield expressions</span></a> section.</p>
</div>
<div class="section" id="the-raise-statement">
<span id="raise"></span><h2>7.8. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code> statement<a class="headerlink" href="#the-raise-statement" title="Permalink to this headline"></a></h2>
<pre id="index-27">
<strong id="grammar-token-raise-stmt">raise_stmt</strong> ::= &quot;raise&quot; [<a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> [&quot;from&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>]]
</pre>
<p>If no expressions are present, <a class="reference internal" href="#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> re-raises the last exception
that was active in the current scope. If no exception is active in the current
scope, a <a class="reference internal" href="../library/exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> exception is raised indicating that this is an
error.</p>
<p>Otherwise, <a class="reference internal" href="#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> evaluates the first expression as the exception
object. It must be either a subclass or an instance of <a class="reference internal" href="../library/exceptions.html#BaseException" title="BaseException"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseException</span></code></a>.
If it is a class, the exception instance will be obtained when needed by
instantiating the class with no arguments.</p>
<p>The <em class="dfn">type</em> of the exception is the exception instances class, the
<em class="dfn">value</em> is the instance itself.</p>
<p id="index-28">A traceback object is normally created automatically when an exception is raised
and attached to it as the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__traceback__</span></code> attribute, which is writable.
You can create an exception and set your own traceback in one step using the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">with_traceback()</span></code> exception method (which returns the same exception
instance, with its traceback set to its argument), like so:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">raise</span> <span class="ne">Exception</span><span class="p">(</span><span class="s2">&quot;foo occurred&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">with_traceback</span><span class="p">(</span><span class="n">tracebackobj</span><span class="p">)</span>
</pre></div>
</div>
<p id="index-29">The <code class="docutils literal notranslate"><span class="pre">from</span></code> clause is used for exception chaining: if given, the second
<em>expression</em> must be another exception class or instance, which will then be
attached to the raised exception as the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__cause__</span></code> attribute (which is
writable). If the raised exception is not handled, both exceptions will be
printed:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="mi">1</span> <span class="o">/</span> <span class="mi">0</span><span class="p">)</span>
<span class="gp">... </span><span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">exc</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="s2">&quot;Something bad happened&quot;</span><span class="p">)</span> <span class="kn">from</span> <span class="nn">exc</span>
<span class="gp">...</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">2</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">ZeroDivisionError</span>: <span class="n">division by zero</span>
<span class="go">The above exception was the direct cause of the following exception:</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">4</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">RuntimeError</span>: <span class="n">Something bad happened</span>
</pre></div>
</div>
<p>A similar mechanism works implicitly if an exception is raised inside an
exception handler or a <a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause: the previous exception is then
attached as the new exceptions <code class="xref py py-attr docutils literal notranslate"><span class="pre">__context__</span></code> attribute:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="mi">1</span> <span class="o">/</span> <span class="mi">0</span><span class="p">)</span>
<span class="gp">... </span><span class="k">except</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="s2">&quot;Something bad happened&quot;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">2</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">ZeroDivisionError</span>: <span class="n">division by zero</span>
<span class="go">During handling of the above exception, another exception occurred:</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">4</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">RuntimeError</span>: <span class="n">Something bad happened</span>
</pre></div>
</div>
<p>Exception chaining can be explicitly suppressed by specifying <a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> in
the <code class="docutils literal notranslate"><span class="pre">from</span></code> clause:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="mi">1</span> <span class="o">/</span> <span class="mi">0</span><span class="p">)</span>
<span class="gp">... </span><span class="k">except</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="s2">&quot;Something bad happened&quot;</span><span class="p">)</span> <span class="kn">from</span> <span class="nn">None</span>
<span class="gp">...</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">4</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">RuntimeError</span>: <span class="n">Something bad happened</span>
</pre></div>
</div>
<p>Additional information on exceptions can be found in section <a class="reference internal" href="executionmodel.html#exceptions"><span class="std std-ref">Exceptions</span></a>,
and information about handling exceptions is in section <a class="reference internal" href="compound_stmts.html#try"><span class="std std-ref">The try statement</span></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified changed">Changed in version 3.3: </span><a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> is now permitted as <code class="docutils literal notranslate"><span class="pre">Y</span></code> in <code class="docutils literal notranslate"><span class="pre">raise</span> <span class="pre">X</span> <span class="pre">from</span> <span class="pre">Y</span></code>.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified added">New in version 3.3: </span>The <code class="docutils literal notranslate"><span class="pre">__suppress_context__</span></code> attribute to suppress automatic display of the
exception context.</p>
</div>
</div>
<div class="section" id="the-break-statement">
<span id="break"></span><h2>7.9. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code> statement<a class="headerlink" href="#the-break-statement" title="Permalink to this headline"></a></h2>
<pre id="index-30">
<strong id="grammar-token-break-stmt">break_stmt</strong> ::= &quot;break&quot;
</pre>
<p><a class="reference internal" href="#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> may only occur syntactically nested in a <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> or
<a class="reference internal" href="compound_stmts.html#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> loop, but not nested in a function or class definition within
that loop.</p>
<p id="index-31">It terminates the nearest enclosing loop, skipping the optional <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code>
clause if the loop has one.</p>
<p>If a <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop is terminated by <a class="reference internal" href="#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a>, the loop control
target keeps its current value.</p>
<p id="index-32">When <a class="reference internal" href="#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> passes control out of a <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement with a
<a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause, that <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause is executed before
really leaving the loop.</p>
</div>
<div class="section" id="the-continue-statement">
<span id="continue"></span><h2>7.10. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code> statement<a class="headerlink" href="#the-continue-statement" title="Permalink to this headline"></a></h2>
<pre id="index-33">
<strong id="grammar-token-continue-stmt">continue_stmt</strong> ::= &quot;continue&quot;
</pre>
<p><a class="reference internal" href="#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> may only occur syntactically nested in a <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> or
<a class="reference internal" href="compound_stmts.html#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> loop, but not nested in a function or class definition or
<a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause within that loop. It continues with the next
cycle of the nearest enclosing loop.</p>
<p>When <a class="reference internal" href="#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> passes control out of a <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement with a
<a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause, that <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause is executed before
really starting the next loop cycle.</p>
</div>
<div class="section" id="the-import-statement">
<span id="from"></span><span id="import"></span><h2>7.11. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code> statement<a class="headerlink" href="#the-import-statement" title="Permalink to this headline"></a></h2>
<pre id="index-34">
<strong id="grammar-token-import-stmt">import_stmt </strong> ::= &quot;import&quot; <a class="reference internal" href="#grammar-token-module"><code class="xref docutils literal notranslate"><span class="pre">module</span></code></a> [&quot;as&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>] (&quot;,&quot; <a class="reference internal" href="#grammar-token-module"><code class="xref docutils literal notranslate"><span class="pre">module</span></code></a> [&quot;as&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>])*
| &quot;from&quot; <a class="reference internal" href="#grammar-token-relative-module"><code class="xref docutils literal notranslate"><span class="pre">relative_module</span></code></a> &quot;import&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> [&quot;as&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>]
(&quot;,&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> [&quot;as&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>])*
| &quot;from&quot; <a class="reference internal" href="#grammar-token-relative-module"><code class="xref docutils literal notranslate"><span class="pre">relative_module</span></code></a> &quot;import&quot; &quot;(&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> [&quot;as&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>]
(&quot;,&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> [&quot;as&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>])* [&quot;,&quot;] &quot;)&quot;
| &quot;from&quot; <a class="reference internal" href="#grammar-token-module"><code class="xref docutils literal notranslate"><span class="pre">module</span></code></a> &quot;import&quot; &quot;*&quot;
<strong id="grammar-token-module">module </strong> ::= (<a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> &quot;.&quot;)* <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>
<strong id="grammar-token-relative-module">relative_module</strong> ::= &quot;.&quot;* <a class="reference internal" href="#grammar-token-module"><code class="xref docutils literal notranslate"><span class="pre">module</span></code></a> | &quot;.&quot;+
</pre>
<p>The basic import statement (no <a class="reference internal" href="#from"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">from</span></code></a> clause) is executed in two
steps:</p>
<ol class="arabic simple">
<li><p>find a module, loading and initializing it if necessary</p></li>
<li><p>define a name or names in the local namespace for the scope where
the <a class="reference internal" href="#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement occurs.</p></li>
</ol>
<p>When the statement contains multiple clauses (separated by
commas) the two steps are carried out separately for each clause, just
as though the clauses had been separated out into individual import
statements.</p>
<p>The details of the first step, finding and loading modules are described in
greater detail in the section on the <a class="reference internal" href="import.html#importsystem"><span class="std std-ref">import system</span></a>,
which also describes the various types of packages and modules that can
be imported, as well as all the hooks that can be used to customize
the import system. Note that failures in this step may indicate either
that the module could not be located, <em>or</em> that an error occurred while
initializing the module, which includes execution of the modules code.</p>
<p>If the requested module is retrieved successfully, it will be made
available in the local namespace in one of three ways:</p>
<ul class="simple" id="index-35">
<li><p>If the module name is followed by <code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code>, then the name
following <code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code> is bound directly to the imported module.</p></li>
<li><p>If no other name is specified, and the module being imported is a top
level module, the modules name is bound in the local namespace as a
reference to the imported module</p></li>
<li><p>If the module being imported is <em>not</em> a top level module, then the name
of the top level package that contains the module is bound in the local
namespace as a reference to the top level package. The imported module
must be accessed using its full qualified name rather than directly</p></li>
</ul>
<p id="index-36">The <a class="reference internal" href="#from"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">from</span></code></a> form uses a slightly more complex process:</p>
<ol class="arabic simple">
<li><p>find the module specified in the <a class="reference internal" href="#from"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">from</span></code></a> clause, loading and
initializing it if necessary;</p></li>
<li><p>for each of the identifiers specified in the <a class="reference internal" href="#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> clauses:</p>
<ol class="arabic simple">
<li><p>check if the imported module has an attribute by that name</p></li>
<li><p>if not, attempt to import a submodule with that name and then
check the imported module again for that attribute</p></li>
<li><p>if the attribute is not found, <a class="reference internal" href="../library/exceptions.html#ImportError" title="ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a> is raised.</p></li>
<li><p>otherwise, a reference to that value is stored in the local namespace,
using the name in the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code> clause if it is present,
otherwise using the attribute name</p></li>
</ol>
</li>
</ol>
<p>Examples:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">foo</span> <span class="c1"># foo imported and bound locally</span>
<span class="kn">import</span> <span class="nn">foo.bar.baz</span> <span class="c1"># foo.bar.baz imported, foo bound locally</span>
<span class="kn">import</span> <span class="nn">foo.bar.baz</span> <span class="k">as</span> <span class="nn">fbb</span> <span class="c1"># foo.bar.baz imported and bound as fbb</span>
<span class="kn">from</span> <span class="nn">foo.bar</span> <span class="k">import</span> <span class="n">baz</span> <span class="c1"># foo.bar.baz imported and bound as baz</span>
<span class="kn">from</span> <span class="nn">foo</span> <span class="k">import</span> <span class="n">attr</span> <span class="c1"># foo imported and foo.attr bound as attr</span>
</pre></div>
</div>
<p id="index-37">If the list of identifiers is replaced by a star (<code class="docutils literal notranslate"><span class="pre">'*'</span></code>), all public
names defined in the module are bound in the local namespace for the scope
where the <a class="reference internal" href="#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement occurs.</p>
<p id="index-38">The <em>public names</em> defined by a module are determined by checking the modules
namespace for a variable named <code class="docutils literal notranslate"><span class="pre">__all__</span></code>; if defined, it must be a sequence
of strings which are names defined or imported by that module. The names
given in <code class="docutils literal notranslate"><span class="pre">__all__</span></code> are all considered public and are required to exist. If
<code class="docutils literal notranslate"><span class="pre">__all__</span></code> is not defined, the set of public names includes all names found
in the modules namespace which do not begin with an underscore character
(<code class="docutils literal notranslate"><span class="pre">'_'</span></code>). <code class="docutils literal notranslate"><span class="pre">__all__</span></code> should contain the entire public API. It is intended
to avoid accidentally exporting items that are not part of the API (such as
library modules which were imported and used within the module).</p>
<p>The wild card form of import — <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">module</span> <span class="pre">import</span> <span class="pre">*</span></code> — is only allowed at
the module level. Attempting to use it in class or function definitions will
raise a <a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a>.</p>
<p id="index-39">When specifying what module to import you do not have to specify the absolute
name of the module. When a module or package is contained within another
package it is possible to make a relative import within the same top package
without having to mention the package name. By using leading dots in the
specified module or package after <a class="reference internal" href="#from"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">from</span></code></a> you can specify how high to
traverse up the current package hierarchy without specifying exact names. One
leading dot means the current package where the module making the import
exists. Two dots means up one package level. Three dots is up two levels, etc.
So if you execute <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">.</span> <span class="pre">import</span> <span class="pre">mod</span></code> from a module in the <code class="docutils literal notranslate"><span class="pre">pkg</span></code> package
then you will end up importing <code class="docutils literal notranslate"><span class="pre">pkg.mod</span></code>. If you execute <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">..subpkg2</span>
<span class="pre">import</span> <span class="pre">mod</span></code> from within <code class="docutils literal notranslate"><span class="pre">pkg.subpkg1</span></code> you will import <code class="docutils literal notranslate"><span class="pre">pkg.subpkg2.mod</span></code>.
The specification for relative imports is contained in
the <a class="reference internal" href="import.html#relativeimports"><span class="std std-ref">Package Relative Imports</span></a> section.</p>
<p><a class="reference internal" href="../library/importlib.html#importlib.import_module" title="importlib.import_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">importlib.import_module()</span></code></a> is provided to support applications that
determine dynamically the modules to be loaded.</p>
<div class="section" id="future-statements">
<span id="future"></span><h3>7.11.1. Future statements<a class="headerlink" href="#future-statements" title="Permalink to this headline"></a></h3>
<p id="index-40">A <em class="dfn">future statement</em> is a directive to the compiler that a particular
module should be compiled using syntax or semantics that will be available in a
specified future release of Python where the feature becomes standard.</p>
<p>The future statement is intended to ease migration to future versions of Python
that introduce incompatible changes to the language. It allows use of the new
features on a per-module basis before the release in which the feature becomes
standard.</p>
<pre>
<strong id="grammar-token-future-stmt">future_stmt</strong> ::= &quot;from&quot; &quot;__future__&quot; &quot;import&quot; <a class="reference internal" href="#grammar-token-feature"><code class="xref docutils literal notranslate"><span class="pre">feature</span></code></a> [&quot;as&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>]
(&quot;,&quot; <a class="reference internal" href="#grammar-token-feature"><code class="xref docutils literal notranslate"><span class="pre">feature</span></code></a> [&quot;as&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>])*
| &quot;from&quot; &quot;__future__&quot; &quot;import&quot; &quot;(&quot; <a class="reference internal" href="#grammar-token-feature"><code class="xref docutils literal notranslate"><span class="pre">feature</span></code></a> [&quot;as&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>]
(&quot;,&quot; <a class="reference internal" href="#grammar-token-feature"><code class="xref docutils literal notranslate"><span class="pre">feature</span></code></a> [&quot;as&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>])* [&quot;,&quot;] &quot;)&quot;
<strong id="grammar-token-feature">feature </strong> ::= <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>
</pre>
<p>A future statement must appear near the top of the module. The only lines that
can appear before a future statement are:</p>
<ul class="simple">
<li><p>the module docstring (if any),</p></li>
<li><p>comments,</p></li>
<li><p>blank lines, and</p></li>
<li><p>other future statements.</p></li>
</ul>
<p>The only feature in Python 3.7 that requires using the future statement is
<code class="docutils literal notranslate"><span class="pre">annotations</span></code>.</p>
<p>All historical features enabled by the future statement are still recognized
by Python 3. The list includes <code class="docutils literal notranslate"><span class="pre">absolute_import</span></code>, <code class="docutils literal notranslate"><span class="pre">division</span></code>,
<code class="docutils literal notranslate"><span class="pre">generators</span></code>, <code class="docutils literal notranslate"><span class="pre">generator_stop</span></code>, <code class="docutils literal notranslate"><span class="pre">unicode_literals</span></code>,
<code class="docutils literal notranslate"><span class="pre">print_function</span></code>, <code class="docutils literal notranslate"><span class="pre">nested_scopes</span></code> and <code class="docutils literal notranslate"><span class="pre">with_statement</span></code>. They are
all redundant because they are always enabled, and only kept for
backwards compatibility.</p>
<p>A future statement is recognized and treated specially at compile time: Changes
to the semantics of core constructs are often implemented by generating
different code. It may even be the case that a new feature introduces new
incompatible syntax (such as a new reserved word), in which case the compiler
may need to parse the module differently. Such decisions cannot be pushed off
until runtime.</p>
<p>For any given release, the compiler knows which feature names have been defined,
and raises a compile-time error if a future statement contains a feature not
known to it.</p>
<p>The direct runtime semantics are the same as for any import statement: there is
a standard module <a class="reference internal" href="../library/__future__.html#module-__future__" title="__future__: Future statement definitions"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code></a>, described later, and it will be imported in
the usual way at the time the future statement is executed.</p>
<p>The interesting runtime semantics depend on the specific feature enabled by the
future statement.</p>
<p>Note that there is nothing special about the statement:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">__future__</span> <span class="p">[</span><span class="k">as</span> <span class="n">name</span><span class="p">]</span>
</pre></div>
</div>
<p>That is not a future statement; its an ordinary import statement with no
special semantics or syntax restrictions.</p>
<p>Code compiled by calls to the built-in functions <a class="reference internal" href="../library/functions.html#exec" title="exec"><code class="xref py py-func docutils literal notranslate"><span class="pre">exec()</span></code></a> and <a class="reference internal" href="../library/functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a>
that occur in a module <code class="xref py py-mod docutils literal notranslate"><span class="pre">M</span></code> containing a future statement will, by default,
use the new syntax or semantics associated with the future statement. This can
be controlled by optional arguments to <a class="reference internal" href="../library/functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a> — see the documentation
of that function for details.</p>
<p>A future statement typed at an interactive interpreter prompt will take effect
for the rest of the interpreter session. If an interpreter is started with the
<a class="reference internal" href="../using/cmdline.html#cmdoption-i"><code class="xref std std-option docutils literal notranslate"><span class="pre">-i</span></code></a> option, is passed a script name to execute, and the script includes
a future statement, it will be in effect in the interactive session started
after the script is executed.</p>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<dl class="simple">
<dt><span class="target" id="index-41"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0236"><strong>PEP 236</strong></a> - Back to the __future__</dt><dd><p>The original proposal for the __future__ mechanism.</p>
</dd>
</dl>
</div>
</div>
</div>
<div class="section" id="the-global-statement">
<span id="global"></span><h2>7.12. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code> statement<a class="headerlink" href="#the-global-statement" title="Permalink to this headline"></a></h2>
<pre id="index-42">
<strong id="grammar-token-global-stmt">global_stmt</strong> ::= &quot;global&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> (&quot;,&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>)*
</pre>
<p>The <a class="reference internal" href="#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statement is a declaration which holds for the entire
current code block. It means that the listed identifiers are to be interpreted
as globals. It would be impossible to assign to a global variable without
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code>, although free variables may refer to globals without being
declared global.</p>
<p>Names listed in a <a class="reference internal" href="#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statement must not be used in the same code
block textually preceding that <code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code> statement.</p>
<p>Names listed in a <a class="reference internal" href="#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statement must not be defined as formal
parameters or in a <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop control target, <a class="reference internal" href="compound_stmts.html#class"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">class</span></code></a>
definition, function definition, <a class="reference internal" href="#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement, or variable
annotation.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> The current implementation does not enforce some of these restrictions, but
programs should not abuse this freedom, as future implementations may enforce
them or silently change the meaning of the program.</p>
</div>
<p id="index-43"><strong>Programmers note:</strong> <a class="reference internal" href="#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> is a directive to the parser. It
applies only to code parsed at the same time as the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code> statement.
In particular, a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code> statement contained in a string or code
object supplied to the built-in <a class="reference internal" href="../library/functions.html#exec" title="exec"><code class="xref py py-func docutils literal notranslate"><span class="pre">exec()</span></code></a> function does not affect the code
block <em>containing</em> the function call, and code contained in such a string is
unaffected by <code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code> statements in the code containing the function
call. The same applies to the <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> and <a class="reference internal" href="../library/functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a> functions.</p>
</div>
<div class="section" id="the-nonlocal-statement">
<span id="nonlocal"></span><h2>7.13. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code> statement<a class="headerlink" href="#the-nonlocal-statement" title="Permalink to this headline"></a></h2>
<pre id="index-44">
<strong id="grammar-token-nonlocal-stmt">nonlocal_stmt</strong> ::= &quot;nonlocal&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> (&quot;,&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>)*
</pre>
<p>The <a class="reference internal" href="#nonlocal"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></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"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></a> statement, unlike those listed in a
<a class="reference internal" href="#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></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"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></a> statement must not collide with
pre-existing bindings in the local scope.</p>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<dl class="simple">
<dt><span class="target" id="index-45"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3104"><strong>PEP 3104</strong></a> - Access to Names in Outer Scopes</dt><dd><p>The specification for the <a class="reference internal" href="#nonlocal"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></a> statement.</p>
</dd>
</dl>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="../contents.html">Table of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">7. Simple statements</a><ul>
<li><a class="reference internal" href="#expression-statements">7.1. Expression statements</a></li>
<li><a class="reference internal" href="#assignment-statements">7.2. Assignment statements</a><ul>
<li><a class="reference internal" href="#augmented-assignment-statements">7.2.1. Augmented assignment statements</a></li>
<li><a class="reference internal" href="#annotated-assignment-statements">7.2.2. Annotated assignment statements</a></li>
</ul>
</li>
<li><a class="reference internal" href="#the-assert-statement">7.3. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">assert</span></code> statement</a></li>
<li><a class="reference internal" href="#the-pass-statement">7.4. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">pass</span></code> statement</a></li>
<li><a class="reference internal" href="#the-del-statement">7.5. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code> statement</a></li>
<li><a class="reference internal" href="#the-return-statement">7.6. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code> statement</a></li>
<li><a class="reference internal" href="#the-yield-statement">7.7. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code> statement</a></li>
<li><a class="reference internal" href="#the-raise-statement">7.8. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code> statement</a></li>
<li><a class="reference internal" href="#the-break-statement">7.9. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code> statement</a></li>
<li><a class="reference internal" href="#the-continue-statement">7.10. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code> statement</a></li>
<li><a class="reference internal" href="#the-import-statement">7.11. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code> statement</a><ul>
<li><a class="reference internal" href="#future-statements">7.11.1. Future statements</a></li>
</ul>
</li>
<li><a class="reference internal" href="#the-global-statement">7.12. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code> statement</a></li>
<li><a class="reference internal" href="#the-nonlocal-statement">7.13. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code> statement</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="expressions.html"
title="previous chapter">6. Expressions</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="compound_stmts.html"
title="next chapter">8. Compound statements</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/reference/simple_stmts.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="compound_stmts.html" title="8. Compound statements"
>next</a> |</li>
<li class="right" >
<a href="expressions.html" title="6. Expressions"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>

View File

@@ -0,0 +1,248 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>9. Top-level components &#8212; Python 3.7.4 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" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></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/language_data.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Search within Python 3.7.4 documentation"
href="../_static/opensearch.xml"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="10. Full Grammar specification" href="grammar.html" />
<link rel="prev" title="8. Compound statements" href="compound_stmts.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/reference/toplevel_components.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<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="grammar.html" title="10. Full Grammar specification"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="compound_stmts.html" title="8. Compound statements"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="top-level-components">
<span id="top-level"></span><h1>9. Top-level components<a class="headerlink" href="#top-level-components" title="Permalink to this headline"></a></h1>
<p id="index-0">The Python interpreter can get its input from a number of sources: from a script
passed to it as standard input or as program argument, typed in interactively,
from a module source file, etc. This chapter gives the syntax used in these
cases.</p>
<div class="section" id="complete-python-programs">
<span id="programs"></span><h2>9.1. Complete Python programs<a class="headerlink" href="#complete-python-programs" title="Permalink to this headline"></a></h2>
<span class="target" id="index-1"></span><p id="index-2">While a language specification need not prescribe how the language interpreter
is invoked, it is useful to have a notion of a complete Python program. A
complete Python program is executed in a minimally initialized environment: all
built-in and standard modules are available, but none have been initialized,
except for <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> (various system services), <a class="reference internal" href="../library/builtins.html#module-builtins" title="builtins: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">builtins</span></code></a> (built-in
functions, exceptions and <code class="docutils literal notranslate"><span class="pre">None</span></code>) and <a class="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a>. The latter is used to
provide the local and global namespace for execution of the complete program.</p>
<p>The syntax for a complete Python program is that for file input, described in
the next section.</p>
<p id="index-3">The interpreter may also be invoked in interactive mode; in this case, it does
not read and execute a complete program but reads and executes one statement
(possibly compound) at a time. The initial environment is identical to that of
a complete program; each statement is executed in the namespace of
<a class="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a>.</p>
<p id="index-4">A complete program can be passed to the interpreter
in three forms: with the <a class="reference internal" href="../using/cmdline.html#cmdoption-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">-c</span></code></a> <em>string</em> command line option, as a file
passed as the first command line argument, or as standard input. If the file
or standard input is a tty device, the interpreter enters interactive mode;
otherwise, it executes the file as a complete program.</p>
</div>
<div class="section" id="file-input">
<span id="id1"></span><h2>9.2. File input<a class="headerlink" href="#file-input" title="Permalink to this headline"></a></h2>
<p>All input read from non-interactive files has the same form:</p>
<pre>
<strong id="grammar-token-file-input">file_input</strong> ::= (NEWLINE | <a class="reference internal" href="compound_stmts.html#grammar-token-statement"><code class="xref docutils literal notranslate"><span class="pre">statement</span></code></a>)*
</pre>
<p>This syntax is used in the following situations:</p>
<ul class="simple">
<li><p>when parsing a complete Python program (from a file or from a string);</p></li>
<li><p>when parsing a module;</p></li>
<li><p>when parsing a string passed to the <a class="reference internal" href="../library/functions.html#exec" title="exec"><code class="xref py py-func docutils literal notranslate"><span class="pre">exec()</span></code></a> function;</p></li>
</ul>
</div>
<div class="section" id="interactive-input">
<span id="interactive"></span><h2>9.3. Interactive input<a class="headerlink" href="#interactive-input" title="Permalink to this headline"></a></h2>
<p>Input in interactive mode is parsed using the following grammar:</p>
<pre>
<strong id="grammar-token-interactive-input">interactive_input</strong> ::= [<a class="reference internal" href="compound_stmts.html#grammar-token-stmt-list"><code class="xref docutils literal notranslate"><span class="pre">stmt_list</span></code></a>] NEWLINE | <a class="reference internal" href="compound_stmts.html#grammar-token-compound-stmt"><code class="xref docutils literal notranslate"><span class="pre">compound_stmt</span></code></a> NEWLINE
</pre>
<p>Note that a (top-level) compound statement must be followed by a blank line in
interactive mode; this is needed to help the parser detect the end of the input.</p>
</div>
<div class="section" id="expression-input">
<span id="id2"></span><h2>9.4. Expression input<a class="headerlink" href="#expression-input" title="Permalink to this headline"></a></h2>
<span class="target" id="index-5"></span><p id="index-6"><a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> is used for expression input. It ignores leading whitespace. The
string argument to <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> must have the following form:</p>
<pre>
<strong id="grammar-token-eval-input">eval_input</strong> ::= <a class="reference internal" href="expressions.html#grammar-token-expression-list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a> NEWLINE*
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="../contents.html">Table of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">9. Top-level components</a><ul>
<li><a class="reference internal" href="#complete-python-programs">9.1. Complete Python programs</a></li>
<li><a class="reference internal" href="#file-input">9.2. File input</a></li>
<li><a class="reference internal" href="#interactive-input">9.3. Interactive input</a></li>
<li><a class="reference internal" href="#expression-input">9.4. Expression input</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="compound_stmts.html"
title="previous chapter">8. Compound statements</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="grammar.html"
title="next chapter">10. Full Grammar specification</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Report a Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.7/Doc/reference/toplevel_components.rst"
rel="nofollow">Show Source
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<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="grammar.html" title="10. Full Grammar specification"
>next</a> |</li>
<li class="right" >
<a href="compound_stmts.html" title="8. Compound statements"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li>
<span class="language_switcher_placeholder">en</span>
<span class="version_switcher_placeholder">3.7.4</span>
<a href="../index.html">Documentation </a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> &#187;</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on Jul 13, 2019.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
</div>
</body>
</html>