blob: b810056f531918de6e92bad2e7b45e6d408a7f0e [file] [log] [blame]
Fred Drake61c77281998-07-28 19:34:22 +00001\chapter{Simple statements\label{simple}}
Fred Drakef6669171998-05-06 19:52:49 +00002\indexii{simple}{statement}
3
4Simple statements are comprised within a single logical line.
5Several simple statements may occur on a single line separated
6by semicolons. The syntax for simple statements is:
7
8\begin{verbatim}
9simple_stmt: expression_stmt
Guido van Rossum56c20131998-07-24 18:25:38 +000010 | assert_stmt
Fred Drakef6669171998-05-06 19:52:49 +000011 | assignment_stmt
12 | pass_stmt
13 | del_stmt
14 | print_stmt
15 | return_stmt
16 | raise_stmt
17 | break_stmt
18 | continue_stmt
19 | import_stmt
20 | global_stmt
21 | exec_stmt
22\end{verbatim}
23
Fred Drake61c77281998-07-28 19:34:22 +000024\section{Expression statements\label{exprstmts}}
Fred Drakef6669171998-05-06 19:52:49 +000025\indexii{expression}{statement}
26
27Expression statements are used (mostly interactively) to compute and
28write a value, or (usually) to call a procedure (a function that
29returns no meaningful result; in Python, procedures return the value
Guido van Rossum56c20131998-07-24 18:25:38 +000030\code{None}). Other uses of expression statements are allowed and
31occasionally useful. The syntax for an expression statement is:
Fred Drakef6669171998-05-06 19:52:49 +000032
33\begin{verbatim}
Guido van Rossum56c20131998-07-24 18:25:38 +000034expression_stmt: expression_list
Fred Drakef6669171998-05-06 19:52:49 +000035\end{verbatim}
36
Guido van Rossum56c20131998-07-24 18:25:38 +000037An expression statement evaluates the expression list (which may be a
38single expression).
Fred Drakef6669171998-05-06 19:52:49 +000039\indexii{expression}{list}
40
41In interactive mode, if the value is not \code{None}, it is converted
Guido van Rossum56c20131998-07-24 18:25:38 +000042to a string using the built-in \function{repr()}\bifuncindex{repr}
43function and the resulting string is written to standard output (see
44section \ref{print}) on a line by itself. (Expression statements
45yielding None are not written, so that procedure calls do not cause
46any output.)
Fred Drakef6669171998-05-06 19:52:49 +000047\ttindex{None}
48\indexii{string}{conversion}
49\index{output}
50\indexii{standard}{output}
51\indexii{writing}{values}
52\indexii{procedure}{call}
53
Fred Drake61c77281998-07-28 19:34:22 +000054\section{Assert statements\label{assert}}\stindex{assert}
Guido van Rossum56c20131998-07-24 18:25:38 +000055
56Assert statements are a convenient way to insert debugging
57assertions\indexii{debugging}{assertions} into a program:
58
59\begin{verbatim}
60assert_statement: "assert" expression ["," expression]
61\end{verbatim}
62
63The simple form, ``\code{assert expression}'', is equivalent to
64
65\begin{verbatim}
66if __debug__:
67 if not expression: raise AssertionError
68\end{verbatim}
69
70The extended form, ``\code{assert expression1, expression2}'', is
71equivalent to
72
73\begin{verbatim}
74if __debug__:
75 if not expression1: raise AssertionError, expression2
76\end{verbatim}
77
78These equivalences assume that \code{__debug__}\ttindex{__debug__} and
79\code{AssertionError}\exindex{AssertionError} refer to the built-in
80variables with those names. In the current implementation, the
81built-in variable \code{__debug__} is 1 under normal circumstances, 0
82when optimization is requested (command line option -O). The current
83code generator emits no code for an assert statement when optimization
84is requested at compile time. Note that it is unnecessary to include
85the source code for the expression that failed in the error message;
86it will be displayed as part of the stack trace.
87
88
Fred Drake61c77281998-07-28 19:34:22 +000089\section{Assignment statements\label{assignment}}
Fred Drakef6669171998-05-06 19:52:49 +000090\indexii{assignment}{statement}
91
92Assignment statements are used to (re)bind names to values and to
93modify attributes or items of mutable objects:
94\indexii{binding}{name}
95\indexii{rebinding}{name}
96\obindex{mutable}
97\indexii{attribute}{assignment}
98
99\begin{verbatim}
100assignment_stmt: (target_list "=")+ expression_list
101target_list: target ("," target)* [","]
102target: identifier | "(" target_list ")" | "[" target_list "]"
103 | attributeref | subscription | slicing
104\end{verbatim}
105
106(See section \ref{primaries} for the syntax definitions for the last
107three symbols.)
108
109An assignment statement evaluates the expression list (remember that
110this can be a single expression or a comma-separated list, the latter
111yielding a tuple) and assigns the single resulting object to each of
112the target lists, from left to right.
113\indexii{expression}{list}
114
115Assignment is defined recursively depending on the form of the target
116(list). When a target is part of a mutable object (an attribute
117reference, subscription or slicing), the mutable object must
118ultimately perform the assignment and decide about its validity, and
119may raise an exception if the assignment is unacceptable. The rules
120observed by various types and the exceptions raised are given with the
121definition of the object types (see section \ref{types}).
122\index{target}
123\indexii{target}{list}
124
125Assignment of an object to a target list is recursively defined as
126follows.
127\indexiii{target}{list}{assignment}
128
129\begin{itemize}
130\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000131If the target list is a single target: The object is assigned to that
Fred Drakef6669171998-05-06 19:52:49 +0000132target.
133
134\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000135If the target list is a comma-separated list of targets: The object
136must be a sequence with the same number of items as the there are
137targets in the target list, and the items are assigned, from left to
138right, to the corresponding targets. (This rule is relaxed as of
139Python 1.5; in earlier versions, the object had to be a tuple. Since
140strings are sequences, an assignment like ``\code{a, b = "xy"}'' is
141now legal as long as the string has the right length.)
Fred Drakef6669171998-05-06 19:52:49 +0000142
143\end{itemize}
144
145Assignment of an object to a single target is recursively defined as
146follows.
147
148\begin{itemize} % nested
149
150\item
151If the target is an identifier (name):
152
153\begin{itemize}
154
155\item
156If the name does not occur in a \keyword{global} statement in the current
Guido van Rossum56c20131998-07-24 18:25:38 +0000157code block: the name is bound to the object in the current local
158namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000159\stindex{global}
160
161\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000162Otherwise: the name is bound to the object in the current global
163namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000164
165\end{itemize} % nested
166
Guido van Rossum56c20131998-07-24 18:25:38 +0000167The name is rebound if it was already bound. This may cause the
168reference count for the object previously bound to the name to reach
169zero, causing the object to be deallocated and its
170destructor\index{destructor} (if it has one) to be called.
Fred Drakef6669171998-05-06 19:52:49 +0000171
172\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000173If the target is a target list enclosed in parentheses or in square
174brackets: The object must be a sequence with the same number of items
175as there are targets in the target list, and its items are assigned,
176from left to right, to the corresponding targets.
Fred Drakef6669171998-05-06 19:52:49 +0000177
178\item
179If the target is an attribute reference: The primary expression in the
180reference is evaluated. It should yield an object with assignable
181attributes; if this is not the case, \exception{TypeError} is raised. That
182object is then asked to assign the assigned object to the given
183attribute; if it cannot perform the assignment, it raises an exception
184(usually but not necessarily \exception{AttributeError}).
185\indexii{attribute}{assignment}
186
187\item
188If the target is a subscription: The primary expression in the
189reference is evaluated. It should yield either a mutable sequence
Guido van Rossum56c20131998-07-24 18:25:38 +0000190object (e.g., a list) or a mapping object (e.g., a dictionary). Next,
191the subscript expression is evaluated.
Fred Drakef6669171998-05-06 19:52:49 +0000192\indexii{subscription}{assignment}
193\obindex{mutable}
194
Guido van Rossum56c20131998-07-24 18:25:38 +0000195If the primary is a mutable sequence object (e.g., a list), the subscript
Fred Drakef6669171998-05-06 19:52:49 +0000196must yield a plain integer. If it is negative, the sequence's length
197is added to it. The resulting value must be a nonnegative integer
198less than the sequence's length, and the sequence is asked to assign
199the assigned object to its item with that index. If the index is out
200of range, \exception{IndexError} is raised (assignment to a subscripted
201sequence cannot add new items to a list).
202\obindex{sequence}
203\obindex{list}
204
Guido van Rossum56c20131998-07-24 18:25:38 +0000205If the primary is a mapping object (e.g., a dictionary), the subscript must
Fred Drakef6669171998-05-06 19:52:49 +0000206have a type compatible with the mapping's key type, and the mapping is
207then asked to create a key/datum pair which maps the subscript to
208the assigned object. This can either replace an existing key/value
209pair with the same key value, or insert a new key/value pair (if no
210key with the same value existed).
211\obindex{mapping}
212\obindex{dictionary}
213
214\item
215If the target is a slicing: The primary expression in the reference is
Guido van Rossum56c20131998-07-24 18:25:38 +0000216evaluated. It should yield a mutable sequence object (e.g., a list). The
Fred Drakef6669171998-05-06 19:52:49 +0000217assigned object should be a sequence object of the same type. Next,
218the lower and upper bound expressions are evaluated, insofar they are
219present; defaults are zero and the sequence's length. The bounds
220should evaluate to (small) integers. If either bound is negative, the
221sequence's length is added to it. The resulting bounds are clipped to
222lie between zero and the sequence's length, inclusive. Finally, the
223sequence object is asked to replace the slice with the items of the
224assigned sequence. The length of the slice may be different from the
225length of the assigned sequence, thus changing the length of the
226target sequence, if the object allows it.
227\indexii{slicing}{assignment}
228
229\end{itemize}
230
231(In the current implementation, the syntax for targets is taken
232to be the same as for expressions, and invalid syntax is rejected
233during the code generation phase, causing less detailed error
234messages.)
235
236WARNING: Although the definition of assignment implies that overlaps
Guido van Rossum56c20131998-07-24 18:25:38 +0000237between the left-hand side and the right-hand side are `safe' (e.g.,
238``\code{a, b = b, a}'' swaps two variables), overlaps \emph{within} the
Fred Drakef6669171998-05-06 19:52:49 +0000239collection of assigned-to variables are not safe! For instance, the
Guido van Rossum56c20131998-07-24 18:25:38 +0000240following program prints ``\code{[0, 2]}'':
Fred Drakef6669171998-05-06 19:52:49 +0000241
242\begin{verbatim}
243x = [0, 1]
244i = 0
245i, x[i] = 1, 2
246print x
247\end{verbatim}
248
249
Fred Drake61c77281998-07-28 19:34:22 +0000250\section{The \keyword{pass} statement\label{pass}}
Fred Drakef6669171998-05-06 19:52:49 +0000251\stindex{pass}
252
253\begin{verbatim}
254pass_stmt: "pass"
255\end{verbatim}
256
257\keyword{pass} is a null operation --- when it is executed, nothing
258happens. It is useful as a placeholder when a statement is
259required syntactically, but no code needs to be executed, for example:
260\indexii{null}{operation}
261
262\begin{verbatim}
263def f(arg): pass # a function that does nothing (yet)
264
265class C: pass # a class with no methods (yet)
266\end{verbatim}
267
Fred Drake61c77281998-07-28 19:34:22 +0000268\section{The \keyword{del} statement\label{del}}
Fred Drakef6669171998-05-06 19:52:49 +0000269\stindex{del}
270
271\begin{verbatim}
272del_stmt: "del" target_list
273\end{verbatim}
274
275Deletion is recursively defined very similar to the way assignment is
276defined. Rather that spelling it out in full details, here are some
277hints.
278\indexii{deletion}{target}
279\indexiii{deletion}{target}{list}
280
281Deletion of a target list recursively deletes each target, from left
282to right.
283
284Deletion of a name removes the binding of that name (which must exist)
Guido van Rossum56c20131998-07-24 18:25:38 +0000285from the local or global namespace, depending on whether the name
Fred Drakef6669171998-05-06 19:52:49 +0000286occurs in a \keyword{global} statement in the same code block.
287\stindex{global}
288\indexii{unbinding}{name}
289
290Deletion of attribute references, subscriptions and slicings
291is passed to the primary object involved; deletion of a slicing
292is in general equivalent to assignment of an empty slice of the
293right type (but even this is determined by the sliced object).
294\indexii{attribute}{deletion}
295
Fred Drake61c77281998-07-28 19:34:22 +0000296\section{The \keyword{print} statement\label{print}}
Fred Drakef6669171998-05-06 19:52:49 +0000297\stindex{print}
298
299\begin{verbatim}
Guido van Rossum56c20131998-07-24 18:25:38 +0000300print_stmt: "print" [ expression ("," expression)* [","] ]
Fred Drakef6669171998-05-06 19:52:49 +0000301\end{verbatim}
302
Guido van Rossum56c20131998-07-24 18:25:38 +0000303\keyword{print} evaluates each expression in turn and writes the resulting
Fred Drakef6669171998-05-06 19:52:49 +0000304object to standard output (see below). If an object is not a string,
305it is first converted to a string using the rules for string
306conversions. The (resulting or original) string is then written. A
307space is written before each object is (converted and) written, unless
308the output system believes it is positioned at the beginning of a
Guido van Rossum56c20131998-07-24 18:25:38 +0000309line. This is the case (1) when no characters have yet been written
310to standard output, (2) when the last character written to standard
311output is \character{\\n}, or (3) when the last write operation on standard
Fred Drakef6669171998-05-06 19:52:49 +0000312output was not a \keyword{print} statement. (In some cases it may be
313functional to write an empty string to standard output for this
314reason.)
315\index{output}
316\indexii{writing}{values}
317
Fred Drakedde91f01998-05-06 20:59:46 +0000318A \character{\\n} character is written at the end, unless the \keyword{print}
Fred Drakef6669171998-05-06 19:52:49 +0000319statement ends with a comma. This is the only action if the statement
320contains just the keyword \keyword{print}.
321\indexii{trailing}{comma}
322\indexii{newline}{suppression}
323
Fred Drakedde91f01998-05-06 20:59:46 +0000324Standard output is defined as the file object named \code{stdout}
Guido van Rossum56c20131998-07-24 18:25:38 +0000325in the built-in module \module{sys}. If no such object exists, or if
326it does not have a \method{write()} method, a \exception{RuntimeError}
327exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000328\indexii{standard}{output}
329\refbimodindex{sys}
330\ttindex{stdout}
331\exindex{RuntimeError}
332
Fred Drake61c77281998-07-28 19:34:22 +0000333\section{The \keyword{return} statement\label{return}}
Fred Drakef6669171998-05-06 19:52:49 +0000334\stindex{return}
335
336\begin{verbatim}
Guido van Rossum56c20131998-07-24 18:25:38 +0000337return_stmt: "return" [expression_list]
Fred Drakef6669171998-05-06 19:52:49 +0000338\end{verbatim}
339
340\keyword{return} may only occur syntactically nested in a function
341definition, not within a nested class definition.
342\indexii{function}{definition}
343\indexii{class}{definition}
344
Guido van Rossum56c20131998-07-24 18:25:38 +0000345If an expression list is present, it is evaluated, else \code{None}
Fred Drakef6669171998-05-06 19:52:49 +0000346is substituted.
347
Guido van Rossum56c20131998-07-24 18:25:38 +0000348\keyword{return} leaves the current function call with the expression
Fred Drakef6669171998-05-06 19:52:49 +0000349list (or \code{None}) as return value.
350
351When \keyword{return} passes control out of a \keyword{try} statement
Guido van Rossum56c20131998-07-24 18:25:38 +0000352with a \keyword{finally} clause, that \keyword{finally} clause is executed
Fred Drakef6669171998-05-06 19:52:49 +0000353before really leaving the function.
354\kwindex{finally}
355
Fred Drake61c77281998-07-28 19:34:22 +0000356\section{The \keyword{raise} statement\label{raise}}
Fred Drakef6669171998-05-06 19:52:49 +0000357\stindex{raise}
358
359\begin{verbatim}
Guido van Rossum56c20131998-07-24 18:25:38 +0000360raise_stmt: "raise" [expression ["," expression ["," expression]]]
Fred Drakef6669171998-05-06 19:52:49 +0000361\end{verbatim}
362
Guido van Rossum56c20131998-07-24 18:25:38 +0000363If no expressions are present, \keyword{raise} re-raises the last
364expression that was raised in the current scope.
365
366Otherwose, \keyword{raise} evaluates its first expression, which must yield
367a string, class, or instance object. If there is a second expression,
Fred Drakef6669171998-05-06 19:52:49 +0000368this is evaluated, else \code{None} is substituted. If the first
Guido van Rossum56c20131998-07-24 18:25:38 +0000369expression is a class object, then the second expression must be an
Fred Drakef6669171998-05-06 19:52:49 +0000370instance of that class or one of its derivatives. If the first
Guido van Rossum56c20131998-07-24 18:25:38 +0000371expression is an instance object, the second expression must be
Fred Drakef6669171998-05-06 19:52:49 +0000372\code{None}.
373\index{exception}
374\indexii{raising}{exception}
375
376If the first object is a class or string, it then raises the exception
377identified by the first object, with the second one (or \code{None})
378as its parameter. If the first object is an instance, it raises the
379exception identified by the class of the object, with the instance as
380its parameter (and there should be no second object, or the second
381object should be \code{None}).
382
Guido van Rossum56c20131998-07-24 18:25:38 +0000383If a third object is present, and it is not \code{None}, it should be
Fred Drakef6669171998-05-06 19:52:49 +0000384a traceback object (see section \ref{traceback}), and it is
385substituted instead of the current location as the place where the
386exception occurred. This is useful to re-raise an exception
387transparently in an except clause.
388\obindex{traceback}
389
Fred Drake61c77281998-07-28 19:34:22 +0000390\section{The \keyword{break} statement\label{break}}
Fred Drakef6669171998-05-06 19:52:49 +0000391\stindex{break}
392
393\begin{verbatim}
394break_stmt: "break"
395\end{verbatim}
396
397\keyword{break} may only occur syntactically nested in a \keyword{for}
398or \keyword{while} loop, but not nested in a function or class definition
399within that loop.
400\stindex{for}
401\stindex{while}
402\indexii{loop}{statement}
403
404It terminates the nearest enclosing loop, skipping the optional
Guido van Rossum56c20131998-07-24 18:25:38 +0000405\keyword{else} clause if the loop has one.
Fred Drakef6669171998-05-06 19:52:49 +0000406\kwindex{else}
407
408If a \keyword{for} loop is terminated by \keyword{break}, the loop control
409target keeps its current value.
410\indexii{loop control}{target}
411
412When \keyword{break} passes control out of a \keyword{try} statement
Guido van Rossum56c20131998-07-24 18:25:38 +0000413with a \keyword{finally} clause, that \keyword{finally} clause is executed
Fred Drakef6669171998-05-06 19:52:49 +0000414before really leaving the loop.
415\kwindex{finally}
416
Fred Drake61c77281998-07-28 19:34:22 +0000417\section{The \keyword{continue} statement\label{continue}}
Fred Drakef6669171998-05-06 19:52:49 +0000418\stindex{continue}
419
420\begin{verbatim}
421continue_stmt: "continue"
422\end{verbatim}
423
424\keyword{continue} may only occur syntactically nested in a \keyword{for} or
425\keyword{while} loop, but not nested in a function or class definition or
Guido van Rossum56c20131998-07-24 18:25:38 +0000426\keyword{try} statement within that loop.\footnote{It may
427occur within an \keyword{except} or \keyword{else} clause. The
428restriction on occurring in the \keyword{try} clause is implementer's
429laziness and will eventually be lifted.}
430It continues with the next cycle of the nearest enclosing loop.
Fred Drakef6669171998-05-06 19:52:49 +0000431\stindex{for}
432\stindex{while}
433\indexii{loop}{statement}
434\kwindex{finally}
435
Fred Drake61c77281998-07-28 19:34:22 +0000436\section{The \keyword{import} statement\label{import}}
Fred Drakef6669171998-05-06 19:52:49 +0000437\stindex{import}
438
439\begin{verbatim}
Guido van Rossum56c20131998-07-24 18:25:38 +0000440import_stmt: "import" module ("," module)*
441 | "from" module "import" identifier ("," identifier)*
442 | "from" module "import" "*"
443module: (identifier ".")* identifier
Fred Drakef6669171998-05-06 19:52:49 +0000444\end{verbatim}
445
446Import statements are executed in two steps: (1) find a module, and
447initialize it if necessary; (2) define a name or names in the local
Guido van Rossum56c20131998-07-24 18:25:38 +0000448namespace (of the scope where the \keyword{import} statement occurs).
Fred Drakef6669171998-05-06 19:52:49 +0000449The first form (without \keyword{from}) repeats these steps for each
Guido van Rossum56c20131998-07-24 18:25:38 +0000450identifier in the list. The form with \keyword{from} performs step
451(1) once, and then performs step (2) repeatedly.
Fred Drakef6669171998-05-06 19:52:49 +0000452\indexii{importing}{module}
453\indexii{name}{binding}
454\kwindex{from}
455
456The system maintains a table of modules that have been initialized,
Guido van Rossum56c20131998-07-24 18:25:38 +0000457indexed by module name. This table table
458accessible as \code{sys.modules}. When a module name is found in
Fred Drakef6669171998-05-06 19:52:49 +0000459this table, step (1) is finished. If not, a search for a module
Guido van Rossum56c20131998-07-24 18:25:38 +0000460definition is started. When a module is found, it is loaded. Details
461of the module searching and loading process are implementation and
462platform specific. It generally involves searching for a ``built-in''
463module with the given name and then searching a list of locations
464given as \code{sys.path}.
Fred Drakef6669171998-05-06 19:52:49 +0000465\ttindex{modules}
466\ttindex{sys.modules}
467\indexii{module}{name}
468\indexii{built-in}{module}
469\indexii{user-defined}{module}
470\refbimodindex{sys}
Fred Drakef6669171998-05-06 19:52:49 +0000471\indexii{filename}{extension}
Fred Drakedde91f01998-05-06 20:59:46 +0000472\indexiii{module}{search}{path}
Fred Drakef6669171998-05-06 19:52:49 +0000473
474If a built-in module is found, its built-in initialization code is
475executed and step (1) is finished. If no matching file is found,
476\exception{ImportError} is raised. If a file is found, it is parsed,
477yielding an executable code block. If a syntax error occurs,
478\exception{SyntaxError} is raised. Otherwise, an empty module of the given
479name is created and inserted in the module table, and then the code
480block is executed in the context of this module. Exceptions during
481this execution terminate step (1).
482\indexii{module}{initialization}
483\exindex{SyntaxError}
484\exindex{ImportError}
485\index{code block}
486
487When step (1) finishes without raising an exception, step (2) can
488begin.
489
490The first form of \keyword{import} statement binds the module name in the
Guido van Rossum56c20131998-07-24 18:25:38 +0000491local namespace to the module object, and then goes on to import the
492next identifier, if any. The \keyword{from} form does not bind the
Fred Drakef6669171998-05-06 19:52:49 +0000493module name: it goes through the list of identifiers, looks each one
494of them up in the module found in step (1), and binds the name in the
Guido van Rossum56c20131998-07-24 18:25:38 +0000495local namespace to the object thus found. If a name is not found,
Fred Drakef6669171998-05-06 19:52:49 +0000496\exception{ImportError} is raised. If the list of identifiers is replaced
Fred Drakedde91f01998-05-06 20:59:46 +0000497by a star (\code{*}), all names defined in the module are bound,
498except those beginning with an underscore(\code{_}).
Fred Drakef6669171998-05-06 19:52:49 +0000499\indexii{name}{binding}
500\exindex{ImportError}
501
Guido van Rossum56c20131998-07-24 18:25:38 +0000502Names bound by \keyword{import} statements may not occur in
503\keyword{global} statements in the same scope.
Fred Drakef6669171998-05-06 19:52:49 +0000504\stindex{global}
505
Fred Drakedde91f01998-05-06 20:59:46 +0000506The \keyword{from} form with \code{*} may only occur in a module scope.
Fred Drakef6669171998-05-06 19:52:49 +0000507\kwindex{from}
508\ttindex{from ... import *}
509
510(The current implementation does not enforce the latter two
511restrictions, but programs should not abuse this freedom, as future
512implementations may enforce them or silently change the meaning of the
513program.)
514
Fred Drake246837d1998-07-24 20:28:22 +0000515\strong{Hierarchical module names:}\indexiii{hierarchical}{module}{names}
Guido van Rossum56c20131998-07-24 18:25:38 +0000516when the module names contains one or more dots, the module search
517path is carried out differently. The sequence of identifiers up to
518the last dot is used to find a ``package''\index{packages}; the final
519identifier is then searched inside the package. A package is
520generally a subdirectory of a directory on \code{sys.path} that has a
521file \file{__init__.py}.\ttindex{__init__.py}
522%
523[XXX Can't be bothered to spell this out right now; see the URL
Fred Drake1a0b8721998-08-07 17:40:20 +0000524\url{http://www.python.org/doc/essays/packages.html} for more details, also
Guido van Rossum56c20131998-07-24 18:25:38 +0000525about how the module search works from inside a package.]
526
527[XXX Also should mention __import__().]
528\bifuncindex{__import__}
529
Fred Drake61c77281998-07-28 19:34:22 +0000530\section{The \keyword{global} statement\label{global}}
Fred Drakef6669171998-05-06 19:52:49 +0000531\stindex{global}
532
533\begin{verbatim}
534global_stmt: "global" identifier ("," identifier)*
535\end{verbatim}
536
537The \keyword{global} statement is a declaration which holds for the
538entire current code block. It means that the listed identifiers are to be
Fred Drakedde91f01998-05-06 20:59:46 +0000539interpreted as globals. While \emph{using} global names is automatic
540if they are not defined in the local scope, \emph{assigning} to global
Fred Drakef6669171998-05-06 19:52:49 +0000541names would be impossible without \keyword{global}.
542\indexiii{global}{name}{binding}
543
544Names listed in a \keyword{global} statement must not be used in the same
545code block before that \keyword{global} statement is executed.
546
547Names listed in a \keyword{global} statement must not be defined as formal
548parameters or in a \keyword{for} loop control target, \keyword{class}
549definition, function definition, or \keyword{import} statement.
550
551(The current implementation does not enforce the latter two
552restrictions, but programs should not abuse this freedom, as future
553implementations may enforce them or silently change the meaning of the
554program.)
555
Guido van Rossum56c20131998-07-24 18:25:38 +0000556\strong{Programmer's note:}
557the \keyword{global} is a directive to the parser. It
Fred Drakef6669171998-05-06 19:52:49 +0000558applies only to code parsed at the same time as the \keyword{global}
559statement. In particular, a \keyword{global} statement contained in an
Fred Drakedde91f01998-05-06 20:59:46 +0000560\keyword{exec} statement does not affect the code block \emph{containing}
Fred Drakef6669171998-05-06 19:52:49 +0000561the \keyword{exec} statement, and code contained in an \keyword{exec}
562statement is unaffected by \keyword{global} statements in the code
563containing the \keyword{exec} statement. The same applies to the
564\function{eval()}, \function{execfile()} and \function{compile()} functions.
565\stindex{exec}
566\bifuncindex{eval}
567\bifuncindex{execfile}
568\bifuncindex{compile}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000569
Fred Drake61c77281998-07-28 19:34:22 +0000570\section{The \keyword{exec} statement\label{exec}}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000571\stindex{exec}
572
573\begin{verbatim}
574exec_stmt: "exec" expression ["in" expression ["," expression]]
575\end{verbatim}
576
577This statement supports dynamic execution of Python code. The first
578expression should evaluate to either a string, an open file object, or
579a code object. If it is a string, the string is parsed as a suite of
580Python statements which is then executed (unless a syntax error
581occurs). If it is an open file, the file is parsed until EOF and
582executed. If it is a code object, it is simply executed.
583
584In all cases, if the optional parts are omitted, the code is executed
585in the current scope. If only the first expression after \keyword{in}
586is specified, it should be a dictionary, which will be used for both
587the global and the local variables. If two expressions are given,
588both must be dictionaries and they are used for the global and local
589variables, respectively.
590
591As a side effect, an implementation may insert additional keys into
592the dictionaries given besides those corresponding to variable names
593set by the executed code. For example, the current implementation
594may add a reference to the dictionary of the built-in module
595\module{__builtin__} under the key \code{__builtins__} (!).
596\ttindex{__builtins__}
597\refbimodindex{__builtin__}
598
Guido van Rossum56c20131998-07-24 18:25:38 +0000599\strong{Programmer's hints:}
600dynamic evaluation of expressions is supported by the built-in
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000601function \function{eval()}. The built-in functions
602\function{globals()} and \function{locals()} return the current global
603and local dictionary, respectively, which may be useful to pass around
604for use by \keyword{exec}.
605\bifuncindex{eval}
606\bifuncindex{globals}
607\bifuncindex{locals}