blob: 16a1a8d02c8caa3b44f16e05ad12ccd6f0f5aec9 [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
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
Guido van Rossumb18a93b1998-07-23 19:36:00 +000089absence of \keyword{global} statements, a name that is bound anywhere
90in the code block is local in the entire code block; all other names
91are considered global. The \keyword{global} statement forces global
Jeremy Hylton0eb10702001-02-01 03:50:59 +000092interpretation of selected names throughout the code block.
93
94The following constructs bind names: formal parameters to functions,
Guido van Rossumb18a93b1998-07-23 19:36:00 +000095\keyword{import} statements, class and function definitions (these
96bind the class or function name in the defining block), and targets
97that are identifiers if occurring in an assignment, \keyword{for} loop
98header, or in the second position of an \keyword{except} clause
Jeremy Hylton0eb10702001-02-01 03:50:59 +000099header. The \keyword{import} statement of the form ``\samp{from
100\ldots import *}'' binds all names defined in the imported module,
101except those beginning with an underscore. This form may only be used
102at the module level.
Fred Drakef6669171998-05-06 19:52:49 +0000103
104A target occurring in a \keyword{del} statement is also considered bound
Jeremy Hylton0eb10702001-02-01 03:50:59 +0000105for this purpose (though the actual semantics are to unbind the
106name). It is illegal to unbind a name that is referenced by an
107enclosing scope; the compiler will report a \exception{SyntaxError}.
Fred Drakef6669171998-05-06 19:52:49 +0000108
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000109When a global name is not found in the global namespace, it is
110searched in the built-in namespace (which is actually the global
Jeremy Hylton0eb10702001-02-01 03:50:59 +0000111namespace of the module \module{__builtin__}\refbimodindex{__builtin__}).
112The built-in namespace associated with the execution of a code block
113is actually found by looking up the name \code{__builtins__} is its
114global namespace; this should be a dictionary or a module (in the
115latter case its dictionary is used). Normally, the
116\code{__builtins__} namespace is the dictionary of the built-in module
117\module{__builtin__} (note: no `s'). If it isn't, restricted
118execution\indexii{restricted}{execution} mode is in effect.
Fred Drakef6669171998-05-06 19:52:49 +0000119\stindex{from}
120\stindex{exec}
121\stindex{global}
Fred Drakef6669171998-05-06 19:52:49 +0000122
Jeremy Hylton0eb10702001-02-01 03:50:59 +0000123The namespace for a module is automatically created the first time a
124module is imported. The main module for a script is always called
125\module{__main__}\refbimodindex{__main__}.
Fred Drakef6669171998-05-06 19:52:49 +0000126
Jeremy Hylton0eb10702001-02-01 03:50:59 +0000127The \function{eval()}, \function{execfile()}, and \function{input()}
128functions and the \keyword{exec} statement do not have access to the
129full environment for resolving names. Names may be resolved in the
130local and global namespaces of the caller. Free variables are not
131resolved in the nearest enclosing namespaces, but in the global
132namespace.\footnote{This limitation occurs because the code that is
133 executed by these operations is not available at the time the
134 module is compiled.}
135The \keyword{exec} statement and the \function{eval()} and
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000136\function{execfile()} functions have optional arguments to override
137the global and local namespace. If only one namespace is specified,
138it is used for both.
Fred Drakef6669171998-05-06 19:52:49 +0000139
140\end{description}
141
Jeremy Hylton0eb10702001-02-01 03:50:59 +0000142The built-in functions \function{globals()} and \function{locals()}
143each return a dictionary, representing the current global and local
144namespace respectively. The effect of modifications to these
145dictionaries on the namespace are undefined.\footnote{
Fred Drake431f0ce1999-05-13 18:38:11 +0000146 The current implementations return the dictionary actually used to
147 implement the namespace, \emph{except} for functions, where the
148 optimizer may cause the local namespace to be implemented
149 differently, and \function{locals()} returns a read-only
150 dictionary.}
Fred Drakef6669171998-05-06 19:52:49 +0000151
Fred Drake431f0ce1999-05-13 18:38:11 +0000152
153\section{Exceptions \label{exceptions}}
154\index{exception}
Fred Drakef6669171998-05-06 19:52:49 +0000155
156Exceptions are a means of breaking out of the normal flow of control
157of a code block in order to handle errors or other exceptional
Fred Drake431f0ce1999-05-13 18:38:11 +0000158conditions. An exception is
159\emph{raised}\index{raise an exception} at the point where the error
160is detected; it may be \emph{handled}\index{handle an exception} by
161the surrounding code block or by any code block that directly or
162indirectly invoked the code block where the error occurred.
Fred Drakef6669171998-05-06 19:52:49 +0000163\index{exception handler}
164\index{errors}
165\index{error handling}
166
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000167The Python interpreter raises an exception when it detects a run-time
Fred Drakef6669171998-05-06 19:52:49 +0000168error (such as division by zero). A Python program can also
169explicitly raise an exception with the \keyword{raise} statement.
170Exception handlers are specified with the \keyword{try} ... \keyword{except}
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000171statement. The \keyword{try} ... \keyword{finally} statement
172specifies cleanup code which does not handle the exception, but is
173executed whether an exception occurred or not in the preceding code.
Fred Drakef6669171998-05-06 19:52:49 +0000174
Fred Drakee15956b2000-04-03 04:51:13 +0000175Python uses the ``termination'' \index{termination model}model of
176error handling: an exception handler can find out what happened and
177continue execution at an outer level, but it cannot repair the cause
178of the error and retry the failing operation (except by re-entering
179the offending piece of code from the top).
Fred Drakef6669171998-05-06 19:52:49 +0000180
181When an exception is not handled at all, the interpreter terminates
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000182execution of the program, or returns to its interactive main loop. In
183either case, it prints a stack backtrace, except when the exception is
Fred Drake431f0ce1999-05-13 18:38:11 +0000184\exception{SystemExit}\withsubitem{(built-in
185exception)}{\ttindex{SystemExit}}.
Fred Drakef6669171998-05-06 19:52:49 +0000186
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000187Exceptions are identified by string objects or class instances.
188Selection of a matching except clause is based on object identity
189(i.e., two different string objects with the same value represent
190different exceptions!) For string exceptions, the \keyword{except}
191clause must reference the same string object. For class exceptions,
192the \keyword{except} clause must reference the same class or a base
193class of it.
Fred Drakef6669171998-05-06 19:52:49 +0000194
195When an exception is raised, an object (maybe \code{None}) is passed
Guido van Rossumb18a93b1998-07-23 19:36:00 +0000196as the exception's ``parameter'' or ``value''; this object does not
197affect the selection of an exception handler, but is passed to the
198selected exception handler as additional information. For class
199exceptions, this object must be an instance of the exception class
200being raised.
Fred Drakef6669171998-05-06 19:52:49 +0000201
Fred Drakee15956b2000-04-03 04:51:13 +0000202See also the description of the \keyword{try} statement in section
203\ref{try} and \keyword{raise} statement in section \ref{raise}.