blob: 2272f3ebcd45eaa14c79ee4ba1d3a8338fd9b9aa [file] [log] [blame]
Fred Drake431f0ce1999-05-13 18:38:11 +00001\chapter{Execution model \label{execmodel}}
Fred Drakef6669171998-05-06 19:52:49 +00002\index{execution model}
3
Fred Drake2829f1c2001-06-23 05:27:20 +00004
Fred Drake431f0ce1999-05-13 18:38:11 +00005\section{Code blocks, execution frames, and namespaces \label{execframes}}
Fred Drakef6669171998-05-06 19:52:49 +00006\index{code block}
Guido van Rossumb18a93b1998-07-23 19:36:00 +00007\index{namespace}
Fred Drake431f0ce1999-05-13 18:38:11 +00008\indexii{execution}{frame}
Fred Drakef6669171998-05-06 19:52:49 +00009
Fred Drake431f0ce1999-05-13 18:38:11 +000010A \dfn{code block}\indexii{code}{block} is a piece
11of Python program text that can be executed as a unit, such as a
12module, a class definition or a function body. Some code blocks (like
13modules) are normally executed only once, others (like function
14bodies) may be executed many times. Code blocks may textually contain
15other code blocks. Code blocks may invoke other code blocks (that may
16or may not be textually contained in them) as part of their execution,
17e.g., by invoking (calling) a function.
Fred Drakef6669171998-05-06 19:52:49 +000018
Guido van Rossumb18a93b1998-07-23 19:36:00 +000019The following are code blocks: A module is a code block. A function
Fred Drakef6669171998-05-06 19:52:49 +000020body is a code block. A class definition is a code block. Each
Guido van Rossumb18a93b1998-07-23 19:36:00 +000021command typed interactively is a separate code block; a script file (a
22file given as standard input to the interpreter or specified on the
23interpreter command line the first argument) is a code block; a script
24command (a command specified on the interpreter command line with the
Fred Drake431f0ce1999-05-13 18:38:11 +000025`\strong{-c}' option) is a code block. The file read by the built-in
Guido van Rossumb18a93b1998-07-23 19:36:00 +000026function \function{execfile()} is a code block. The string argument
27passed to the built-in function \function{eval()} and to the
Jeremy Hyltone7024812001-03-23 14:05:16 +000028\keyword{exec} statement is a code block. And finally, the expression
29read and evaluated by the built-in function \function{input()} is a
30code block.
Fred Drakef6669171998-05-06 19:52:49 +000031
Fred Drakea1cce711998-07-24 22:12:32 +000032A code block is executed in an execution frame. An \dfn{execution
Fred Drake431f0ce1999-05-13 18:38:11 +000033frame}\indexii{execution}{frame} contains some administrative
34information (used for debugging), determines where and how execution
35continues after the code block's execution has completed, and (perhaps
Jeremy Hyltone7024812001-03-23 14:05:16 +000036most importantly) defines two namespaces, the local and the global
37namespace, that affect execution of the code block.
Fred Drakef6669171998-05-06 19:52:49 +000038
Jeremy Hyltone7024812001-03-23 14:05:16 +000039A \dfn{namespace}\index{namespace} is a mapping from names
40(identifiers) to objects. A particular namespace may be referenced by
41more than one execution frame, and from other places as well. Adding
42a name to a namespace is called \dfn{binding}\indexii{binding}{name} a
43name (to an object); changing the mapping of a name is called
44\dfn{rebinding}\indexii{rebinding}{name}; removing a name is
Fred Drake431f0ce1999-05-13 18:38:11 +000045\dfn{unbinding}\indexii{unbinding}{name}. Namespaces are functionally
46equivalent to dictionaries (and often implemented as dictionaries).
Fred Drakef6669171998-05-06 19:52:49 +000047
Jeremy Hyltone7024812001-03-23 14:05:16 +000048The \dfn{local namespace}\indexii{local}{namespace} of an execution
49frame determines the default place where names are defined and
50searched. The
51\dfn{global namespace}\indexii{global}{namespace} determines the place
52where names listed in \keyword{global}\stindex{global} statements are
53defined and searched, and where names that are not bound anywhere in
54the current code block are searched.
Fred Drakef6669171998-05-06 19:52:49 +000055
56Whether a name is local or global in a code block is determined by
57static inspection of the source text for the code block: in the
Jeremy Hyltone7024812001-03-23 14:05:16 +000058absence of \keyword{global} statements, a name that is bound anywhere
59in the code block is local in the entire code block; all other names
60are considered global. The \keyword{global} statement forces global
61interpretation of selected names throughout the code block. The
62following constructs bind names: formal parameters to functions,
Guido van Rossumb18a93b1998-07-23 19:36:00 +000063\keyword{import} statements, class and function definitions (these
64bind the class or function name in the defining block), and targets
65that are identifiers if occurring in an assignment, \keyword{for} loop
66header, or in the second position of an \keyword{except} clause
Jeremy Hyltone7024812001-03-23 14:05:16 +000067header. Local names are searched only on the local namespace; global
68names are searched only in the global and built-in
69namespace.\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.}
Fred Drakef6669171998-05-06 19:52:49 +000074
75A target occurring in a \keyword{del} statement is also considered bound
Jeremy Hyltone7024812001-03-23 14:05:16 +000076for this purpose (though the actual semantics are to ``unbind'' the
77name).
Fred Drakef6669171998-05-06 19:52:49 +000078
Guido van Rossumb18a93b1998-07-23 19:36:00 +000079When a global name is not found in the global namespace, it is
80searched in the built-in namespace (which is actually the global
Jeremy Hyltone7024812001-03-23 14:05:16 +000081namespace of the module
82\module{__builtin__}\refbimodindex{__builtin__}). The built-in
83namespace associated with the execution of a code block is actually
Fred Drakeb9879e12001-05-29 15:44:27 +000084found by looking up the name \code{__builtins__} in its global
Jeremy Hyltone7024812001-03-23 14:05:16 +000085namespace; this should be a dictionary or a module (in the latter case
86its dictionary is used). Normally, the \code{__builtins__} namespace
87is the dictionary of the built-in module \module{__builtin__} (note:
88no `s'); if it isn't, restricted
89execution\indexii{restricted}{execution} mode is in effect. When a
90name is not found at all, a
91\exception{NameError}\withsubitem{(built-in
92exception)}{\ttindex{NameError}} exception is raised.
93\stindex{from}
94\stindex{exec}
95\stindex{global}
Fred Drakef6669171998-05-06 19:52:49 +000096
Jeremy Hyltone7024812001-03-23 14:05:16 +000097The following table lists the meaning of the local and global
98namespace for various types of code blocks. The namespace for a
99particular module is automatically created when the module is first
100imported (i.e., when it is loaded). Note that in almost all cases,
101the global namespace is the namespace of the containing module ---
102scopes in Python do not nest!
Fred Drakef6669171998-05-06 19:52:49 +0000103
Jeremy Hyltone7024812001-03-23 14:05:16 +0000104\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}
134
135Notes:
136
137\begin{description}
138
139\item[n.s.] means \emph{namespace}
140
141\item[(1)] The main module for a script is always called
142\module{__main__}; ``the filename don't enter into it.''
143
144\item[(2)] The global and local namespace for these can be
145overridden with optional extra arguments.
146
147\item[(3)] The \keyword{exec} statement and the \function{eval()} and
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000148\function{execfile()} functions have optional arguments to override
149the global and local namespace. If only one namespace is specified,
150it is used for both.
Fred Drakef6669171998-05-06 19:52:49 +0000151
Jeremy Hyltone7024812001-03-23 14:05:16 +0000152\end{description}
153
154The built-in functions \function{globals()} and \function{locals()} returns a
155dictionary representing the current global and local namespace,
156respectively. The effect of modifications to this dictionary on the
157namespace are undefined.\footnote{
Fred Drake431f0ce1999-05-13 18:38:11 +0000158 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.}
Fred Drakef6669171998-05-06 19:52:49 +0000163
Fred Drake431f0ce1999-05-13 18:38:11 +0000164
165\section{Exceptions \label{exceptions}}
166\index{exception}
Fred Drakef6669171998-05-06 19:52:49 +0000167
168Exceptions are a means of breaking out of the normal flow of control
169of a code block in order to handle errors or other exceptional
Fred Drake431f0ce1999-05-13 18:38:11 +0000170conditions. An exception is
171\emph{raised}\index{raise an exception} at the point where the error
172is detected; it may be \emph{handled}\index{handle an exception} by
173the surrounding code block or by any code block that directly or
174indirectly invoked the code block where the error occurred.
Fred Drakef6669171998-05-06 19:52:49 +0000175\index{exception handler}
176\index{errors}
177\index{error handling}
178
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000179The Python interpreter raises an exception when it detects a run-time
Fred Drakef6669171998-05-06 19:52:49 +0000180error (such as division by zero). A Python program can also
181explicitly raise an exception with the \keyword{raise} statement.
182Exception handlers are specified with the \keyword{try} ... \keyword{except}
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000183statement. The \keyword{try} ... \keyword{finally} statement
184specifies cleanup code which does not handle the exception, but is
185executed whether an exception occurred or not in the preceding code.
Fred Drakef6669171998-05-06 19:52:49 +0000186
Fred Drakee15956b2000-04-03 04:51:13 +0000187Python uses the ``termination'' \index{termination model}model of
188error handling: an exception handler can find out what happened and
189continue execution at an outer level, but it cannot repair the cause
190of the error and retry the failing operation (except by re-entering
191the offending piece of code from the top).
Fred Drakef6669171998-05-06 19:52:49 +0000192
193When an exception is not handled at all, the interpreter terminates
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000194execution of the program, or returns to its interactive main loop. In
195either case, it prints a stack backtrace, except when the exception is
Fred Drake431f0ce1999-05-13 18:38:11 +0000196\exception{SystemExit}\withsubitem{(built-in
197exception)}{\ttindex{SystemExit}}.
Fred Drakef6669171998-05-06 19:52:49 +0000198
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000199Exceptions are identified by string objects or class instances.
200Selection of a matching except clause is based on object identity
201(i.e., two different string objects with the same value represent
202different exceptions!) For string exceptions, the \keyword{except}
203clause must reference the same string object. For class exceptions,
204the \keyword{except} clause must reference the same class or a base
205class of it.
Fred Drakef6669171998-05-06 19:52:49 +0000206
207When an exception is raised, an object (maybe \code{None}) is passed
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000208as the exception's ``parameter'' or ``value''; this object does not
209affect the selection of an exception handler, but is passed to the
210selected exception handler as additional information. For class
211exceptions, this object must be an instance of the exception class
212being raised.
Fred Drakef6669171998-05-06 19:52:49 +0000213
Fred Drakee15956b2000-04-03 04:51:13 +0000214See also the description of the \keyword{try} statement in section
215\ref{try} and \keyword{raise} statement in section \ref{raise}.