py-cvs-2001_07_13 (Rev 1.3) merge
[python/dscho.git] / Doc / ref / ref4.tex
blob2272f3ebcd45eaa14c79ee4ba1d3a8338fd9b9aa
1 \chapter{Execution model \label{execmodel}}
2 \index{execution model}
5 \section{Code blocks, execution frames, and namespaces \label{execframes}}
6 \index{code block}
7 \index{namespace}
8 \indexii{execution}{frame}
10 A \dfn{code block}\indexii{code}{block} is a piece
11 of Python program text that can be executed as a unit, such as a
12 module, a class definition or a function body. Some code blocks (like
13 modules) are normally executed only once, others (like function
14 bodies) may be executed many times. Code blocks may textually contain
15 other code blocks. Code blocks may invoke other code blocks (that may
16 or may not be textually contained in them) as part of their execution,
17 e.g., by invoking (calling) a function.
19 The following are code blocks: A module is a code block. A function
20 body is a code block. A class definition is a code block. Each
21 command typed interactively is a separate code block; a script file (a
22 file given as standard input to the interpreter or specified on the
23 interpreter command line the first argument) is a code block; a script
24 command (a command specified on the interpreter command line with the
25 `\strong{-c}' option) is a code block. The file read by the built-in
26 function \function{execfile()} is a code block. The string argument
27 passed to the built-in function \function{eval()} and to the
28 \keyword{exec} statement is a code block. And finally, the expression
29 read and evaluated by the built-in function \function{input()} is a
30 code block.
32 A code block is executed in an execution frame. An \dfn{execution
33 frame}\indexii{execution}{frame} contains some administrative
34 information (used for debugging), determines where and how execution
35 continues after the code block's execution has completed, and (perhaps
36 most importantly) defines two namespaces, the local and the global
37 namespace, that affect execution of the code block.
39 A \dfn{namespace}\index{namespace} is a mapping from names
40 (identifiers) to objects. A particular namespace may be referenced by
41 more than one execution frame, and from other places as well. Adding
42 a name to a namespace is called \dfn{binding}\indexii{binding}{name} a
43 name (to an object); changing the mapping of a name is called
44 \dfn{rebinding}\indexii{rebinding}{name}; removing a name is
45 \dfn{unbinding}\indexii{unbinding}{name}. Namespaces are functionally
46 equivalent to dictionaries (and often implemented as dictionaries).
48 The \dfn{local namespace}\indexii{local}{namespace} of an execution
49 frame determines the default place where names are defined and
50 searched. The
51 \dfn{global namespace}\indexii{global}{namespace} determines the place
52 where names listed in \keyword{global}\stindex{global} statements are
53 defined and searched, and where names that are not bound anywhere in
54 the current code block are searched.
56 Whether a name is local or global in a code block is determined by
57 static inspection of the source text for the code block: in the
58 absence of \keyword{global} statements, a name that is bound anywhere
59 in the code block is local in the entire code block; all other names
60 are considered global. The \keyword{global} statement forces global
61 interpretation of selected names throughout the code block. The
62 following constructs bind names: formal parameters to functions,
63 \keyword{import} statements, class and function definitions (these
64 bind the class or function name in the defining block), and targets
65 that are identifiers if occurring in an assignment, \keyword{for} loop
66 header, or in the second position of an \keyword{except} clause
67 header. Local names are searched only on the local namespace; global
68 names are searched only in the global and built-in
69 namespace.\footnote{
70 If the code block contains \keyword{exec} statements or the
71 construct ``\samp{from \ldots import *}'', the semantics of local
72 names change: local name lookup first searches the local namespace,
73 then the global namespace and the built-in namespace.}
75 A target occurring in a \keyword{del} statement is also considered bound
76 for this purpose (though the actual semantics are to ``unbind'' the
77 name).
79 When a global name is not found in the global namespace, it is
80 searched in the built-in namespace (which is actually the global
81 namespace of the module
82 \module{__builtin__}\refbimodindex{__builtin__}). The built-in
83 namespace associated with the execution of a code block is actually
84 found by looking up the name \code{__builtins__} in its global
85 namespace; this should be a dictionary or a module (in the latter case
86 its dictionary is used). Normally, the \code{__builtins__} namespace
87 is the dictionary of the built-in module \module{__builtin__} (note:
88 no `s'); if it isn't, restricted
89 execution\indexii{restricted}{execution} mode is in effect. When a
90 name is not found at all, a
91 \exception{NameError}\withsubitem{(built-in
92 exception)}{\ttindex{NameError}} exception is raised.
93 \stindex{from}
94 \stindex{exec}
95 \stindex{global}
97 The following table lists the meaning of the local and global
98 namespace for various types of code blocks. The namespace for a
99 particular module is automatically created when the module is first
100 imported (i.e., when it is loaded). Note that in almost all cases,
101 the global namespace is the namespace of the containing module ---
102 scopes in Python do not nest!
104 \begin{tableiv}{l|l|l|l}{textrm}
105 {Code block type}{Global namespace}{Local namespace}{Notes}
106 \lineiv{Module}
107 {n.s. for this module}
108 {same as global}{}
109 \lineiv{Script (file or command)}
110 {n.s. for \module{__main__}\refbimodindex{__main__}}
111 {same as global}{(1)}
112 \lineiv{Interactive command}
113 {n.s. for \module{__main__}\refbimodindex{__main__}}
114 {same as global}{}
115 \lineiv{Class definition}
116 {global n.s. of containing block}
117 {new n.s.}{}
118 \lineiv{Function body}
119 {global n.s. of containing block}
120 {new n.s.}{(2)}
121 \lineiv{String passed to \keyword{exec} statement}
122 {global n.s. of containing block}
123 {local n.s. of containing block}{(2), (3)}
124 \lineiv{String passed to \function{eval()}}
125 {global n.s. of caller}
126 {local n.s. of caller}{(2), (3)}
127 \lineiv{File read by \function{execfile()}}
128 {global n.s. of caller}
129 {local n.s. of caller}{(2), (3)}
130 \lineiv{Expression read by \function{input()}}
131 {global n.s. of caller}
132 {local n.s. of caller}{}
133 \end{tableiv}
135 Notes:
137 \begin{description}
139 \item[n.s.] means \emph{namespace}
141 \item[(1)] The main module for a script is always called
142 \module{__main__}; ``the filename don't enter into it.''
144 \item[(2)] The global and local namespace for these can be
145 overridden with optional extra arguments.
147 \item[(3)] The \keyword{exec} statement and the \function{eval()} and
148 \function{execfile()} functions have optional arguments to override
149 the global and local namespace. If only one namespace is specified,
150 it is used for both.
152 \end{description}
154 The built-in functions \function{globals()} and \function{locals()} returns a
155 dictionary representing the current global and local namespace,
156 respectively. The effect of modifications to this dictionary on the
157 namespace are undefined.\footnote{
158 The current implementations return the dictionary actually used to
159 implement the namespace, \emph{except} for functions, where the
160 optimizer may cause the local namespace to be implemented
161 differently, and \function{locals()} returns a read-only
162 dictionary.}
165 \section{Exceptions \label{exceptions}}
166 \index{exception}
168 Exceptions are a means of breaking out of the normal flow of control
169 of a code block in order to handle errors or other exceptional
170 conditions. An exception is
171 \emph{raised}\index{raise an exception} at the point where the error
172 is detected; it may be \emph{handled}\index{handle an exception} by
173 the surrounding code block or by any code block that directly or
174 indirectly invoked the code block where the error occurred.
175 \index{exception handler}
176 \index{errors}
177 \index{error handling}
179 The Python interpreter raises an exception when it detects a run-time
180 error (such as division by zero). A Python program can also
181 explicitly raise an exception with the \keyword{raise} statement.
182 Exception handlers are specified with the \keyword{try} ... \keyword{except}
183 statement. The \keyword{try} ... \keyword{finally} statement
184 specifies cleanup code which does not handle the exception, but is
185 executed whether an exception occurred or not in the preceding code.
187 Python uses the ``termination'' \index{termination model}model of
188 error handling: an exception handler can find out what happened and
189 continue execution at an outer level, but it cannot repair the cause
190 of the error and retry the failing operation (except by re-entering
191 the offending piece of code from the top).
193 When an exception is not handled at all, the interpreter terminates
194 execution of the program, or returns to its interactive main loop. In
195 either case, it prints a stack backtrace, except when the exception is
196 \exception{SystemExit}\withsubitem{(built-in
197 exception)}{\ttindex{SystemExit}}.
199 Exceptions are identified by string objects or class instances.
200 Selection of a matching except clause is based on object identity
201 (i.e., two different string objects with the same value represent
202 different exceptions!) For string exceptions, the \keyword{except}
203 clause must reference the same string object. For class exceptions,
204 the \keyword{except} clause must reference the same class or a base
205 class of it.
207 When an exception is raised, an object (maybe \code{None}) is passed
208 as the exception's ``parameter'' or ``value''; this object does not
209 affect the selection of an exception handler, but is passed to the
210 selected exception handler as additional information. For class
211 exceptions, this object must be an instance of the exception class
212 being raised.
214 See also the description of the \keyword{try} statement in section
215 \ref{try} and \keyword{raise} statement in section \ref{raise}.