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