blob: 673fea33d8dfa800fca2b5fbfdc93cdc82261c40 [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 Drake431f0ce1999-05-13 18:38:11 +00004\section{Code blocks, execution frames, and namespaces \label{execframes}}
Fred Drakef6669171998-05-06 19:52:49 +00005\index{code block}
Guido van Rossumb18a93b1998-07-23 19:36:00 +00006\index{namespace}
Fred Drake431f0ce1999-05-13 18:38:11 +00007\indexii{execution}{frame}
Fred Drakef6669171998-05-06 19:52:49 +00008
Fred Drake431f0ce1999-05-13 18:38:11 +00009A \dfn{code block}\indexii{code}{block} is a piece
10of Python program text that can be executed as a unit, such as a
11module, a class definition or a function body. Some code blocks (like
12modules) are normally executed only once, others (like function
13bodies) may be executed many times. Code blocks may textually contain
14other code blocks. Code blocks may invoke other code blocks (that may
15or may not be textually contained in them) as part of their execution,
16e.g., by invoking (calling) a function.
Fred Drakef6669171998-05-06 19:52:49 +000017
Guido van Rossumb18a93b1998-07-23 19:36:00 +000018The following are code blocks: A module is a code block. A function
Fred Drakef6669171998-05-06 19:52:49 +000019body is a code block. A class definition is a code block. Each
Guido van Rossumb18a93b1998-07-23 19:36:00 +000020command typed interactively is a separate code block; a script file (a
21file given as standard input to the interpreter or specified on the
22interpreter command line the first argument) is a code block; a script
23command (a command specified on the interpreter command line with the
Fred Drake431f0ce1999-05-13 18:38:11 +000024`\strong{-c}' option) is a code block. The file read by the built-in
Guido van Rossumb18a93b1998-07-23 19:36:00 +000025function \function{execfile()} is a code block. The string argument
26passed to the built-in function \function{eval()} and to the
27\keyword{exec} statement is a code block. And finally, the expression
28read and evaluated by the built-in function \function{input()} is a
29code block.
Fred Drakef6669171998-05-06 19:52:49 +000030
Fred Drakea1cce711998-07-24 22:12:32 +000031A code block is executed in an execution frame. An \dfn{execution
Fred Drake431f0ce1999-05-13 18:38:11 +000032frame}\indexii{execution}{frame} contains some administrative
33information (used for debugging), determines where and how execution
34continues after the code block's execution has completed, and (perhaps
35most importantly) defines two namespaces, the local and the global
36namespace, that affect execution of the code block.
Fred Drakef6669171998-05-06 19:52:49 +000037
Fred Drake431f0ce1999-05-13 18:38:11 +000038A \dfn{namespace}\index{namespace} is a mapping from names
39(identifiers) to objects. A particular namespace may be referenced by
40more than one execution frame, and from other places as well. Adding
41a name to a namespace is called \dfn{binding}\indexii{binding}{name} a
42name (to an object); changing the mapping of a name is called
43\dfn{rebinding}\indexii{rebinding}{name}; removing a name is
44\dfn{unbinding}\indexii{unbinding}{name}. Namespaces are functionally
45equivalent to dictionaries (and often implemented as dictionaries).
Fred Drakef6669171998-05-06 19:52:49 +000046
Fred Drake431f0ce1999-05-13 18:38:11 +000047The \dfn{local namespace}\indexii{local}{namespace} of an execution
48frame determines the default place where names are defined and
49searched. The
50\dfn{global namespace}\indexii{global}{namespace} determines the place
51where names listed in \keyword{global}\stindex{global} statements are
52defined and searched, and where names that are not bound anywhere in
53the current code block are searched.
Fred Drakef6669171998-05-06 19:52:49 +000054
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
Guido van Rossumb18a93b1998-07-23 19:36:00 +000057absence of \keyword{global} statements, a name that is bound anywhere
58in the code block is local in the entire code block; all other names
59are considered global. The \keyword{global} statement forces global
Fred Drakef6669171998-05-06 19:52:49 +000060interpretation of selected names throughout the code block. The
Guido van Rossumb18a93b1998-07-23 19:36:00 +000061following constructs bind names: formal parameters to functions,
62\keyword{import} statements, class and function definitions (these
63bind the class or function name in the defining block), and targets
64that are identifiers if occurring in an assignment, \keyword{for} loop
65header, or in the second position of an \keyword{except} clause
66header. Local names are searched only on the local namespace; global
Fred Drakeb55ce1e1999-04-05 21:32:52 +000067names are searched only in the global and built-in
68namespace.\footnote{
Fred Drake431f0ce1999-05-13 18:38:11 +000069 If the code block contains \keyword{exec} statements or the
70 construct ``\samp{from \ldots import *}'', the semantics of local
71 names change: local name lookup first searches the local namespace,
72 then the global namespace and the built-in namespace.}
Fred Drakef6669171998-05-06 19:52:49 +000073
74A target occurring in a \keyword{del} statement is also considered bound
75for this purpose (though the actual semantics are to ``unbind'' the
76name).
77
Guido van Rossumb18a93b1998-07-23 19:36:00 +000078When a global name is not found in the global namespace, it is
79searched in the built-in namespace (which is actually the global
Fred Drake431f0ce1999-05-13 18:38:11 +000080namespace of the module
81\module{__builtin__}\refbimodindex{__builtin__}). The built-in
82namespace associated with the execution of a code block is actually
83found by looking up the name \code{__builtins__} is its global
84namespace; this should be a dictionary or a module (in the latter case
85its dictionary is used). Normally, the \code{__builtins__} namespace
86is the dictionary of the built-in module \module{__builtin__} (note:
87no `s'); if it isn't, restricted
88execution\indexii{restricted}{execution} mode is in effect. When a
89name is not found at all, a
90\exception{NameError}\withsubitem{(built-in
91exception)}{\ttindex{NameError}} exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +000092\stindex{from}
93\stindex{exec}
94\stindex{global}
Fred Drakef6669171998-05-06 19:52:49 +000095
Guido van Rossumb18a93b1998-07-23 19:36:00 +000096The following table lists the meaning of the local and global
97namespace for various types of code blocks. The namespace for a
Fred Drakef6669171998-05-06 19:52:49 +000098particular module is automatically created when the module is first
Guido van Rossumb18a93b1998-07-23 19:36:00 +000099imported (i.e., when it is loaded). Note that in almost all cases,
100the global namespace is the namespace of the containing module ---
101scopes in Python do not nest!
Fred Drakef6669171998-05-06 19:52:49 +0000102
Fred Drakedad11321998-10-21 00:26:56 +0000103\begin{tableiv}{l|l|l|l}{textrm}
Fred Drakea1cce711998-07-24 22:12:32 +0000104 {Code block type}{Global namespace}{Local namespace}{Notes}
Fred Drakedad11321998-10-21 00:26:56 +0000105 \lineiv{Module}
106 {n.s. for this module}
Fred Drakea1cce711998-07-24 22:12:32 +0000107 {same as global}{}
Fred Drakedad11321998-10-21 00:26:56 +0000108 \lineiv{Script (file or command)}
Fred Drake431f0ce1999-05-13 18:38:11 +0000109 {n.s. for \module{__main__}\refbimodindex{__main__}}
Fred Drakea1cce711998-07-24 22:12:32 +0000110 {same as global}{(1)}
Fred Drakedad11321998-10-21 00:26:56 +0000111 \lineiv{Interactive command}
Fred Drake431f0ce1999-05-13 18:38:11 +0000112 {n.s. for \module{__main__}\refbimodindex{__main__}}
Fred Drakea1cce711998-07-24 22:12:32 +0000113 {same as global}{}
Fred Drakedad11321998-10-21 00:26:56 +0000114 \lineiv{Class definition}
115 {global n.s. of containing block}
Fred Drakea1cce711998-07-24 22:12:32 +0000116 {new n.s.}{}
Fred Drakedad11321998-10-21 00:26:56 +0000117 \lineiv{Function body}
118 {global n.s. of containing block}
Fred Drakea1cce711998-07-24 22:12:32 +0000119 {new n.s.}{(2)}
Fred Drakedad11321998-10-21 00:26:56 +0000120 \lineiv{String passed to \keyword{exec} statement}
121 {global n.s. of containing block}
Fred Drakea1cce711998-07-24 22:12:32 +0000122 {local n.s. of containing block}{(2), (3)}
Fred Drakedad11321998-10-21 00:26:56 +0000123 \lineiv{String passed to \function{eval()}}
124 {global n.s. of caller}
Fred Drakea1cce711998-07-24 22:12:32 +0000125 {local n.s. of caller}{(2), (3)}
Fred Drakedad11321998-10-21 00:26:56 +0000126 \lineiv{File read by \function{execfile()}}
127 {global n.s. of caller}
Fred Drakea1cce711998-07-24 22:12:32 +0000128 {local n.s. of caller}{(2), (3)}
Fred Drakedad11321998-10-21 00:26:56 +0000129 \lineiv{Expression read by \function{input()}}
130 {global n.s. of caller}
Fred Drakea1cce711998-07-24 22:12:32 +0000131 {local n.s. of caller}{}
132\end{tableiv}
Fred Drakef6669171998-05-06 19:52:49 +0000133
134Notes:
135
136\begin{description}
137
Fred Drakea1cce711998-07-24 22:12:32 +0000138\item[n.s.] means \emph{namespace}
Fred Drakef6669171998-05-06 19:52:49 +0000139
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000140\item[(1)] The main module for a script is always called
141\module{__main__}; ``the filename don't enter into it.''
142
143\item[(2)] The global and local namespace for these can be
Fred Drakef6669171998-05-06 19:52:49 +0000144overridden with optional extra arguments.
145
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000146\item[(3)] The \keyword{exec} statement and the \function{eval()} and
147\function{execfile()} functions have optional arguments to override
148the global and local namespace. If only one namespace is specified,
149it is used for both.
Fred Drakef6669171998-05-06 19:52:49 +0000150
151\end{description}
152
153The built-in functions \function{globals()} and \function{locals()} returns a
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000154dictionary representing the current global and local namespace,
Fred Drakef6669171998-05-06 19:52:49 +0000155respectively. The effect of modifications to this dictionary on the
Fred Drakeb55ce1e1999-04-05 21:32:52 +0000156namespace are undefined.\footnote{
Fred Drake431f0ce1999-05-13 18:38:11 +0000157 The current implementations return the dictionary actually used to
158 implement the namespace, \emph{except} for functions, where the
159 optimizer may cause the local namespace to be implemented
160 differently, and \function{locals()} returns a read-only
161 dictionary.}
Fred Drakef6669171998-05-06 19:52:49 +0000162
Fred Drake431f0ce1999-05-13 18:38:11 +0000163
164\section{Exceptions \label{exceptions}}
165\index{exception}
Fred Drakef6669171998-05-06 19:52:49 +0000166
167Exceptions are a means of breaking out of the normal flow of control
168of a code block in order to handle errors or other exceptional
Fred Drake431f0ce1999-05-13 18:38:11 +0000169conditions. An exception is
170\emph{raised}\index{raise an exception} at the point where the error
171is detected; it may be \emph{handled}\index{handle an exception} by
172the surrounding code block or by any code block that directly or
173indirectly invoked the code block where the error occurred.
Fred Drakef6669171998-05-06 19:52:49 +0000174\index{exception handler}
175\index{errors}
176\index{error handling}
177
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000178The Python interpreter raises an exception when it detects a run-time
Fred Drakef6669171998-05-06 19:52:49 +0000179error (such as division by zero). A Python program can also
180explicitly raise an exception with the \keyword{raise} statement.
181Exception handlers are specified with the \keyword{try} ... \keyword{except}
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000182statement. The \keyword{try} ... \keyword{finally} statement
183specifies cleanup code which does not handle the exception, but is
184executed whether an exception occurred or not in the preceding code.
Fred Drakef6669171998-05-06 19:52:49 +0000185
186Python uses the ``termination'' model of error handling: an exception
187handler can find out what happened and continue execution at an outer
188level, but it cannot repair the cause of the error and retry the
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000189failing operation (except by re-entering the offending piece of
Fred Drakef6669171998-05-06 19:52:49 +0000190code from the top).
191
192When an exception is not handled at all, the interpreter terminates
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000193execution of the program, or returns to its interactive main loop. In
194either case, it prints a stack backtrace, except when the exception is
Fred Drake431f0ce1999-05-13 18:38:11 +0000195\exception{SystemExit}\withsubitem{(built-in
196exception)}{\ttindex{SystemExit}}.
Fred Drakef6669171998-05-06 19:52:49 +0000197
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000198Exceptions are identified by string objects or class instances.
199Selection of a matching except clause is based on object identity
200(i.e., two different string objects with the same value represent
201different exceptions!) For string exceptions, the \keyword{except}
202clause must reference the same string object. For class exceptions,
203the \keyword{except} clause must reference the same class or a base
204class of it.
Fred Drakef6669171998-05-06 19:52:49 +0000205
206When an exception is raised, an object (maybe \code{None}) is passed
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000207as the exception's ``parameter'' or ``value''; this object does not
208affect the selection of an exception handler, but is passed to the
209selected exception handler as additional information. For class
210exceptions, this object must be an instance of the exception class
211being raised.
Fred Drakef6669171998-05-06 19:52:49 +0000212
213See also the description of the \keyword{try} and \keyword{raise}
Fred Drake431f0ce1999-05-13 18:38:11 +0000214statements in chapter \ref{compound}.