cpython/Doc/ref/ref4.tex

202 lines
10 KiB
TeX

\chapter{Execution model \label{execmodel}}
\index{execution model}
\section{Code blocks, execution frames, and namespaces \label{execframes}}
\index{code block}
\index{namespace}
\indexii{execution}{frame}
A \dfn{code block}\indexii{code}{block} is a piece
of Python program text that can be executed as a unit, such as a
module, a class definition or a function body. Some code blocks (like
modules) are normally executed only once, others (like function
bodies) may be executed many times. Code blocks may textually contain
other code blocks. Code blocks may invoke other code blocks (that may
or may not be textually contained in them) as part of their execution,
e.g., by invoking (calling) a function.
The following are code blocks: A module is a code block. A function
body is a code block. A class definition is a code block. Each
command typed interactively is a separate code block; a script file (a
file given as standard input to the interpreter or specified on the
interpreter command line the first argument) is a code block; a script
command (a command specified on the interpreter command line with the
`\strong{-c}' option) is a code block. The file read by the built-in
function \function{execfile()} is a code block. The string argument
passed to the built-in function \function{eval()} and to the
\keyword{exec} statement is a code block. And finally, the expression
read and evaluated by the built-in function \function{input()} is a
code block.
A code block is executed in an execution frame. An \dfn{execution
frame}\indexii{execution}{frame} contains some administrative
information (used for debugging), determines where and how execution
continues after the code block's execution has completed, and (perhaps
most importantly) defines the environment in which names are resolved.
A \dfn{namespace}\indexii{namespace} is a mapping from names
(identifiers) to objects. An \dfn{environment}\index{environment} is
a hierarchical collection of the namespaces that are visible to a
particular code block. Python namespaces are statically scoped in the
tradition of Algol, but also has \keyword{global} statement that can
be used to access the top-level namespace on the environment.
Names refers to objects. Names are introduced by name
\dfn{binding}\indexii{binding}{name} operations. Each occurrence of a name
in the program text refers to the binding of that name established in
the innermost function namespace containing the use. Changing the
mapping of a name to an object is called
\dfn{rebinding}\indexii{rebinding}{name}; removing a name is
\dfn{unbinding}\indexii{unbinding}{name}. Namespaces are functionally
equivalent to dictionaries (and often implemented as dictionaries).
When a name is bound, a mapping is created in the \dfn{local
namespace}\indexii{local}{namespace} of the execution frame unless the
name is declared global. If a name binding operation occurs anywhere
within a code block, all uses of the name within the block are treated
as references to the local namespace. (Note: This can lead to errors
when a name is used within a block before it is bound.)
The \dfn{global namespace}\indexii{global}{namespace} determines the
place where names listed in \keyword{global}\stindex{global}
statements are defined and searched. The global namespace of a block
is the namespace of the module in which the block was defined.
If a name is used within a code block, but it is not bound there and
is not declared global, it is a \dfn{free variable}
\indexii{free}{variable}. A free variable is resolved using the
nearest enclosing function block that has a binding for the name. If
no such block exists, the name is resolved in the global namespace.
When a name is not found at all, a
\exception{NameError}\withsubitem{(built-in
exception)}{\ttindex{NameError}} exception is raised.
The local namespace of a class definition becomes the attribute
dictionary of the class. If a block is contained within a class
definition, the name bindings that occur in the containing class block
are not visible to enclosed blocks.
The following constructs bind names: formal parameters to functions,
\keyword{import} statements, class and function definitions (these bind
the class or function name in the defining block), and identifiers
occurring as the target of an assignment, in a \keyword{for} loop header
(including list comprehensions), or in the second position of an
\keyword{except} clause.
Whether a name is local or global in a code block is determined by
static inspection of the source text for the code block: in the
absence of \keyword{global} statements, a name that is bound anywhere
in the code block is local in the entire code block; all other names
are considered global. The \keyword{global} statement forces global
interpretation of selected names throughout the code block.
The following constructs bind names: formal parameters to functions,
\keyword{import} statements, class and function definitions (these
bind the class or function name in the defining block), and targets
that are identifiers if occurring in an assignment, \keyword{for} loop
header, or in the second position of an \keyword{except} clause
header. The \keyword{import} statement of the form ``\samp{from
\ldots import *}'' binds all names defined in the imported module,
except those beginning with an underscore. This form may only be used
at the module level.
A target occurring in a \keyword{del} statement is also considered bound
for this purpose (though the actual semantics are to unbind the
name). It is illegal to unbind a name that is referenced by an
enclosing scope; the compiler will report a \exception{SyntaxError}.
When a global name is not found in the global namespace, it is
searched in the built-in namespace (which is actually the global
namespace of the module \module{__builtin__}\refbimodindex{__builtin__}).
The built-in namespace associated with the execution of a code block
is actually found by looking up the name \code{__builtins__} is its
global namespace; this should be a dictionary or a module (in the
latter case its dictionary is used). Normally, the
\code{__builtins__} namespace is the dictionary of the built-in module
\module{__builtin__} (note: no `s'). If it isn't, restricted
execution\indexii{restricted}{execution} mode is in effect.
\stindex{from}
\stindex{exec}
\stindex{global}
The namespace for a module is automatically created the first time a
module is imported. The main module for a script is always called
\module{__main__}\refbimodindex{__main__}.
The \function{eval()}, \function{execfile()}, and \function{input()}
functions and the \keyword{exec} statement do not have access to the
full environment for resolving names. Names may be resolved in the
local and global namespaces of the caller. Free variables are not
resolved in the nearest enclosing namespaces, but in the global
namespace.\footnote{This limitation occurs because the code that is
executed by these operations is not available at the time the
module is compiled.}
The \keyword{exec} statement and the \function{eval()} and
\function{execfile()} functions have optional arguments to override
the global and local namespace. If only one namespace is specified,
it is used for both.
The built-in functions \function{globals()} and \function{locals()}
each return a dictionary, representing the current global and local
namespace respectively. The effect of modifications to these
dictionaries on the namespace are undefined.\footnote{
The current implementations return the dictionary actually used to
implement the namespace, \emph{except} for functions, where the
optimizer may cause the local namespace to be implemented
differently, and \function{locals()} returns a read-only
dictionary.}
\section{Exceptions \label{exceptions}}
\index{exception}
Exceptions are a means of breaking out of the normal flow of control
of a code block in order to handle errors or other exceptional
conditions. An exception is
\emph{raised}\index{raise an exception} at the point where the error
is detected; it may be \emph{handled}\index{handle an exception} by
the surrounding code block or by any code block that directly or
indirectly invoked the code block where the error occurred.
\index{exception handler}
\index{errors}
\index{error handling}
The Python interpreter raises an exception when it detects a run-time
error (such as division by zero). A Python program can also
explicitly raise an exception with the \keyword{raise} statement.
Exception handlers are specified with the \keyword{try} ... \keyword{except}
statement. The \keyword{try} ... \keyword{finally} statement
specifies cleanup code which does not handle the exception, but is
executed whether an exception occurred or not in the preceding code.
Python uses the ``termination'' \index{termination model}model of
error handling: an exception handler can find out what happened and
continue execution at an outer level, but it cannot repair the cause
of the error and retry the failing operation (except by re-entering
the offending piece of code from the top).
When an exception is not handled at all, the interpreter terminates
execution of the program, or returns to its interactive main loop. In
either case, it prints a stack backtrace, except when the exception is
\exception{SystemExit}\withsubitem{(built-in
exception)}{\ttindex{SystemExit}}.
Exceptions are identified by string objects or class instances.
Selection of a matching except clause is based on object identity
(i.e., two different string objects with the same value represent
different exceptions!) For string exceptions, the \keyword{except}
clause must reference the same string object. For class exceptions,
the \keyword{except} clause must reference the same class or a base
class of it.
When an exception is raised, an object (maybe \code{None}) is passed
as the exception's ``parameter'' or ``value''; this object does not
affect the selection of an exception handler, but is passed to the
selected exception handler as additional information. For class
exceptions, this object must be an instance of the exception class
being raised.
See also the description of the \keyword{try} statement in section
\ref{try} and \keyword{raise} statement in section \ref{raise}.