Kerala Cyber Warriors
KCW Uploader V1.1

Path : /usr/share/doc/python2/html/reference/
File Upload :
Current File : //usr/share/doc/python2/html/reference/compound_stmts.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>7. Compound statements &#8212; Python 2.7.18 documentation</title>
    <link rel="stylesheet" href="../_static/classic.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 2.7.18 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. Top-level components" href="toplevel_components.html" />
    <link rel="prev" title="6. Simple statements" href="simple_stmts.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="file:///usr/share/doc/python2.7/html/reference/compound_stmts.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>
<div id="outdated-warning" style="padding: .5em; text-align: center; background-color: #FFBABA; color: #6A0E0E;">
    This document is for an old version of Python that is <a href="https://devguide.python.org/devcycle/#end-of-life-branches">no longer supported</a>.
    You should install the python3 and python3-doc packages and read the 
    <a href="file:///usr/share/doc/python3-doc/html/reference/compound_stmts.html"> Python documentation for the Python3 version packaged in this release</a>.
</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"
             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="8. Top-level components"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="simple_stmts.html" title="6. 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>
          <a href="../index.html">Python 2.7.18 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> &#187;</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>7. 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.  Function and class
definitions are also syntactically compound statements.</p>
<p id="index-1">Compound statements consist 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 header’s colon, or it
can be one or more indented statements on subsequent lines.  Only the latter
form of suite can contain nested compound statements; the following is illegal,
mostly because it wouldn’t 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-default 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="n">x</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="simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a>
statements are executed:</p>
<div class="highlight-default 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="n">x</span><span class="p">;</span> <span class="nb">print</span> <span class="n">y</span><span class="p">;</span> <span class="nb">print</span> <span class="n">z</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-decorated"><code class="xref docutils literal notranslate"><span class="pre">decorated</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>7.1. The <a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> 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>7.2. The <a class="reference internal" href="#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> 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 <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 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 <a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clause’s 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>7.3. The <a class="reference internal" href="#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> 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 of
ascending indices.  Each item in turn is assigned to the target list using the
standard rules for assignments, and then the suite is executed.  When the items
are exhausted (which is immediately when the sequence is empty), the suite in
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, 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 <a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clause’s 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 <a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clause if there was no next
item.</p>
<p>The suite may assign to the variable(s) in the target list; this does not affect
the next item assigned to it.</p>
<p id="index-8">The target list is not deleted when the loop is finished, but if the sequence is
empty, it will not have been assigned to at all by the loop.  Hint: the built-in
function <a class="reference internal" href="../library/functions.html#range" title="range"><code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code></a> returns a sequence of integers suitable to emulate the
effect of Pascal’s <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">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="first 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="last highlight-default 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>7.4. The <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> 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> ::=  try1_stmt | try2_stmt
<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; | &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;:&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>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>In previous versions of Python, <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> did not work. <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> had to be
nested in <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="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a>.</p>
</div>
<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 <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> 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" 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>When a matching except clause is found, the exception is assigned to the target
specified in that except clause, if present, and the except clause’s 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 id="index-11">Before an except clause’s suite is executed, details about the exception are
assigned to three variables 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: <code class="docutils literal notranslate"><span class="pre">sys.exc_type</span></code> receives
the object identifying the exception; <code class="docutils literal notranslate"><span class="pre">sys.exc_value</span></code> receives the exception’s
parameter; <code class="docutils literal notranslate"><span class="pre">sys.exc_traceback</span></code> receives 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. These details are also available through the <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>
function, which returns a tuple <code class="docutils literal notranslate"><span class="pre">(exc_type,</span> <span class="pre">exc_value,</span> <span class="pre">exc_traceback)</span></code>.  Use
of the corresponding variables is deprecated in favor of this function, since
their use is unsafe in a threaded program.  As of Python 1.5, the variables are
restored to their previous values (before the call) when returning from a
function that handled an exception.</p>
<p id="index-12">The optional <a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> 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 <a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> 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-13">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
<a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clauses.  If an exception occurs in any of the clauses and is
not handled, the exception is temporarily saved. 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 executed.  If there is a saved exception, it is re-raised at the end 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. If the <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause raises another
exception or 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-default 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-14">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 <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="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a>
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 <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> 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
<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 in the <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause will
always be the last one executed:</p>
<div class="highlight-default 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>7.5. The <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement<a class="headerlink" href="#the-with-statement" title="Permalink to this headline">¶</a></h2>
<div class="versionadded" id="index-15">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<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 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; with_item (&quot;,&quot; with_item)* &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 class="first">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 class="first">The context manager’s <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 class="first">The context manager’s <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 class="first">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="first admonition-title">Note</p>
<p class="last">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 class="first">The suite is executed.</p>
</li>
<li><p class="first">The context manager’s <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-default 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-default 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="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In Python 2.5, 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 only allowed when the
<code class="docutils literal notranslate"><span class="pre">with_statement</span></code> feature has been enabled.  It is always enabled in
Python 2.6.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Support for multiple context expressions.</p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-16"></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>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.</dd>
</dl>
</div>
</div>
<div class="section" id="function-definitions">
<span id="def"></span><span id="function"></span><span id="index-17"></span><h2>7.6. Function definitions<a class="headerlink" href="#function-definitions" title="Permalink to this headline">¶</a></h2>
<p id="index-18">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-decorated">decorated     </strong> ::=  decorators (classdef | funcdef)
<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-funcdef">funcdef       </strong> ::=  &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;:&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-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;)*
                    (  &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;,&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;**&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>
                    | <a class="reference internal" href="#grammar-token-defparameter"><code class="xref docutils literal notranslate"><span class="pre">defparameter</span></code></a> [&quot;,&quot;] )
