blob: 8366a5fcdb90500b3882c122c9bb6777f772be8a [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
Fred Drake667c9e42001-02-02 02:43:18 +000027\keyword{exec}\stindex{exec} statement is a code block. And finally,
28the expression read and evaluated by the built-in function
29\function{input()} is a code 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
Jeremy Hylton0eb10702001-02-01 03:50:59 +000035most importantly) defines the environment in which names are resolved.
Fred Drakef6669171998-05-06 19:52:49 +000036
Jeremy Hylton0eb10702001-02-01 03:50:59 +000037A \dfn{namespace}\indexii{namespace} is a mapping from names
38(identifiers) to objects. An \dfn{environment}\index{environment} is
39a hierarchical collection of the namespaces that are visible to a
40particular code block. Python namespaces are statically scoped in the
41tradition of Algol, but also has \keyword{global} statement that can
42be used to access the top-level namespace on the environment.
43
44Names refers to objects. Names are introduced by name
45\dfn{binding}\indexii{binding}{name} operations. Each occurrence of a name
46in the program text refers to the binding of that name established in
47the innermost function namespace containing the use. Changing the
48mapping of a name to an object is called
49\dfn{rebinding}\indexii{rebinding}{name}; removing a name is
Fred Drake431f0ce1999-05-13 18:38:11 +000050\dfn{unbinding}\indexii{unbinding}{name}. Namespaces are functionally
51equivalent to dictionaries (and often implemented as dictionaries).
Fred Drakef6669171998-05-06 19:52:49 +000052
Jeremy Hylton0eb10702001-02-01 03:50:59 +000053When a name is bound, a mapping is created in the \dfn{local
54namespace}\indexii{local}{namespace} of the execution frame unless the
55name is declared global. If a name binding operation occurs anywhere
56within a code block, all uses of the name within the block are treated
57as references to the local namespace. (Note: This can lead to errors
58when a name is used within a block before it is bound.)
59
60The \dfn{global namespace}\indexii{global}{namespace} determines the
61place where names listed in \keyword{global}\stindex{global}
62statements are defined and searched. The global namespace of a block
63is the namespace of the module in which the block was defined.
64
65If a name is used within a code block, but it is not bound there and
66is not declared global, it is a \dfn{free variable}
67\indexii{free}{variable}. A free variable is resolved using the
68nearest enclosing function block that has a binding for the name. If
69no such block exists, the name is resolved in the global namespace.
70
71When a name is not found at all, a
72\exception{NameError}\withsubitem{(built-in
73exception)}{\ttindex{NameError}} exception is raised.
74
75The local namespace of a class definition becomes the attribute
76dictionary of the class. If a block is contained within a class
77definition, the name bindings that occur in the containing class block
78are not visible to enclosed blocks.
79
80The following constructs bind names: formal parameters to functions,
81\keyword{import} statements, class and function definitions (these bind
82the class or function name in the defining block), and identifiers
83occurring as the target of an assignment, in a \keyword{for} loop header
84(including list comprehensions), or in the second position of an
85\keyword{except} clause.
Fred Drakef6669171998-05-06 19:52:49 +000086
87Whether a name is local or global in a code block is determined by
88static inspection of the source text for the code block: in the
Fred Drake667c9e42001-02-02 02:43:18 +000089absence of \keyword{global}\stindex{global} statements, a name that is
90bound anywhere in the code block is local in the entire code block;
91all other names are considered global. The \keyword{global} statement
92forces global interpretation of selected names throughout the code
93block.
Jeremy Hylton0eb10702001-02-01 03:50:59 +000094
95The following constructs bind names: formal parameters to functions,
Guido van Rossumb18a93b1998-07-23 19:36:00 +000096\keyword{import} statements, class and function definitions (these
97bind the class or function name in the defining block), and targets
98that are identifiers if occurring in an assignment, \keyword{for} loop
99header, or in the second position of an \keyword{except} clause
Jeremy Hylton0eb10702001-02-01 03:50:59 +0000100header. The \keyword{import} statement of the form ``\samp{from
Fred Drake667c9e42001-02-02 02:43:18 +0000101\ldots import *}''\stindex{from} binds all names defined in the
102imported module, except those beginning with an underscore. This form
103may only be used at the module level.
Fred Drakef6669171998-05-06 19:52:49 +0000104
105A target occurring in a \keyword{del} statement is also considered bound
Jeremy Hylton0eb10702001-02-01 03:50:59 +0000106for this purpose (though the actual semantics are to unbind the
107name). It is illegal to unbind a name that is referenced by an
108enclosing scope; the compiler will report a \exception{SyntaxError}.
Fred Drakef6669171998-05-06 19:52:49 +0000109
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000110When a global name is not found in the global namespace, it is
111searched in the built-in namespace (which is actually the global
Jeremy Hylton0eb10702001-02-01 03:50:59 +0000112namespace of the module \module{__builtin__}\refbimodindex{__builtin__}).
113The built-in namespace associated with the execution of a code block
Fred Drake667c9e42001-02-02 02:43:18 +0000114is actually found by looking up the name \code{__builtins__} in its
Jeremy Hylton0eb10702001-02-01 03:50:59 +0000115global namespace; this should be a dictionary or a module (in the
Fred Drake667c9e42001-02-02 02:43:18 +0000116latter case the module's dictionary is used). Normally, the
Jeremy Hylton0eb10702001-02-01 03:50:59 +0000117\code{__builtins__} namespace is the dictionary of the built-in module
118\module{__builtin__} (note: no `s'). If it isn't, restricted
119execution\indexii{restricted}{execution} mode is in effect.
Fred Drakef6669171998-05-06 19:52:49 +0000120
Jeremy Hylton0eb10702001-02-01 03:50:59 +0000121The namespace for a module is automatically created the first time a
122module is imported. The main module for a script is always called
123\module{__main__}\refbimodindex{__main__}.
Fred Drakef6669171998-05-06 19:52:49 +0000124
Jeremy Hylton0eb10702001-02-01 03:50:59 +0000125The \function{eval()}, \function{execfile()}, and \function{input()}
126functions and the \keyword{exec} statement do not have access to the
127full environment for resolving names. Names may be resolved in the
128local and global namespaces of the caller. Free variables are not
129resolved in the nearest enclosing namespaces, but in the global
130namespace.\footnote{This limitation occurs because the code that is
131 executed by these operations is not available at the time the
132 module is compiled.}
133The \keyword{exec} statement and the \function{eval()} and
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000134\function{execfile()} functions have optional arguments to override
135the global and local namespace. If only one namespace is specified,
136it is used for both.
Fred Drakef6669171998-05-06 19:52:49 +0000137
Jeremy Hylton0eb10702001-02-01 03:50:59 +0000138The built-in functions \function{globals()} and \function{locals()}
139each return a dictionary, representing the current global and local
140namespace respectively. The effect of modifications to these
141dictionaries on the namespace are undefined.\footnote{
Fred Drake431f0ce1999-05-13 18:38:11 +0000142 The current implementations return the dictionary actually used to
143 implement the namespace, \emph{except} for functions, where the
144 optimizer may cause the local namespace to be implemented
145 differently, and \function{locals()} returns a read-only
146 dictionary.}
Fred Drakef6669171998-05-06 19:52:49 +0000147
Fred Drake431f0ce1999-05-13 18:38:11 +0000148
149\section{Exceptions \label{exceptions}}
150\index{exception}
Fred Drakef6669171998-05-06 19:52:49 +0000151
152Exceptions are a means of breaking out of the normal flow of control
153of a code block in order to handle errors or other exceptional
Fred Drake431f0ce1999-05-13 18:38:11 +0000154conditions. An exception is
155\emph{raised}\index{raise an exception} at the point where the error
156is detected; it may be \emph{handled}\index{handle an exception} by
157the surrounding code block or by any code block that directly or
158indirectly invoked the code block where the error occurred.
Fred Drakef6669171998-05-06 19:52:49 +0000159\index{exception handler}
160\index{errors}
161\index{error handling}
162
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000163The Python interpreter raises an exception when it detects a run-time
Fred Drakef6669171998-05-06 19:52:49 +0000164error (such as division by zero). A Python program can also
165explicitly raise an exception with the \keyword{raise} statement.
166Exception handlers are specified with the \keyword{try} ... \keyword{except}
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000167statement. The \keyword{try} ... \keyword{finally} statement
168specifies cleanup code which does not handle the exception, but is
169executed whether an exception occurred or not in the preceding code.
Fred Drakef6669171998-05-06 19:52:49 +0000170
Fred Drakee15956b2000-04-03 04:51:13 +0000171Python uses the ``termination'' \index{termination model}model of
172error handling: an exception handler can find out what happened and
173continue execution at an outer level, but it cannot repair the cause
174of the error and retry the failing operation (except by re-entering
175the offending piece of code from the top).
Fred Drakef6669171998-05-06 19:52:49 +0000176
177When an exception is not handled at all, the interpreter terminates
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000178execution of the program, or returns to its interactive main loop. In
179either case, it prints a stack backtrace, except when the exception is
Fred Drake431f0ce1999-05-13 18:38:11 +0000180\exception{SystemExit}\withsubitem{(built-in
181exception)}{\ttindex{SystemExit}}.
Fred Drakef6669171998-05-06 19:52:49 +0000182
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000183Exceptions are identified by string objects or class instances.
184Selection of a matching except clause is based on object identity
185(i.e., two different string objects with the same value represent
186different exceptions!) For string exceptions, the \keyword{except}
187clause must reference the same string object. For class exceptions,
188the \keyword{except} clause must reference the same class or a base
189class of it.
Fred Drakef6669171998-05-06 19:52:49 +0000190
191When an exception is raised, an object (maybe \code{None}) is passed
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000192as the exception's ``parameter'' or ``value''; this object does not
193affect the selection of an exception handler, but is passed to the
194selected exception handler as additional information. For class
195exceptions, this object must be an instance of the exception class
196being raised.
Fred Drakef6669171998-05-06 19:52:49 +0000197
Fred Drakee15956b2000-04-03 04:51:13 +0000198See also the description of the \keyword{try} statement in section
199\ref{try} and \keyword{raise} statement in section \ref{raise}.