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