1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
5
<html xmlns="http://www.w3.org/1999/xhtml">
7
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
9
<title>4. Execution model — Python 3.5.1 documentation</title>
11
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
12
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
14
<script type="text/javascript">
15
var DOCUMENTATION_OPTIONS = {
18
COLLAPSE_INDEX: false,
23
<script type="text/javascript" src="../_static/jquery.js"></script>
24
<script type="text/javascript" src="../_static/underscore.js"></script>
25
<script type="text/javascript" src="../_static/doctools.js"></script>
26
<script type="text/javascript" src="../_static/sidebar.js"></script>
27
<link rel="search" type="application/opensearchdescription+xml"
28
title="Search within Python 3.5.1 documentation"
29
href="../_static/opensearch.xml"/>
30
<link rel="author" title="About these documents" href="../about.html" />
31
<link rel="copyright" title="Copyright" href="../copyright.html" />
32
<link rel="top" title="Python 3.5.1 documentation" href="../contents.html" />
33
<link rel="up" title="The Python Language Reference" href="index.html" />
34
<link rel="next" title="5. The import system" href="import.html" />
35
<link rel="prev" title="3. Data model" href="datamodel.html" />
36
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
37
<script type="text/javascript" src="../_static/copybutton.js"></script>
38
<script type="text/javascript" src="../_static/version_switch.js"></script>
43
<body role="document">
44
<div class="related" role="navigation" aria-label="related navigation">
47
<li class="right" style="margin-right: 10px">
48
<a href="../genindex.html" title="General Index"
49
accesskey="I">index</a></li>
51
<a href="../py-modindex.html" title="Python Module Index"
54
<a href="import.html" title="5. The import system"
55
accesskey="N">next</a> |</li>
57
<a href="datamodel.html" title="3. Data model"
58
accesskey="P">previous</a> |</li>
59
<li><img src="../_static/py.png" alt=""
60
style="vertical-align: middle; margin-top: -1px"/></li>
61
<li><a href="https://www.python.org/">Python</a> »</li>
63
<span class="version_switcher_placeholder">3.5.1</span>
64
<a href="../index.html">Documentation </a> »
67
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> »</li>
71
<div class="document">
72
<div class="documentwrapper">
73
<div class="bodywrapper">
74
<div class="body" role="main">
76
<div class="section" id="execution-model">
77
<span id="execmodel"></span><h1>4. Execution model<a class="headerlink" href="#execution-model" title="Permalink to this headline">¶</a></h1>
78
<div class="section" id="structure-of-a-program">
79
<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>
80
<p id="index-1">A Python program is constructed from code blocks.
81
A <em class="dfn">block</em> is a piece of Python program text that is executed as a unit.
82
The following are blocks: a module, a function body, and a class definition.
83
Each command typed interactively is a block. A script file (a file given as
84
standard input to the interpreter or specified as a command line argument to the
85
interpreter) is a code block. A script command (a command specified on the
86
interpreter command line with the ‘<strong>-c</strong>‘ option) is a code block. The string
87
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"><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"><span class="pre">exec()</span></code></a> is a
89
<p id="index-2">A code block is executed in an <em class="dfn">execution frame</em>. A frame contains some
90
administrative information (used for debugging) and determines where and how
91
execution continues after the code block’s execution has completed.</p>
93
<div class="section" id="naming-and-binding">
94
<span id="naming"></span><h2>4.2. Naming and binding<a class="headerlink" href="#naming-and-binding" title="Permalink to this headline">¶</a></h2>
95
<div class="section" id="binding-of-names">
96
<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>
97
<p id="index-4"><em class="dfn">Names</em> refer to objects. Names are introduced by name binding operations.</p>
98
<p id="index-5">The following constructs bind names: formal parameters to functions,
99
<a class="reference internal" href="simple_stmts.html#import"><code class="xref std std-keyword docutils literal"><span class="pre">import</span></code></a> statements, class and function definitions (these bind the
100
class or function name in the defining block), and targets that are identifiers
101
if occurring in an assignment, <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal"><span class="pre">for</span></code></a> loop header, or after
102
<a class="reference internal" href="compound_stmts.html#as"><code class="xref std std-keyword docutils literal"><span class="pre">as</span></code></a> in a <a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal"><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"><span class="pre">except</span></code></a> clause.
103
The <a class="reference internal" href="simple_stmts.html#import"><code class="xref std std-keyword docutils literal"><span class="pre">import</span></code></a> statement
104
of the form <code class="docutils literal"><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
105
module, except those beginning with an underscore. This form may only be used
106
at the module level.</p>
107
<p>A target occurring in a <a class="reference internal" href="simple_stmts.html#del"><code class="xref std std-keyword docutils literal"><span class="pre">del</span></code></a> statement is also considered bound for
108
this purpose (though the actual semantics are to unbind the name).</p>
109
<p>Each assignment or import statement occurs within a block defined by a class or
110
function definition or at the module level (the top-level code block).</p>
111
<p id="index-6">If a name is bound in a block, it is a local variable of that block, unless
112
declared as <a class="reference internal" href="simple_stmts.html#nonlocal"><code class="xref std std-keyword docutils literal"><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"><span class="pre">global</span></code></a>. If a name is bound at
113
the module level, it is a global variable. (The variables of the module code
114
block are local and global.) If a variable is used in a code block but not
115
defined there, it is a <em class="dfn">free variable</em>.</p>
116
<p>Each occurrence of a name in the program text refers to the <em class="dfn">binding</em> of
117
that name established by the following name resolution rules.</p>
119
<div class="section" id="resolution-of-names">
120
<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>
121
<p id="index-7">A <em class="dfn">scope</em> defines the visibility of a name within a block. If a local
122
variable is defined in a block, its scope includes that block. If the
123
definition occurs in a function block, the scope extends to any blocks contained
124
within the defining one, unless a contained block introduces a different binding
126
<p id="index-8">When a name is used in a code block, it is resolved using the nearest enclosing
127
scope. The set of all such scopes visible to a code block is called the block’s
128
<em class="dfn">environment</em>.</p>
129
<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"><span class="pre">NameError</span></code></a> exception is raised.
130
If the current scope is a function scope, and the name refers to a local
131
variable that has not yet been bound to a value at the point where the name is
132
used, an <a class="reference internal" href="../library/exceptions.html#UnboundLocalError" title="UnboundLocalError"><code class="xref py py-exc docutils literal"><span class="pre">UnboundLocalError</span></code></a> exception is raised.
133
<a class="reference internal" href="../library/exceptions.html#UnboundLocalError" title="UnboundLocalError"><code class="xref py py-exc docutils literal"><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"><span class="pre">NameError</span></code></a>.</p>
134
<p>If a name binding operation occurs anywhere within a code block, all uses of the
135
name within the block are treated as references to the current block. This can
136
lead to errors when a name is used within a block before it is bound. This rule
137
is subtle. Python lacks declarations and allows name binding operations to
138
occur anywhere within a code block. The local variables of a code block can be
139
determined by scanning the entire text of the block for name binding operations.</p>
140
<p>If the <a class="reference internal" href="simple_stmts.html#global"><code class="xref std std-keyword docutils literal"><span class="pre">global</span></code></a> statement occurs within a block, all uses of the name
141
specified in the statement refer to the binding of that name in the top-level
142
namespace. Names are resolved in the top-level namespace by searching the
143
global namespace, i.e. the namespace of the module containing the code block,
144
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"><span class="pre">builtins</span></code></a>. The
145
global namespace is searched first. If the name is not found there, the
146
builtins namespace is searched. The <a class="reference internal" href="simple_stmts.html#global"><code class="xref std std-keyword docutils literal"><span class="pre">global</span></code></a> statement must precede
147
all uses of the name.</p>
148
<p>The <a class="reference internal" href="simple_stmts.html#global"><code class="xref std std-keyword docutils literal"><span class="pre">global</span></code></a> statement has the same scope as a name binding operation
149
in the same block. If the nearest enclosing scope for a free variable contains
150
a global statement, the free variable is treated as a global.</p>
151
<p>The <a class="reference internal" href="simple_stmts.html#nonlocal"><code class="xref std std-keyword docutils literal"><span class="pre">nonlocal</span></code></a> statement causes corresponding names to refer
152
to previously bound variables in the nearest enclosing function scope.
153
<a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal"><span class="pre">SyntaxError</span></code></a> is raised at compile time if the given name does not
154
exist in any enclosing function scope.</p>
155
<p id="index-10">The namespace for a module is automatically created the first time a module is
156
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"><span class="pre">__main__</span></code></a>.</p>
157
<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"><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"><span class="pre">eval()</span></code></a> are
158
special in the context of name resolution.
159
A class definition is an executable statement that may use and define names.
160
These references follow the normal rules for name resolution with an exception
161
that unbound local variables are looked up in the global namespace.
162
The namespace of the class definition becomes the attribute dictionary of
163
the class. The scope of names defined in a class block is limited to the
164
class block; it does not extend to the code blocks of methods – this includes
165
comprehensions and generator expressions since they are implemented using a
166
function scope. This means that the following will fail:</p>
167
<div class="highlight-python3"><div class="highlight"><pre><span class="k">class</span> <span class="nc">A</span><span class="p">:</span>
168
<span class="n">a</span> <span class="o">=</span> <span class="mi">42</span>
169
<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>
173
<div class="section" id="builtins-and-restricted-execution">
174
<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>
175
<p id="index-11">The builtins namespace associated with the execution of a code block is actually
176
found by looking up the name <code class="docutils literal"><span class="pre">__builtins__</span></code> in its global namespace; this
177
should be a dictionary or a module (in the latter case the module’s dictionary
178
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"><span class="pre">__main__</span></code></a> module, <code class="docutils literal"><span class="pre">__builtins__</span></code> is
179
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"><span class="pre">builtins</span></code></a>; when in any other module,
180
<code class="docutils literal"><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"><span class="pre">builtins</span></code></a> module
181
itself. <code class="docutils literal"><span class="pre">__builtins__</span></code> can be set to a user-created dictionary to create a
182
weak form of restricted execution.</p>
183
<div class="impl-detail compound">
184
<p><strong>CPython implementation detail:</strong> Users should not touch <code class="docutils literal"><span class="pre">__builtins__</span></code>; it is strictly an implementation
185
detail. Users wanting to override values in the builtins namespace should
186
<a class="reference internal" href="simple_stmts.html#import"><code class="xref std std-keyword docutils literal"><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"><span class="pre">builtins</span></code></a> module and modify its
187
attributes appropriately.</p>
190
<div class="section" id="interaction-with-dynamic-features">
191
<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>
192
<p>Name resolution of free variables occurs at runtime, not at compile time.
193
This means that the following code will print 42:</p>
194
<div class="highlight-python3"><div class="highlight"><pre><span class="n">i</span> <span class="o">=</span> <span class="mi">10</span>
195
<span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
196
<span class="nb">print</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
197
<span class="n">i</span> <span class="o">=</span> <span class="mi">42</span>
198
<span class="n">f</span><span class="p">()</span>
201
<p>There are several cases where Python statements are illegal when used in
202
conjunction with nested scopes that contain free variables.</p>
203
<p>If a variable is referenced in an enclosing scope, it is illegal to delete the
204
name. An error will be reported at compile time.</p>
205
<p>The <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal"><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"><span class="pre">exec()</span></code></a> functions do not have access to the full
206
environment for resolving names. Names may be resolved in the local and global
207
namespaces of the caller. Free variables are not resolved in the nearest
208
enclosing namespace, but in the global namespace. <a class="footnote-reference" 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"><span class="pre">exec()</span></code></a> and
209
<a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal"><span class="pre">eval()</span></code></a> functions have optional arguments to override the global and local
210
namespace. If only one namespace is specified, it is used for both.</p>
213
<div class="section" id="exceptions">
214
<span id="id2"></span><h2>4.3. Exceptions<a class="headerlink" href="#exceptions" title="Permalink to this headline">¶</a></h2>
215
<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
216
block in order to handle errors or other exceptional conditions. An exception
217
is <em>raised</em> at the point where the error is detected; it may be <em>handled</em> by the
218
surrounding code block or by any code block that directly or indirectly invoked
219
the code block where the error occurred.</p>
220
<p>The Python interpreter raises an exception when it detects a run-time error
221
(such as division by zero). A Python program can also explicitly raise an
222
exception with the <a class="reference internal" href="simple_stmts.html#raise"><code class="xref std std-keyword docutils literal"><span class="pre">raise</span></code></a> statement. Exception handlers are specified
223
with the <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal"><span class="pre">try</span></code></a> ... <a class="reference internal" href="compound_stmts.html#except"><code class="xref std std-keyword docutils literal"><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"><span class="pre">finally</span></code></a>
224
clause of such a statement can be used to specify cleanup code which does not
225
handle the exception, but is executed whether an exception occurred or not in
226
the preceding code.</p>
227
<p id="index-14">Python uses the “termination” model of error handling: an exception handler can
228
find out what happened and continue execution at an outer level, but it cannot
229
repair the cause of the error and retry the failing operation (except by
230
re-entering the offending piece of code from the top).</p>
231
<p id="index-15">When an exception is not handled at all, the interpreter terminates execution of
232
the program, or returns to its interactive main loop. In either case, it prints
233
a stack backtrace, except when the exception is <a class="reference internal" href="../library/exceptions.html#SystemExit" title="SystemExit"><code class="xref py py-exc docutils literal"><span class="pre">SystemExit</span></code></a>.</p>
234
<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"><span class="pre">except</span></code></a> clause is
235
selected depending on the class of the instance: it must reference the class of
236
the instance or a base class thereof. The instance can be received by the
237
handler and can carry additional information about the exceptional condition.</p>
238
<div class="admonition note">
239
<p class="first admonition-title">Note</p>
240
<p class="last">Exception messages are not part of the Python API. Their contents may change
241
from one version of Python to the next without warning and should not be
242
relied on by code which will run under multiple versions of the interpreter.</p>
244
<p>See also the description of the <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal"><span class="pre">try</span></code></a> statement in section <a class="reference internal" href="compound_stmts.html#try"><span>The try statement</span></a>
245
and <a class="reference internal" href="simple_stmts.html#raise"><code class="xref std std-keyword docutils literal"><span class="pre">raise</span></code></a> statement in section <a class="reference internal" href="simple_stmts.html#raise"><span>The raise statement</span></a>.</p>
246
<p class="rubric">Footnotes</p>
247
<table class="docutils footnote" frame="void" id="id3" rules="none">
248
<colgroup><col class="label" /><col /></colgroup>
250
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>This limitation occurs because the code that is executed by these operations
251
is not available at the time the module is compiled.</td></tr>
261
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
262
<div class="sphinxsidebarwrapper">
263
<h3><a href="../contents.html">Table Of Contents</a></h3>
265
<li><a class="reference internal" href="#">4. Execution model</a><ul>
266
<li><a class="reference internal" href="#structure-of-a-program">4.1. Structure of a program</a></li>
267
<li><a class="reference internal" href="#naming-and-binding">4.2. Naming and binding</a><ul>
268
<li><a class="reference internal" href="#binding-of-names">4.2.1. Binding of names</a></li>
269
<li><a class="reference internal" href="#resolution-of-names">4.2.2. Resolution of names</a></li>
270
<li><a class="reference internal" href="#builtins-and-restricted-execution">4.2.3. Builtins and restricted execution</a></li>
271
<li><a class="reference internal" href="#interaction-with-dynamic-features">4.2.4. Interaction with dynamic features</a></li>
274
<li><a class="reference internal" href="#exceptions">4.3. Exceptions</a></li>
279
<h4>Previous topic</h4>
280
<p class="topless"><a href="datamodel.html"
281
title="previous chapter">3. Data model</a></p>
283
<p class="topless"><a href="import.html"
284
title="next chapter">5. The import system</a></p>
286
<ul class="this-page-menu">
287
<li><a href="../bugs.html">Report a Bug</a></li>
288
<li><a href="../_sources/reference/executionmodel.txt"
289
rel="nofollow">Show Source</a></li>
292
<div id="searchbox" style="display: none" role="search">
293
<h3>Quick search</h3>
294
<form class="search" action="../search.html" method="get">
295
<input type="text" name="q" />
296
<input type="submit" value="Go" />
297
<input type="hidden" name="check_keywords" value="yes" />
298
<input type="hidden" name="area" value="default" />
300
<p class="searchtip" style="font-size: 90%">
301
Enter search terms or a module, class or function name.
304
<script type="text/javascript">$('#searchbox').show(0);</script>
307
<div class="clearer"></div>
309
<div class="related" role="navigation" aria-label="related navigation">
312
<li class="right" style="margin-right: 10px">
313
<a href="../genindex.html" title="General Index"
316
<a href="../py-modindex.html" title="Python Module Index"
319
<a href="import.html" title="5. The import system"
322
<a href="datamodel.html" title="3. Data model"
324
<li><img src="../_static/py.png" alt=""
325
style="vertical-align: middle; margin-top: -1px"/></li>
326
<li><a href="https://www.python.org/">Python</a> »</li>
328
<span class="version_switcher_placeholder">3.5.1</span>
329
<a href="../index.html">Documentation </a> »
332
<li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> »</li>
336
© <a href="../copyright.html">Copyright</a> 1990-2016, Python Software Foundation.
338
The Python Software Foundation is a non-profit corporation.
339
<a href="https://www.python.org/psf/donations/">Please donate.</a>
341
Last updated on Jan 22, 2016.
342
<a href="../bugs.html">Found a bug</a>?
344
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.3.3.
b'\\ No newline at end of file'