blob: 9ab448b5d2826ca872546dce84df752e4dc6465f [file] [log] [blame]
Fred Drakef6669171998-05-06 19:52:49 +00001\chapter{Execution model}
2\index{execution model}
3
4\section{Code blocks, execution frames, and name spaces} \label{execframes}
5\index{code block}
6\indexii{execution}{frame}
7\index{name space}
8
9A {\em code block} is a piece of Python program text that can be
10executed as a unit, such as a module, a class definition or a function
11body. Some code blocks (like modules) are executed only once, others
12(like function bodies) may be executed many times. Code blocks may
13textually contain other code blocks. Code blocks may invoke other
14code blocks (that may or may not be textually contained in them) as
15part of their execution, e.g. by invoking (calling) a function.
16\index{code block}
17\indexii{code}{block}
18
19The following are code blocks: A module is a code block. A function
20body is a code block. A class definition is a code block. Each
21command typed interactively is a separate code block; a script file is
22a code block. The string argument passed to the built-in function
23\function{eval()} and to the \keyword{exec} statement are code blocks.
24And finally, the expression read and evaluated by the built-in
25function \function{input()} is a code block.
26
27A code block is executed in an execution frame. An {\em execution
28frame} contains some administrative information (used for debugging),
29determines where and how execution continues after the code block's
30execution has completed, and (perhaps most importantly) defines two
31name spaces, the local and the global name space, that affect
32execution of the code block.
33\indexii{execution}{frame}
34
35A {\em name space} is a mapping from names (identifiers) to objects.
36A particular name space may be referenced by more than one execution
37frame, and from other places as well. Adding a name to a name space
38is called {\em binding} a name (to an object); changing the mapping of
39a name is called {\em rebinding}; removing a name is {\em unbinding}.
40Name spaces are functionally equivalent to dictionaries.
41\index{name space}
42\indexii{binding}{name}
43\indexii{rebinding}{name}
44\indexii{unbinding}{name}
45
46The {\em local name space} of an execution frame determines the default
47place where names are defined and searched. The {\em global name
48space} determines the place where names listed in \keyword{global}
49statements are defined and searched, and where names that are not
50explicitly bound in the current code block are searched.
51\indexii{local}{name space}
52\indexii{global}{name space}
53\stindex{global}
54
55Whether a name is local or global in a code block is determined by
56static inspection of the source text for the code block: in the
57absence of \keyword{global} statements, a name that is bound anywhere in
58the code block is local in the entire code block; all other names are
59considered global. The \keyword{global} statement forces global
60interpretation of selected names throughout the code block. The
61following constructs bind names: formal parameters, \keyword{import}
62statements, class and function definitions (these bind the class or
63function name), and targets that are identifiers if occurring in an
64assignment, \keyword{for} loop header, or except clause header.
65
66A target occurring in a \keyword{del} statement is also considered bound
67for this purpose (though the actual semantics are to ``unbind'' the
68name).
69
70When a global name is not found in the global name space, it is
71searched in the list of ``built-in'' names (which is actually the
72global name space of the module \module{__builtin__}). When a name is not
73found at all, the \exception{NameError} exception is raised.%
74\footnote{If the code block contains \keyword{exec} statements or the
75construct \samp{from \ldots import *}, the semantics of names not
76explicitly mentioned in a {\tt global} statement change subtly: name
77lookup first searches the local name space, then the global one, then
78the built-in one.}
79\refbimodindex{__builtin__}
80\stindex{from}
81\stindex{exec}
82\stindex{global}
83\withsubitem{(built-in exception)}{\ttindex{NameError}}
84
85The following table lists the meaning of the local and global name
86space for various types of code blocks. The name space for a
87particular module is automatically created when the module is first
88referenced. Note that in almost all cases, the global name space is
89the name space of the containing module --- scopes in Python do not
90nest!
91
92\begin{center}
93\begin{tabular}{|l|l|l|l|}
94\hline
95Code block type & Global name space & Local name space & Notes \\
96\hline
97Module & n.s. for this module & same as global & \\
98Script & n.s. for \module{__main__} & same as global & \\
99Interactive command & n.s. for \module{__main__} & same as global & \\
100Class definition & global n.s. of containing block & new n.s. & \\
101Function body & global n.s. of containing block & new n.s. & (2) \\
102String passed to \keyword{exec} statement
103 & global n.s. of containing block
104 & local n.s. of containing block & (1) \\
105String passed to \function{eval()}
106 & global n.s. of caller & local n.s. of caller & (1) \\
107File read by \function{execfile()}
108 & global n.s. of caller & local n.s. of caller & (1) \\
109Expression read by \function{input()}
110 & global n.s. of caller & local n.s. of caller & \\
111\hline
112\end{tabular}
113\end{center}
114\refbimodindex{__main__}
115
116Notes:
117
118\begin{description}
119
120\item[n.s.] means {\em name space}
121
122\item[(1)] The global and local name space for these can be
123overridden with optional extra arguments.
124
125\item[(2)] The body of lambda forms (see section \ref{lambda}) is
126treated exactly the same as a (nested) function definition. Lambda
127forms have their own name space consisting of their formal arguments.
128\indexii{lambda}{form}
129
130\end{description}
131
132The built-in functions \function{globals()} and \function{locals()} returns a
133dictionary representing the current global and local name space,
134respectively. The effect of modifications to this dictionary on the
135name space are undefined.%
136\footnote{The current implementations return the dictionary actually
137used to implement the name space, {\em except} for functions, where
138the optimizer may cause the local name space to be implemented
139differently, and \function{locals()} returns a read-only dictionary.}
140
141\section{Exceptions}
142
143Exceptions are a means of breaking out of the normal flow of control
144of a code block in order to handle errors or other exceptional
145conditions. An exception is {\em raised} at the point where the error
146is detected; it may be {\em handled} by the surrounding code block or
147by any code block that directly or indirectly invoked the code block
148where the error occurred.
149\index{exception}
150\index{raise an exception}
151\index{handle an exception}
152\index{exception handler}
153\index{errors}
154\index{error handling}
155
156The Python interpreter raises an exception when it detects an run-time
157error (such as division by zero). A Python program can also
158explicitly raise an exception with the \keyword{raise} statement.
159Exception handlers are specified with the \keyword{try} ... \keyword{except}
160statement.
161
162Python uses the ``termination'' model of error handling: an exception
163handler can find out what happened and continue execution at an outer
164level, but it cannot repair the cause of the error and retry the
165failing operation (except by re-entering the the offending piece of
166code from the top).
167
168When an exception is not handled at all, the interpreter terminates
169execution of the program, or returns to its interactive main loop.
170
171Exceptions are identified by string objects or class instances. Two
172different string objects with the same value identify different
173exceptions. An exception can be raised with a class instance. Such
174exceptions are caught by specifying an except clause that has the
175class name (or a base class) as the condition.
176
177When an exception is raised, an object (maybe \code{None}) is passed
178as the exception's ``parameter''; this object does not affect the
179selection of an exception handler, but is passed to the selected
180exception handler as additional information. For exceptions raised
181with a class instance, the instance is passed as the ``parameter''.
182
183For example:
184
185\begin{verbatim}
186>>> class Error:
187... def __init__(self, msg): self.msg = msg
188...
189>>> class SpecificError(Error): pass
190...
191>>> try:
192... raise SpecificError('broken')
193... except Error, obj:
194... print obj.msg
195...
196broken
197\end{verbatim}
198
199See also the description of the \keyword{try} and \keyword{raise}
200statements.