<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-sublist">sublist       </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="#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="#grammar-token-sublist"><code class="xref docutils literal notranslate"><span class="pre">sublist</span></code></a> &quot;)&quot;
<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" href="#id5" id="id2">[2]</a></p>
<p id="index-19">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-default 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 equivalent to:</p>
<div class="highlight-default 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 id="index-20">When one or more top-level <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 parameter’s default value is substituted.  If a
parameter has a default value, all following parameters 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 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-default 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-21">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 dictionary
receiving any excess keyword arguments, defaulting to a new empty dictionary.</p>
<p id="index-22">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 “<a class="reference internal" href="#def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">def</span></code></a>” form is actually more powerful
since it allows the execution of multiple statements.</p>
<p><strong>Programmer’s note:</strong> Functions are first-class objects.  A “<code class="docutils literal notranslate"><span class="pre">def</span></code>” form
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>
<div class="section" id="class-definitions">
<span id="class"></span><h2>7.7. Class definitions<a class="headerlink" href="#class-definitions" title="Permalink to this headline">¶</a></h2>
<p id="index-23">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> ::=  &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-expression-list"><code class="xref docutils literal notranslate"><span class="pre">expression_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.  It first evaluates the
inheritance list, if present.  Each item in the inheritance list should evaluate
to a class object or class type which allows subclassing.  The class’s suite is
then executed in a new execution frame (see section <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 only function definitions.)  When the class’s suite finishes
execution, its execution frame is discarded but its local namespace is
saved. <a class="footnote-reference" 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><strong>Programmer’s note:</strong> Variables defined in the class definition are class
variables; they are shared by all instances.  To create instance variables, they
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
variables are accessible through the notation “<code class="docutils literal notranslate"><span class="pre">self.name</span></code>”, and an instance
variable hides a class variable with the same name when accessed in this way.
Class variables can be used as defaults for instance variables, but using
mutable values there can lead to unexpected results.  For <a class="reference internal" href="../glossary.html#term-new-style-class"><span class="xref std std-term">new-style
class</span></a>es, descriptors can be used to create instance variables with different
implementation details.</p>
<p>Class definitions, like function definitions, 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.  The evaluation rules for the decorator
expressions are the same as for functions.  The result must be a class object,
which is then bound to the class name.</p>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id4" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>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.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id5" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id2">[2]</a></td><td>A string literal appearing as the first statement in the function body is
transformed into the function’s <code class="docutils literal notranslate"><span class="pre">__doc__</span></code> attribute and therefore the
function’s <a class="reference internal" href="../glossary.html#term-docstring"><span class="xref std std-term">docstring</span></a>.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id6" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id3">[3]</a></td><td>A string literal appearing as the first statement in the class body is
transformed into the namespace’s <code class="docutils literal notranslate"><span class="pre">__doc__</span></code> item and therefore the class’s
<a class="reference internal" href="../glossary.html#term-docstring"><span class="xref std std-term">docstring</span></a>.</td></tr>
</tbody>
</table>
</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. Compound statements</a><ul>
<li><a class="reference internal" href="#the-if-statement">7.1. The <code class="docutils literal notranslate"><span class="pre">if</span></code> statement</a></li>
<li><a class="reference internal" href="#the-while-statement">7.2. The <code class="docutils literal notranslate"><span class="pre">while</span></code> statement</a></li>
<li><a class="reference internal" href="#the-for-statement">7.3. The <code class="docutils literal notranslate"><span class="pre">for</span></code> statement</a></li>
<li><a class="reference internal" href="#the-try-statement">7.4. The <code class="docutils literal notranslate"><span class="pre">try</span></code> statement</a></li>
<li><a class="reference internal" href="#the-with-statement">7.5. The <code class="docutils literal notranslate"><span class="pre">with</span></code> statement</a></li>
<li><a class="reference internal" href="#function-definitions">7.6. Function definitions</a></li>
<li><a class="reference internal" href="#class-definitions">7.7. Class definitions</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="simple_stmts.html"
                        title="previous chapter">6. Simple statements</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="toplevel_components.html"
                        title="next chapter">8. Top-level components</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/reference/compound_stmts.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input 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>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </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="8. Top-level components"
             >next</a> |</li>
        <li class="right" >
          <a href="simple_stmts.html" title="6. 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>
          <a href="../index.html">Python 2.7.18 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2024, 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 November 21, 2024.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.8.5.
    </div>

  </body>
</html>

-=[ KCW uplo4d3r c0ded by cJ_n4p573r ]=-
Ⓒ2017 ҠЄГѦLѦ СүѣЄГ ЩѦГГіѺГՏ