blob: 80e9a71228e9fb943318ef9ac9e705ebf9602a90 [file] [log] [blame]
Fred Drakef6669171998-05-06 19:52:49 +00001\chapter{Simple statements}
2\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
10 | assignment_stmt
11 | pass_stmt
12 | del_stmt
13 | print_stmt
14 | return_stmt
15 | raise_stmt
16 | break_stmt
17 | continue_stmt
18 | import_stmt
19 | global_stmt
20 | exec_stmt
21\end{verbatim}
22
23\section{Expression statements}
24\indexii{expression}{statement}
25
26Expression statements are used (mostly interactively) to compute and
27write a value, or (usually) to call a procedure (a function that
28returns no meaningful result; in Python, procedures return the value
29\code{None}):
30
31\begin{verbatim}
32expression_stmt: condition_list
33\end{verbatim}
34
35An expression statement evaluates the condition list (which may be a
36single condition).
37\indexii{expression}{list}
38
39In interactive mode, if the value is not \code{None}, it is converted
40to a string using the rules for string conversions (expressions in
41reverse quotes), and the resulting string is written to standard
42output (see section \ref{print}) on a line by itself.
43(The exception for \code{None} is made so that procedure calls, which
44are syntactically equivalent to expressions, do not cause any output.)
45\ttindex{None}
46\indexii{string}{conversion}
47\index{output}
48\indexii{standard}{output}
49\indexii{writing}{values}
50\indexii{procedure}{call}
51
52\section{Assignment statements}
53\indexii{assignment}{statement}
54
55Assignment statements are used to (re)bind names to values and to
56modify attributes or items of mutable objects:
57\indexii{binding}{name}
58\indexii{rebinding}{name}
59\obindex{mutable}
60\indexii{attribute}{assignment}
61
62\begin{verbatim}
63assignment_stmt: (target_list "=")+ expression_list
64target_list: target ("," target)* [","]
65target: identifier | "(" target_list ")" | "[" target_list "]"
66 | attributeref | subscription | slicing
67\end{verbatim}
68
69(See section \ref{primaries} for the syntax definitions for the last
70three symbols.)
71
72An assignment statement evaluates the expression list (remember that
73this can be a single expression or a comma-separated list, the latter
74yielding a tuple) and assigns the single resulting object to each of
75the target lists, from left to right.
76\indexii{expression}{list}
77
78Assignment is defined recursively depending on the form of the target
79(list). When a target is part of a mutable object (an attribute
80reference, subscription or slicing), the mutable object must
81ultimately perform the assignment and decide about its validity, and
82may raise an exception if the assignment is unacceptable. The rules
83observed by various types and the exceptions raised are given with the
84definition of the object types (see section \ref{types}).
85\index{target}
86\indexii{target}{list}
87
88Assignment of an object to a target list is recursively defined as
89follows.
90\indexiii{target}{list}{assignment}
91
92\begin{itemize}
93\item
94If the target list is a single target: the object is assigned to that
95target.
96
97\item
98If the target list is a comma-separated list of targets: the object
99must be a tuple with the same number of items as the list contains
100targets, and the items are assigned, from left to right, to the
101corresponding targets.
102
103\end{itemize}
104
105Assignment of an object to a single target is recursively defined as
106follows.
107
108\begin{itemize} % nested
109
110\item
111If the target is an identifier (name):
112
113\begin{itemize}
114
115\item
116If the name does not occur in a \keyword{global} statement in the current
117code block: the name is bound to the object in the current local name
118space.
119\stindex{global}
120
121\item
122Otherwise: the name is bound to the object in the current global name
123space.
124
125\end{itemize} % nested
126
127The name is rebound if it was already bound.
128
129\item
130If the target is a target list enclosed in parentheses: the object is
131assigned to that target list as described above.
132
133\item
134If the target is a target list enclosed in square brackets: the object
135must be a list with the same number of items as the target list
136contains targets, and its items are assigned, from left to right, to
137the corresponding targets.
138
139\item
140If the target is an attribute reference: The primary expression in the
141reference is evaluated. It should yield an object with assignable
142attributes; if this is not the case, \exception{TypeError} is raised. That
143object is then asked to assign the assigned object to the given
144attribute; if it cannot perform the assignment, it raises an exception
145(usually but not necessarily \exception{AttributeError}).
146\indexii{attribute}{assignment}
147
148\item
149If the target is a subscription: The primary expression in the
150reference is evaluated. It should yield either a mutable sequence
151(list) object or a mapping (dictionary) object. Next, the subscript
152expression is evaluated.
153\indexii{subscription}{assignment}
154\obindex{mutable}
155
156If the primary is a mutable sequence object (a list), the subscript
157must yield a plain integer. If it is negative, the sequence's length
158is added to it. The resulting value must be a nonnegative integer
159less than the sequence's length, and the sequence is asked to assign
160the assigned object to its item with that index. If the index is out
161of range, \exception{IndexError} is raised (assignment to a subscripted
162sequence cannot add new items to a list).
163\obindex{sequence}
164\obindex{list}
165
166If the primary is a mapping (dictionary) object, the subscript must
167have a type compatible with the mapping's key type, and the mapping is
168then asked to create a key/datum pair which maps the subscript to
169the assigned object. This can either replace an existing key/value
170pair with the same key value, or insert a new key/value pair (if no
171key with the same value existed).
172\obindex{mapping}
173\obindex{dictionary}
174
175\item
176If the target is a slicing: The primary expression in the reference is
177evaluated. It should yield a mutable sequence object (e.g. a list). The
178assigned object should be a sequence object of the same type. Next,
179the lower and upper bound expressions are evaluated, insofar they are
180present; defaults are zero and the sequence's length. The bounds
181should evaluate to (small) integers. If either bound is negative, the
182sequence's length is added to it. The resulting bounds are clipped to
183lie between zero and the sequence's length, inclusive. Finally, the
184sequence object is asked to replace the slice with the items of the
185assigned sequence. The length of the slice may be different from the
186length of the assigned sequence, thus changing the length of the
187target sequence, if the object allows it.
188\indexii{slicing}{assignment}
189
190\end{itemize}
191
192(In the current implementation, the syntax for targets is taken
193to be the same as for expressions, and invalid syntax is rejected
194during the code generation phase, causing less detailed error
195messages.)
196
197WARNING: Although the definition of assignment implies that overlaps
198between the left-hand side and the right-hand side are `safe' (e.g.
Fred Drakedde91f01998-05-06 20:59:46 +0000199\code{a, b = b, a} swaps two variables), overlaps within the
Fred Drakef6669171998-05-06 19:52:49 +0000200collection of assigned-to variables are not safe! For instance, the
Fred Drakedde91f01998-05-06 20:59:46 +0000201following program prints \code{[0, 2]}:
Fred Drakef6669171998-05-06 19:52:49 +0000202
203\begin{verbatim}
204x = [0, 1]
205i = 0
206i, x[i] = 1, 2
207print x
208\end{verbatim}
209
210
Fred Drakedde91f01998-05-06 20:59:46 +0000211\section{The \keyword{pass} statement}
Fred Drakef6669171998-05-06 19:52:49 +0000212\stindex{pass}
213
214\begin{verbatim}
215pass_stmt: "pass"
216\end{verbatim}
217
218\keyword{pass} is a null operation --- when it is executed, nothing
219happens. It is useful as a placeholder when a statement is
220required syntactically, but no code needs to be executed, for example:
221\indexii{null}{operation}
222
223\begin{verbatim}
224def f(arg): pass # a function that does nothing (yet)
225
226class C: pass # a class with no methods (yet)
227\end{verbatim}
228
Fred Drakedde91f01998-05-06 20:59:46 +0000229\section{The \keyword{del} statement}
Fred Drakef6669171998-05-06 19:52:49 +0000230\stindex{del}
231
232\begin{verbatim}
233del_stmt: "del" target_list
234\end{verbatim}
235
236Deletion is recursively defined very similar to the way assignment is
237defined. Rather that spelling it out in full details, here are some
238hints.
239\indexii{deletion}{target}
240\indexiii{deletion}{target}{list}
241
242Deletion of a target list recursively deletes each target, from left
243to right.
244
245Deletion of a name removes the binding of that name (which must exist)
246from the local or global name space, depending on whether the name
247occurs in a \keyword{global} statement in the same code block.
248\stindex{global}
249\indexii{unbinding}{name}
250
251Deletion of attribute references, subscriptions and slicings
252is passed to the primary object involved; deletion of a slicing
253is in general equivalent to assignment of an empty slice of the
254right type (but even this is determined by the sliced object).
255\indexii{attribute}{deletion}
256
Fred Drakedde91f01998-05-06 20:59:46 +0000257\section{The \keyword{print} statement} \label{print}
Fred Drakef6669171998-05-06 19:52:49 +0000258\stindex{print}
259
260\begin{verbatim}
261print_stmt: "print" [ condition ("," condition)* [","] ]
262\end{verbatim}
263
264\keyword{print} evaluates each condition in turn and writes the resulting
265object to standard output (see below). If an object is not a string,
266it is first converted to a string using the rules for string
267conversions. The (resulting or original) string is then written. A
268space is written before each object is (converted and) written, unless
269the output system believes it is positioned at the beginning of a
270line. This is the case: (1) when no characters have yet been written
271to standard output; or (2) when the last character written to standard
Fred Drakedde91f01998-05-06 20:59:46 +0000272output is \character{\\n}; or (3) when the last write operation on standard
Fred Drakef6669171998-05-06 19:52:49 +0000273output was not a \keyword{print} statement. (In some cases it may be
274functional to write an empty string to standard output for this
275reason.)
276\index{output}
277\indexii{writing}{values}
278
Fred Drakedde91f01998-05-06 20:59:46 +0000279A \character{\\n} character is written at the end, unless the \keyword{print}
Fred Drakef6669171998-05-06 19:52:49 +0000280statement ends with a comma. This is the only action if the statement
281contains just the keyword \keyword{print}.
282\indexii{trailing}{comma}
283\indexii{newline}{suppression}
284
Fred Drakedde91f01998-05-06 20:59:46 +0000285Standard output is defined as the file object named \code{stdout}
286in the built-in module \module{sys}. If no such object exists,
Fred Drakef6669171998-05-06 19:52:49 +0000287or if it is not a writable file, a \exception{RuntimeError} exception is raised.
288(The original implementation attempts to write to the system's original
289standard output instead, but this is not safe, and should be fixed.)
290\indexii{standard}{output}
291\refbimodindex{sys}
292\ttindex{stdout}
293\exindex{RuntimeError}
294
Fred Drakedde91f01998-05-06 20:59:46 +0000295\section{The \keyword{return} statement}
Fred Drakef6669171998-05-06 19:52:49 +0000296\stindex{return}
297
298\begin{verbatim}
299return_stmt: "return" [condition_list]
300\end{verbatim}
301
302\keyword{return} may only occur syntactically nested in a function
303definition, not within a nested class definition.
304\indexii{function}{definition}
305\indexii{class}{definition}
306
307If a condition list is present, it is evaluated, else \code{None}
308is substituted.
309
310\keyword{return} leaves the current function call with the condition
311list (or \code{None}) as return value.
312
313When \keyword{return} passes control out of a \keyword{try} statement
314with a finally clause, that finally clause is executed
315before really leaving the function.
316\kwindex{finally}
317
Fred Drakedde91f01998-05-06 20:59:46 +0000318\section{The \keyword{raise} statement}
Fred Drakef6669171998-05-06 19:52:49 +0000319\stindex{raise}
320
321\begin{verbatim}
322raise_stmt: "raise" condition ["," condition ["," condition]]
323\end{verbatim}
324
325\keyword{raise} evaluates its first condition, which must yield
326a string, class, or instance object. If there is a second condition,
327this is evaluated, else \code{None} is substituted. If the first
328condition is a class object, then the second condition must be an
329instance of that class or one of its derivatives. If the first
330condition is an instance object, the second condition must be
331\code{None}.
332\index{exception}
333\indexii{raising}{exception}
334
335If the first object is a class or string, it then raises the exception
336identified by the first object, with the second one (or \code{None})
337as its parameter. If the first object is an instance, it raises the
338exception identified by the class of the object, with the instance as
339its parameter (and there should be no second object, or the second
340object should be \code{None}).
341
342If a third object is present, and it it not \code{None}, it should be
343a traceback object (see section \ref{traceback}), and it is
344substituted instead of the current location as the place where the
345exception occurred. This is useful to re-raise an exception
346transparently in an except clause.
347\obindex{traceback}
348
Fred Drakedde91f01998-05-06 20:59:46 +0000349\section{The \keyword{break} statement}
Fred Drakef6669171998-05-06 19:52:49 +0000350\stindex{break}
351
352\begin{verbatim}
353break_stmt: "break"
354\end{verbatim}
355
356\keyword{break} may only occur syntactically nested in a \keyword{for}
357or \keyword{while} loop, but not nested in a function or class definition
358within that loop.
359\stindex{for}
360\stindex{while}
361\indexii{loop}{statement}
362
363It terminates the nearest enclosing loop, skipping the optional
364else clause if the loop has one.
365\kwindex{else}
366
367If a \keyword{for} loop is terminated by \keyword{break}, the loop control
368target keeps its current value.
369\indexii{loop control}{target}
370
371When \keyword{break} passes control out of a \keyword{try} statement
372with a finally clause, that finally clause is executed
373before really leaving the loop.
374\kwindex{finally}
375
Fred Drakedde91f01998-05-06 20:59:46 +0000376\section{The \keyword{continue} statement}
Fred Drakef6669171998-05-06 19:52:49 +0000377\stindex{continue}
378
379\begin{verbatim}
380continue_stmt: "continue"
381\end{verbatim}
382
383\keyword{continue} may only occur syntactically nested in a \keyword{for} or
384\keyword{while} loop, but not nested in a function or class definition or
385\keyword{try} statement within that loop.\footnote{Except that it may
Fred Drakedde91f01998-05-06 20:59:46 +0000386currently occur within an except clause.}
Fred Drakef6669171998-05-06 19:52:49 +0000387\stindex{for}
388\stindex{while}
389\indexii{loop}{statement}
390\kwindex{finally}
391
392It continues with the next cycle of the nearest enclosing loop.
393
Fred Drakedde91f01998-05-06 20:59:46 +0000394\section{The \keyword{import} statement} \label{import}
Fred Drakef6669171998-05-06 19:52:49 +0000395\stindex{import}
396
397\begin{verbatim}
398import_stmt: "import" identifier ("," identifier)*
399 | "from" identifier "import" identifier ("," identifier)*
400 | "from" identifier "import" "*"
401\end{verbatim}
402
403Import statements are executed in two steps: (1) find a module, and
404initialize it if necessary; (2) define a name or names in the local
405name space (of the scope where the \keyword{import} statement occurs).
406The first form (without \keyword{from}) repeats these steps for each
407identifier in the list, the \keyword{from} form performs them once, with
408the first identifier specifying the module name.
409\indexii{importing}{module}
410\indexii{name}{binding}
411\kwindex{from}
412
413The system maintains a table of modules that have been initialized,
414indexed by module name. (The current implementation makes this table
415accessible as \code{sys.modules}.) When a module name is found in
416this table, step (1) is finished. If not, a search for a module
417definition is started. This first looks for a built-in module
418definition, and if no built-in module if the given name is found, it
419searches a user-specified list of directories for a file whose name is
420the module name with extension \file{.py}. (The current
421implementation uses the list of strings \code{sys.path} as the search
422path; it is initialized from the shell environment variable
423\envvar{PYTHONPATH}, with an installation-dependent default.)
424\ttindex{modules}
425\ttindex{sys.modules}
426\indexii{module}{name}
427\indexii{built-in}{module}
428\indexii{user-defined}{module}
429\refbimodindex{sys}
Fred Drakef6669171998-05-06 19:52:49 +0000430\indexii{filename}{extension}
Fred Drakedde91f01998-05-06 20:59:46 +0000431\indexiii{module}{search}{path}
Fred Drakef6669171998-05-06 19:52:49 +0000432
433If a built-in module is found, its built-in initialization code is
434executed and step (1) is finished. If no matching file is found,
435\exception{ImportError} is raised. If a file is found, it is parsed,
436yielding an executable code block. If a syntax error occurs,
437\exception{SyntaxError} is raised. Otherwise, an empty module of the given
438name is created and inserted in the module table, and then the code
439block is executed in the context of this module. Exceptions during
440this execution terminate step (1).
441\indexii{module}{initialization}
442\exindex{SyntaxError}
443\exindex{ImportError}
444\index{code block}
445
446When step (1) finishes without raising an exception, step (2) can
447begin.
448
449The first form of \keyword{import} statement binds the module name in the
450local name space to the module object, and then goes on to import the
451next identifier, if any. The \keyword{from} from does not bind the
452module name: it goes through the list of identifiers, looks each one
453of them up in the module found in step (1), and binds the name in the
454local name space to the object thus found. If a name is not found,
455\exception{ImportError} is raised. If the list of identifiers is replaced
Fred Drakedde91f01998-05-06 20:59:46 +0000456by a star (\code{*}), all names defined in the module are bound,
457except those beginning with an underscore(\code{_}).
Fred Drakef6669171998-05-06 19:52:49 +0000458\indexii{name}{binding}
459\exindex{ImportError}
460
461Names bound by import statements may not occur in \keyword{global}
462statements in the same scope.
463\stindex{global}
464
Fred Drakedde91f01998-05-06 20:59:46 +0000465The \keyword{from} form with \code{*} may only occur in a module scope.
Fred Drakef6669171998-05-06 19:52:49 +0000466\kwindex{from}
467\ttindex{from ... import *}
468
469(The current implementation does not enforce the latter two
470restrictions, but programs should not abuse this freedom, as future
471implementations may enforce them or silently change the meaning of the
472program.)
473
Fred Drakedde91f01998-05-06 20:59:46 +0000474\section{The \keyword{global} statement} \label{global}
Fred Drakef6669171998-05-06 19:52:49 +0000475\stindex{global}
476
477\begin{verbatim}
478global_stmt: "global" identifier ("," identifier)*
479\end{verbatim}
480
481The \keyword{global} statement is a declaration which holds for the
482entire current code block. It means that the listed identifiers are to be
Fred Drakedde91f01998-05-06 20:59:46 +0000483interpreted as globals. While \emph{using} global names is automatic
484if they are not defined in the local scope, \emph{assigning} to global
Fred Drakef6669171998-05-06 19:52:49 +0000485names would be impossible without \keyword{global}.
486\indexiii{global}{name}{binding}
487
488Names listed in a \keyword{global} statement must not be used in the same
489code block before that \keyword{global} statement is executed.
490
491Names listed in a \keyword{global} statement must not be defined as formal
492parameters or in a \keyword{for} loop control target, \keyword{class}
493definition, function definition, or \keyword{import} statement.
494
495(The current implementation does not enforce the latter two
496restrictions, but programs should not abuse this freedom, as future
497implementations may enforce them or silently change the meaning of the
498program.)
499
500Note: the \keyword{global} is a directive to the parser. Therefore, it
501applies only to code parsed at the same time as the \keyword{global}
502statement. In particular, a \keyword{global} statement contained in an
Fred Drakedde91f01998-05-06 20:59:46 +0000503\keyword{exec} statement does not affect the code block \emph{containing}
Fred Drakef6669171998-05-06 19:52:49 +0000504the \keyword{exec} statement, and code contained in an \keyword{exec}
505statement is unaffected by \keyword{global} statements in the code
506containing the \keyword{exec} statement. The same applies to the
507\function{eval()}, \function{execfile()} and \function{compile()} functions.
508\stindex{exec}
509\bifuncindex{eval}
510\bifuncindex{execfile}
511\bifuncindex{compile}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000512
513\section{The {\tt exec} statement} \label{exec}
514\stindex{exec}
515
516\begin{verbatim}
517exec_stmt: "exec" expression ["in" expression ["," expression]]
518\end{verbatim}
519
520This statement supports dynamic execution of Python code. The first
521expression should evaluate to either a string, an open file object, or
522a code object. If it is a string, the string is parsed as a suite of
523Python statements which is then executed (unless a syntax error
524occurs). If it is an open file, the file is parsed until EOF and
525executed. If it is a code object, it is simply executed.
526
527In all cases, if the optional parts are omitted, the code is executed
528in the current scope. If only the first expression after \keyword{in}
529is specified, it should be a dictionary, which will be used for both
530the global and the local variables. If two expressions are given,
531both must be dictionaries and they are used for the global and local
532variables, respectively.
533
534As a side effect, an implementation may insert additional keys into
535the dictionaries given besides those corresponding to variable names
536set by the executed code. For example, the current implementation
537may add a reference to the dictionary of the built-in module
538\module{__builtin__} under the key \code{__builtins__} (!).
539\ttindex{__builtins__}
540\refbimodindex{__builtin__}
541
542Hints: dynamic evaluation of expressions is supported by the built-in
543function \function{eval()}. The built-in functions
544\function{globals()} and \function{locals()} return the current global
545and local dictionary, respectively, which may be useful to pass around
546for use by \keyword{exec}.
547\bifuncindex{eval}
548\bifuncindex{globals}
549\bifuncindex{locals}