blob: 69a6259a235e75f2612f5b63a5cbab572aadb7e3 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2.. _execmodel:
3
4***************
5Execution model
6***************
7
8.. index:: single: execution model
9
10
11.. _naming:
12
13Naming and binding
14==================
15
16.. index::
17 pair: code; block
18 single: namespace
19 single: scope
20
21.. index::
22 single: name
23 pair: binding; name
24
25:dfn:`Names` refer to objects. Names are introduced by name binding operations.
26Each occurrence of a name in the program text refers to the :dfn:`binding` of
27that name established in the innermost function block containing the use.
28
29.. index:: single: block
30
31A :dfn:`block` is a piece of Python program text that is executed as a unit.
32The following are blocks: a module, a function body, and a class definition.
33Each command typed interactively is a block. A script file (a file given as
34standard input to the interpreter or specified on the interpreter command line
35the first argument) is a code block. A script command (a command specified on
36the interpreter command line with the '**-c**' option) is a code block. The
37file read by the built-in function :func:`execfile` is a code block. The string
38argument passed to the built-in function :func:`eval` and to the :keyword:`exec`
39statement is a code block. The expression read and evaluated by the built-in
40function :func:`input` is a code block.
41
42.. index:: pair: execution; frame
43
44A code block is executed in an :dfn:`execution frame`. A frame contains some
45administrative information (used for debugging) and determines where and how
46execution continues after the code block's execution has completed.
47
48.. index:: single: scope
49
50A :dfn:`scope` defines the visibility of a name within a block. If a local
51variable is defined in a block, its scope includes that block. If the
52definition occurs in a function block, the scope extends to any blocks contained
53within the defining one, unless a contained block introduces a different binding
54for the name. The scope of names defined in a class block is limited to the
55class block; it does not extend to the code blocks of methods.
56
57.. index:: single: environment
58
59When a name is used in a code block, it is resolved using the nearest enclosing
60scope. The set of all such scopes visible to a code block is called the block's
61:dfn:`environment`.
62
63.. index:: pair: free; variable
64
65If a name is bound in a block, it is a local variable of that block. If a name
66is bound at the module level, it is a global variable. (The variables of the
67module code block are local and global.) If a variable is used in a code block
68but not defined there, it is a :dfn:`free variable`.
69
70.. index::
71 single: NameError (built-in exception)
72 single: UnboundLocalError
73
74When a name is not found at all, a :exc:`NameError` exception is raised. If the
75name refers to a local variable that has not been bound, a
76:exc:`UnboundLocalError` exception is raised. :exc:`UnboundLocalError` is a
77subclass of :exc:`NameError`.
78
79.. index:: statement: from
80
81The following constructs bind names: formal parameters to functions,
82:keyword:`import` statements, class and function definitions (these bind the
83class or function name in the defining block), and targets that are identifiers
84if occurring in an assignment, :keyword:`for` loop header, or in the second
85position of an :keyword:`except` clause header. The :keyword:`import` statement
86of the form "``from ...import *``" binds all names defined in the imported
87module, except those beginning with an underscore. This form may only be used
88at the module level.
89
90A target occurring in a :keyword:`del` statement is also considered bound for
91this purpose (though the actual semantics are to unbind the name). It is
92illegal to unbind a name that is referenced by an enclosing scope; the compiler
93will report a :exc:`SyntaxError`.
94
95Each assignment or import statement occurs within a block defined by a class or
96function definition or at the module level (the top-level code block).
97
98If a name binding operation occurs anywhere within a code block, all uses of the
99name within the block are treated as references to the current block. This can
100lead to errors when a name is used within a block before it is bound. This rule
101is subtle. Python lacks declarations and allows name binding operations to
102occur anywhere within a code block. The local variables of a code block can be
103determined by scanning the entire text of the block for name binding operations.
104
105If the global statement occurs within a block, all uses of the name specified in
106the statement refer to the binding of that name in the top-level namespace.
107Names are resolved in the top-level namespace by searching the global namespace,
108i.e. the namespace of the module containing the code block, and the builtin
109namespace, the namespace of the module :mod:`__builtin__`. The global namespace
110is searched first. If the name is not found there, the builtin namespace is
111searched. The global statement must precede all uses of the name.
112
113.. index:: pair: restricted; execution
114
115The built-in namespace associated with the execution of a code block is actually
116found by looking up the name ``__builtins__`` in its global namespace; this
117should be a dictionary or a module (in the latter case the module's dictionary
118is used). By default, when in the :mod:`__main__` module, ``__builtins__`` is
119the built-in module :mod:`__builtin__` (note: no 's'); when in any other module,
120``__builtins__`` is an alias for the dictionary of the :mod:`__builtin__` module
121itself. ``__builtins__`` can be set to a user-created dictionary to create a
122weak form of restricted execution.
123
124.. note::
125
126 Users should not touch ``__builtins__``; it is strictly an implementation
127 detail. Users wanting to override values in the built-in namespace should
128 :keyword:`import` the :mod:`__builtin__` (no 's') module and modify its
129 attributes appropriately.
130
131.. index:: module: __main__
132
133The namespace for a module is automatically created the first time a module is
134imported. The main module for a script is always called :mod:`__main__`.
135
136The global statement has the same scope as a name binding operation in the same
137block. If the nearest enclosing scope for a free variable contains a global
138statement, the free variable is treated as a global.
139
140A class definition is an executable statement that may use and define names.
141These references follow the normal rules for name resolution. The namespace of
142the class definition becomes the attribute dictionary of the class. Names
143defined at the class scope are not visible in methods.
144
145
146.. _dynamic-features:
147
148Interaction with dynamic features
149---------------------------------
150
151There are several cases where Python statements are illegal when used in
152conjunction with nested scopes that contain free variables.
153
154If a variable is referenced in an enclosing scope, it is illegal to delete the
155name. An error will be reported at compile time.
156
157If the wild card form of import --- ``import *`` --- is used in a function and
158the function contains or is a nested block with free variables, the compiler
159will raise a :exc:`SyntaxError`.
160
161If :keyword:`exec` is used in a function and the function contains or is a
162nested block with free variables, the compiler will raise a :exc:`SyntaxError`
163unless the exec explicitly specifies the local namespace for the
164:keyword:`exec`. (In other words, ``exec obj`` would be illegal, but ``exec obj
165in ns`` would be legal.)
166
167The :func:`eval`, :func:`execfile`, and :func:`input` functions and the
168:keyword:`exec` statement do not have access to the full environment for
169resolving names. Names may be resolved in the local and global namespaces of
170the caller. Free variables are not resolved in the nearest enclosing namespace,
171but in the global namespace. [#]_ The :keyword:`exec` statement and the
172:func:`eval` and :func:`execfile` functions have optional arguments to override
173the global and local namespace. If only one namespace is specified, it is used
174for both.
175
176
177.. _exceptions:
178
179Exceptions
180==========
181
182.. index:: single: exception
183
184.. index::
185 single: raise an exception
186 single: handle an exception
187 single: exception handler
188 single: errors
189 single: error handling
190
191Exceptions are a means of breaking out of the normal flow of control of a code
192block in order to handle errors or other exceptional conditions. An exception
193is *raised* at the point where the error is detected; it may be *handled* by the
194surrounding code block or by any code block that directly or indirectly invoked
195the code block where the error occurred.
196
197The Python interpreter raises an exception when it detects a run-time error
198(such as division by zero). A Python program can also explicitly raise an
199exception with the :keyword:`raise` statement. Exception handlers are specified
200with the :keyword:`try` ... :keyword:`except` statement. The :keyword:`try` ...
201:keyword:`finally` statement specifies cleanup code which does not handle the
202exception, but is executed whether an exception occurred or not in the preceding
203code.
204
205.. index:: single: termination model
206
207Python uses the "termination" model of error handling: an exception handler can
208find out what happened and continue execution at an outer level, but it cannot
209repair the cause of the error and retry the failing operation (except by
210re-entering the offending piece of code from the top).
211
212.. index:: single: SystemExit (built-in exception)
213
214When an exception is not handled at all, the interpreter terminates execution of
215the program, or returns to its interactive main loop. In either case, it prints
216a stack backtrace, except when the exception is :exc:`SystemExit`.
217
218Exceptions are identified by class instances. The :keyword:`except` clause is
219selected depending on the class of the instance: it must reference the class of
220the instance or a base class thereof. The instance can be received by the
221handler and can carry additional information about the exceptional condition.
222
223Exceptions can also be identified by strings, in which case the
224:keyword:`except` clause is selected by object identity. An arbitrary value can
225be raised along with the identifying string which can be passed to the handler.
226
227.. warning::
228
229 Messages to exceptions are not part of the Python API. Their contents may
230 change from one version of Python to the next without warning and should not be
231 relied on by code which will run under multiple versions of the interpreter.
232
233See also the description of the :keyword:`try` statement in section :ref:`try`
234and :keyword:`raise` statement in section :ref:`raise`.
235
236.. rubric:: Footnotes
237
238.. [#] This limitation occurs because the code that is executed by these operations is
239 not available at the time the module is compiled.
240