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