11\chapter {Execution model }
22\index {execution model}
33
4- \section {Code blocks, execution frames, and name spaces } \label {execframes }
4+ \section {Code blocks, execution frames, and namespaces } \label {execframes }
55\index {code block}
66\indexii {execution}{frame}
7- \index {name space }
7+ \index {namespace }
88
99A {\em code block} is a piece of Python program text that can be
1010executed 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
11+ body. Some code blocks (like modules) are normally executed only once, others
1212(like function bodies) may be executed many times. Code blocks may
1313textually contain other code blocks. Code blocks may invoke other
1414code blocks (that may or may not be textually contained in them) as
1515part of their execution, e.g. by invoking (calling) a function.
1616\index {code block}
1717\indexii {code}{block}
1818
19- The following are code blocks: A module is a code block. A function
19+ The following are code blocks: A module is a code block. A function
2020body 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.
21+ command typed interactively is a separate code block; a script file (a
22+ file given as standard input to the interpreter or specified on the
23+ interpreter command line the first argument) is a code block; a script
24+ command (a command specified on the interpreter command line with the
25+ `\code {-c}' option) is a code block. The file read by the built-in
26+ function \function {execfile()} is a code block. The string argument
27+ passed to the built-in function \function {eval()} and to the
28+ \keyword {exec} statement is a code block. And finally, the expression
29+ read and evaluated by the built-in function \function {input()} is a
30+ code block.
2631
2732A code block is executed in an execution frame. An {\em execution
2833frame} contains some administrative information (used for debugging),
2934determines where and how execution continues after the code block's
3035execution has completed, and (perhaps most importantly) defines two
31- name spaces , the local and the global name space , that affect
36+ namespaces , the local and the global namespace , that affect
3237execution of the code block.
3338\indexii {execution}{frame}
3439
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
40+ A {\em namespace } is a mapping from names (identifiers) to objects.
41+ A particular namespace may be referenced by more than one execution
42+ frame, and from other places as well. Adding a name to a namespace
3843is called {\em binding} a name (to an object); changing the mapping of
3944a name is called {\em rebinding}; removing a name is {\em unbinding}.
40- Name spaces are functionally equivalent to dictionaries.
41- \index {name space}
45+ Namespaces are functionally equivalent to dictionaries (and often
46+ implemented as dictionaries).
47+ \index {namespace}
4248\indexii {binding}{name}
4349\indexii {rebinding}{name}
4450\indexii {unbinding}{name}
4551
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}
52+ The {\em local namespace } of an execution frame determines the default
53+ place where names are defined and searched. The {\em global
54+ namespace } determines the place where names listed in \keyword {global}
4955statements 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 }
56+ bound anywhere in the current code block are searched.
57+ \indexii {local}{namespace }
58+ \indexii {global}{namespace }
5359\stindex {global}
5460
5561Whether a name is local or global in a code block is determined by
5662static 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
63+ absence of \keyword {global} statements, a name that is bound anywhere
64+ in the code block is local in the entire code block; all other names
65+ are considered global. The \keyword {global} statement forces global
6066interpretation 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.
67+ following constructs bind names: formal parameters to functions,
68+ \keyword {import} statements, class and function definitions (these
69+ bind the class or function name in the defining block), and targets
70+ that are identifiers if occurring in an assignment, \keyword {for} loop
71+ header, or in the second position of an \keyword {except} clause
72+ header. Local names are searched only on the local namespace; global
73+ names are searched only in the global and built-in namespace.%
74+ %
75+ \footnote {If the code block contains \keyword {exec} statements or the
76+ construct `` \samp {from \ldots import *}'' , the semantics of local
77+ names change: local name lookup first searches the local namespace,
78+ then the global namespace and the built-in namespace.}
6579
6680A target occurring in a \keyword {del} statement is also considered bound
6781for this purpose (though the actual semantics are to `` unbind'' the
6882name).
6983
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.}
84+ When a global name is not found in the global namespace, it is
85+ searched in the built-in namespace (which is actually the global
86+ namespace of the module \module {__builtin__}). The built-in namespace
87+ associated with the execution of a code block is actually found by
88+ looking up the name \code {__builtins__} is its global namespace; this
89+ should be a dictionary or a module (in the latter case its dictionary
90+ is used). Normally, the \code {__builtins__} namespace is the
91+ dictionary of the built-in module \module {__builtin__} (note: no `s');
92+ if it isn't, restricted execution mode is in effect. When a name is
93+ not found at all, a \exception {NameError} exception is raised.%
7994\refbimodindex {__builtin__}
8095\stindex {from}
8196\stindex {exec}
8297\stindex {global}
98+ \indexii {restricted}{execution}
8399\withsubitem {(built-in exception)}{\ttindex {NameError}}
84100
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
101+ The following table lists the meaning of the local and global
102+ namespace for various types of code blocks. The namespace for a
87103particular 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!
104+ imported (i.e., when it is loaded). Note that in almost all cases,
105+ the global namespace is the namespace of the containing module ---
106+ scopes in Python do not nest!
91107
92108\begin {center }
93109\begin {tabular }{|l|l|l|l|}
94110\hline
95- Code block type & Global name space & Local name space & Notes \\
111+ Code block type & Global namespace & Local namespace & Notes \\
96112\hline
97113Module & n.s. for this module & same as global & \\
98- Script & n.s. for \module {__main__} & same as global & \\
114+ Script (file or command) & n.s. for \module {__main__} & same as global
115+ & (1) \\
99116Interactive command & n.s. for \module {__main__} & same as global & \\
100117Class definition & global n.s. of containing block & new n.s. & \\
101118Function body & global n.s. of containing block & new n.s. & (2) \\
102119String passed to \keyword {exec} statement
103120 & global n.s. of containing block
104- & local n.s. of containing block & (1 ) \\
121+ & local n.s. of containing block & (2), (3 ) \\
105122String passed to \function {eval()}
106- & global n.s. of caller & local n.s. of caller & (1 ) \\
123+ & global n.s. of caller & local n.s. of caller & (2), (3 ) \\
107124File read by \function {execfile()}
108- & global n.s. of caller & local n.s. of caller & (1 ) \\
125+ & global n.s. of caller & local n.s. of caller & (2), (3 ) \\
109126Expression read by \function {input()}
110127 & global n.s. of caller & local n.s. of caller & \\
111128\hline
@@ -117,25 +134,28 @@ \section{Code blocks, execution frames, and name spaces} \label{execframes}
117134
118135\begin {description }
119136
120- \item [n.s.] means {\em name space }
137+ \item [n.s.] means {\em namespace }
121138
122- \item [(1)] The global and local name space for these can be
139+ \item [(1)] The main module for a script is always called
140+ \module {__main__}; `` the filename don't enter into it.''
141+
142+ \item [(2)] The global and local namespace for these can be
123143overridden with optional extra arguments.
124144
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}
145+ \item [(3 )] The \keyword {exec} statement and the \function {eval()} and
146+ \function {execfile()} functions have optional arguments to override
147+ the global and local namespace. If only one namespace is specified,
148+ it is used for both.
129149
130150\end {description }
131151
132152The built-in functions \function {globals()} and \function {locals()} returns a
133- dictionary representing the current global and local name space ,
153+ dictionary representing the current global and local namespace ,
134154respectively. The effect of modifications to this dictionary on the
135- name space are undefined.%
155+ namespace are undefined.%
136156\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
157+ used to implement the namespace , {\em except} for functions, where
158+ the optimizer may cause the local namespace to be implemented
139159differently, and \function {locals()} returns a read-only dictionary.}
140160
141161\section {Exceptions }
@@ -153,48 +173,39 @@ \section{Exceptions}
153173\index {errors}
154174\index {error handling}
155175
156- The Python interpreter raises an exception when it detects an run-time
176+ The Python interpreter raises an exception when it detects a run-time
157177error (such as division by zero). A Python program can also
158178explicitly raise an exception with the \keyword {raise} statement.
159179Exception handlers are specified with the \keyword {try} ... \keyword {except}
160- statement.
180+ statement. The \keyword {try} ... \keyword {finally} statement
181+ specifies cleanup code which does not handle the exception, but is
182+ executed whether an exception occurred or not in the preceding code.
161183
162184Python uses the `` termination'' model of error handling: an exception
163185handler can find out what happened and continue execution at an outer
164186level, but it cannot repair the cause of the error and retry the
165- failing operation (except by re-entering the the offending piece of
187+ failing operation (except by re-entering the offending piece of
166188code from the top).
167189
168190When 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.
191+ execution of the program, or returns to its interactive main loop. In
192+ either case, it prints a stack backtrace, except when the exception is
193+ \exception {SystemExit}.\ttindex {SystemExit}
194+
195+ Exceptions are identified by string objects or class instances.
196+ Selection of a matching except clause is based on object identity
197+ (i.e., two different string objects with the same value represent
198+ different exceptions!) For string exceptions, the \keyword {except}
199+ clause must reference the same string object. For class exceptions,
200+ the \keyword {except} clause must reference the same class or a base
201+ class of it.
176202
177203When 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 }
204+ as the exception's `` parameter'' or `` value'' ; this object does not
205+ affect the selection of an exception handler, but is passed to the
206+ selected exception handler as additional information. For class
207+ exceptions, this object must be an instance of the exception class
208+ being raised.
198209
199210See also the description of the \keyword {try} and \keyword {raise}
200- statements.
211+ statements in chapter 7 .
0 commit comments